File size: 2,580 Bytes
3ea44ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | """
Resource reference expression parser.
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Jan 31, 2014.
"""
from pyparsing import CaselessKeyword
from pyparsing import Combine
from pyparsing import Group
from pyparsing import Literal
from pyparsing import Word
from pyparsing import ZeroOrMore
from pyparsing import alphanums
from pyparsing import alphas
from pyparsing import delimitedList
from pyparsing import replaceWith
from everest.constants import ResourceReferenceRepresentationKinds
from everest.entities.utils import identifier_from_slug
from everest.representers.config import IGNORE_OPTION
from everest.representers.config import WRITE_AS_LINK_OPTION
__docformat__ = 'reStructuredText en'
__all__ = ['parse_refs',
]
TILDE_PAT = '~'
URL_PAT = ResourceReferenceRepresentationKinds.URL
INLINE_PAT = ResourceReferenceRepresentationKinds.INLINE
OFF_PAT = ResourceReferenceRepresentationKinds.OFF
URL = CaselessKeyword("url").setParseAction(replaceWith(URL_PAT))
INLINE = CaselessKeyword("inline").setParseAction(replaceWith(INLINE_PAT))
OFF = CaselessKeyword("off").setParseAction(replaceWith(OFF_PAT))
class RefsConverter(object):
"""
Converter for a sequence of resource references.
"""
@classmethod
def convert(cls, toks):
config = {}
for rf in toks:
config.update(cls.__convert_ref(rf))
return config
@classmethod
def __convert_ref(cls, rf):
names = [identifier_from_slug(token)
for token in rf.attribute.split('.')]
config = {}
# First, make sure that all parent attributes are configured INLINE.
for idx in range(len(names[:-1])):
key = tuple(names[:idx + 1])
config[key] = {IGNORE_OPTION:False,
WRITE_AS_LINK_OPTION:False}
is_off = rf.option == OFF_PAT
opts = {IGNORE_OPTION:is_off}
if not is_off:
opts[WRITE_AS_LINK_OPTION] = rf.option == URL_PAT
config[tuple(names)] = opts
return config
colon = Literal(':')
attribute = Word(alphas, alphanums + '-')
identifier = \
Combine(attribute + ZeroOrMore('.' + attribute)).setName('identifier')
option = (URL | INLINE | OFF)
ref = Group(identifier('attribute')
+ colon.suppress()
+ option('option'))
refs = delimitedList(ref, delim=TILDE_PAT)
refs.setParseAction(RefsConverter.convert)
def parse_refs(refs_string):
return refs.parseString(refs_string)[0]
|