INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Use ODict for maps
def construct_mapping(self, node, deep=False): """ Use ODict for maps """ mapping = ODict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mappin...
AWS CloudFormation Template Flip is a tool that converts AWS CloudFormation templates between JSON and YAML formats, making use of the YAML format's short function syntax where possible.
def main(ctx, **kwargs): """ AWS CloudFormation Template Flip is a tool that converts AWS CloudFormation templates between JSON and YAML formats, making use of the YAML format's short function syntax where possible. """ in_format = kwargs.pop('in_format') out_format = kwargs.pop('out_format'...
do a full-table scan of the credential-store, and update the version format of every credential if it is an integer
def updateVersions(region="us-east-1", table="credential-store"): ''' do a full-table scan of the credential-store, and update the version format of every credential if it is an integer ''' dynamodb = boto3.resource('dynamodb', region_name=region) secrets = dynamodb.Table(table) response = ...
return a string that contains `i`, left-padded with 0's up to PAD_LEN digits
def paddedInt(i): ''' return a string that contains `i`, left-padded with 0's up to PAD_LEN digits ''' i_str = str(i) pad = PAD_LEN - len(i_str) return (pad * "0") + i_str
Return the highest version of `name` in the table
def getHighestVersion(name, region=None, table="credential-store", **kwargs): ''' Return the highest version of `name` in the table ''' session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region) secrets = dynamodb.Table(table) response...
A decorator to cleanly exit on a failed call to AWS. catch a `botocore.exceptions.ClientError` raised from an action. This sort of error is raised if you are targeting a region that isn't set up (see, `credstash setup`.
def clean_fail(func): ''' A decorator to cleanly exit on a failed call to AWS. catch a `botocore.exceptions.ClientError` raised from an action. This sort of error is raised if you are targeting a region that isn't set up (see, `credstash setup`. ''' def func_wrapper(*args, **kwargs): ...
do a full-table scan of the credential-store, and return the names and versions of every credential
def listSecrets(region=None, table="credential-store", **kwargs): ''' do a full-table scan of the credential-store, and return the names and versions of every credential ''' session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region) secrets = dynamodb.Table(...
put a secret called `name` into the secret-store, protected by the key kms_key
def putSecret(name, secret, version="", kms_key="alias/credstash", region=None, table="credential-store", context=None, digest=DEFAULT_DIGEST, comment="", **kwargs): ''' put a secret called `name` into the secret-store, protected by the key kms_key ''' if not context: ...
fetch and decrypt all secrets
def getAllSecrets(version="", region=None, table="credential-store", context=None, credential=None, session=None, **kwargs): ''' fetch and decrypt all secrets ''' if session is None: session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region)...
fetch and decrypt the secret called `name`
def getSecret(name, version="", region=None, table="credential-store", context=None, dynamodb=None, kms=None, **kwargs): ''' fetch and decrypt the secret called `name` ''' if not context: context = {} # Can we cache if dynamodb is None or kms is None: ...
create the secret store table in DDB in the specified region
def createDdbTable(region=None, table="credential-store", **kwargs): ''' create the secret store table in DDB in the specified region ''' session = get_session(**kwargs) dynamodb = session.resource("dynamodb", region_name=region) if table in (t.name for t in dynamodb.tables.all()): print...
Decrypts secrets stored by `seal_aes_ctr_legacy`. Assumes that the plaintext is unicode (non-binary).
def open_aes_ctr_legacy(key_service, material): """ Decrypts secrets stored by `seal_aes_ctr_legacy`. Assumes that the plaintext is unicode (non-binary). """ key = key_service.decrypt(b64decode(material['key'])) digest_method = material.get('digest', DEFAULT_DIGEST) ciphertext = b64decode(ma...
Encrypts `secret` using the key service. You can decrypt with the companion method `open_aes_ctr_legacy`.
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST): """ Encrypts `secret` using the key service. You can decrypt with the companion method `open_aes_ctr_legacy`. """ # generate a a 64 byte key. # Half will be for data encryption, the other half for HMAC key, encoded_k...
get the parsers dict
def get_parser(): """get the parsers dict""" parsers = {} parsers['super'] = argparse.ArgumentParser( description="A credential/secret storage system") parsers['super'].add_argument("-r", "--region", help="the AWS region in which to operate. " ...
Check RabbitMQ service by opening and closing a broker channel.
def check_status(self): """Check RabbitMQ service by opening and closing a broker channel.""" logger.debug("Checking for a broker_url on django settings...") broker_url = getattr(settings, "BROKER_URL", None) logger.debug("Got %s as the broker_url. Connecting to rabbit...", broker_url)...
Return single instance parsed from given accept header string.
def from_string(cls, value): """Return single instance parsed from given accept header string.""" match = cls.pattern.search(value) if match is None: raise ValueError('"%s" is not a valid media type' % value) try: return cls(match.group('mime_type'), float(match.g...
Parse HTTP accept header and return instances sorted by weight.
def parse_header(cls, value='*/*'): """Parse HTTP accept header and return instances sorted by weight.""" yield from sorted(( cls.from_string(token.strip()) for token in value.split(',') if token.strip() ), reverse=True)
Converts a potentially timezone-aware datetime to be a naive UTC datetime
def convert_to_timezone_naive(time_to_freeze): """ Converts a potentially timezone-aware datetime to be a naive UTC datetime """ if time_to_freeze.tzinfo: time_to_freeze -= time_to_freeze.utcoffset() time_to_freeze = time_to_freeze.replace(tzinfo=None) return time_to_freeze
Parses all the possible inputs for freeze_time :returns: a naive ``datetime.datetime`` object
def _parse_time_to_freeze(time_to_freeze_str): """Parses all the possible inputs for freeze_time :returns: a naive ``datetime.datetime`` object """ if time_to_freeze_str is None: time_to_freeze_str = datetime.datetime.utcnow() if isinstance(time_to_freeze_str, datetime.datetime): ti...
Moves frozen date to the given ``target_datetime``
def move_to(self, target_datetime): """Moves frozen date to the given ``target_datetime``""" target_datetime = _parse_time_to_freeze(target_datetime) delta = target_datetime - self.time_to_freeze self.tick(delta=delta)
Main control function. Set up the top-level parts of the stylesheet, then process recursively all nodes in all data trees, and finally emit the serialized stylesheet.
def emit(self, ctx, modules, fd): """Main control function. Set up the top-level parts of the stylesheet, then process recursively all nodes in all data trees, and finally emit the serialized stylesheet. """ for (epos, etag, eargs) in ctx.errors: if error.is_...
Process data nodes, RPCs and notifications in a single module.
def process_module(self, yam): """Process data nodes, RPCs and notifications in a single module.""" for ann in yam.search(("ietf-yang-metadata", "annotation")): self.process_annotation(ann) for ch in yam.i_children[:]: if ch.keyword == "rpc": self.process_...
Process metadata annotation.
def process_annotation(self, ann): """Process metadata annotation.""" tmpl = self.xsl_template("@" + self.qname(ann)) ET.SubElement(tmpl, "param", name="level", select="0") ct = self.xsl_calltemplate("leaf", tmpl) ET.SubElement(ct, "with-param", name="level", select="$level") ...
Process input and output parts of `rpc`.
def process_rpc(self, rpc): """Process input and output parts of `rpc`.""" p = "/nc:rpc/" + self.qname(rpc) tmpl = self.xsl_template(p) inp = rpc.search_one("input") if inp is not None: ct = self.xsl_calltemplate("rpc-input", tmpl) self.xsl_withparam("nsid...
Process event notification `ntf`.
def process_notification(self, ntf): """Process event notification `ntf`.""" p = "/en:notification/" + self.qname(ntf) tmpl = self.xsl_template(p) ct = self.xsl_calltemplate("container", tmpl) self.xsl_withparam("level", "1", ct) if ntf.arg == "eventTime": # lo...
Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates.
def process_children(self, node, path, level, parent=None): """Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates. """ data_parent = parent if parent else node chs = node.i_children for ch in ch...
Resolve the type of a leaf or leaf-list node for JSON.
def type_param(self, node, ct): """Resolve the type of a leaf or leaf-list node for JSON. """ types = self.get_types(node) ftyp = types[0] if len(types) == 1: if ftyp in type_class: jtyp = type_class[ftyp] else: jtyp = "othe...
Construct an XSLT 'text' element containing `text`. `parent` is this element's parent.
def xsl_text(self, text, parent): """Construct an XSLT 'text' element containing `text`. `parent` is this element's parent. """ res = ET.SubElement(parent, "text") res.text = text return res
Construct an XSLT 'with-param' element. `parent` is this element's parent. `name` is the parameter name. `value` is the parameter value.
def xsl_withparam(self, name, value, parent): """Construct an XSLT 'with-param' element. `parent` is this element's parent. `name` is the parameter name. `value` is the parameter value. """ res = ET.SubElement(parent, "with-param", name=name) res.text = value ...
Called by pyang plugin framework at to initialize the plugin.
def pyang_plugin_init(): """Called by pyang plugin framework at to initialize the plugin.""" # Register the plugin plugin.register_plugin(SMIPlugin()) # Add our special argument syntax checkers syntax.add_arg_type('smi-oid', _chk_smi_oid) syntax.add_arg_type('smi-max-access', _chk_smi_max_acce...
Create an element node.
def element(cls, name, parent=None, interleave=None, occur=0): """Create an element node.""" node = cls("element", parent, interleave=interleave) node.attr["name"] = name node.occur = occur return node
Create _list_ node for a leaf-list.
def leaf_list(cls, name, parent=None, interleave=None): """Create _list_ node for a leaf-list.""" node = cls("_list_", parent, interleave=interleave) node.attr["name"] = name node.keys = None node.minEl = "0" node.maxEl = None node.occur = 3 return node
Create _list_ node for a list.
def list(cls, name, parent=None, interleave=None): """Create _list_ node for a list.""" node = cls.leaf_list(name, parent, interleave=interleave) node.keys = [] node.keymap = {} return node
Create choice node.
def choice(cls, parent=None, occur=0): """Create choice node.""" node = cls("choice", parent) node.occur = occur node.default_case = None return node
Create define node.
def define(cls, name, parent=None, interleave=False): """Create define node.""" node = cls("define", parent, interleave=interleave) node.occur = 0 node.attr["name"] = name return node
Inherit interleave status from parent if undefined.
def adjust_interleave(self, interleave): """Inherit interleave status from parent if undefined.""" if interleave == None and self.parent: self.interleave = self.parent.interleave else: self.interleave = interleave
Make `node` receiver's child.
def subnode(self, node): """Make `node` receiver's child.""" self.children.append(node) node.parent = self node.adjust_interleave(node.interleave)
Add `node` as an annotation of the receiver.
def annot(self, node): """Add `node` as an annotation of the receiver.""" self.annots.append(node) node.parent = self
Return XML start tag for the receiver.
def start_tag(self, alt=None, empty=False): """Return XML start tag for the receiver.""" if alt: name = alt else: name = self.name result = "<" + name for it in self.attr: result += ' %s="%s"' % (it, escape(self.attr[it], {'"':"&quot;", '%': "%...
Return XML end tag for the receiver.
def end_tag(self, alt=None): """Return XML end tag for the receiver.""" if alt: name = alt else: name = self.name return "</" + name + ">"
Return RELAX NG representation of the receiver and subtree.
def serialize(self, occur=None): """Return RELAX NG representation of the receiver and subtree. """ fmt = self.ser_format.get(self.name, SchemaNode._default_format) return fmt(self, occur) % (escape(self.text) + self.serialize_children())
Return the default serialization format.
def _default_format(self, occur): """Return the default serialization format.""" if self.text or self.children: return self.start_tag() + "%s" + self.end_tag() return self.start_tag(empty=True)
Return the serialization format for a define node.
def _define_format(self, occur): """Return the serialization format for a define node.""" if hasattr(self, "default"): self.attr["nma:default"] = self.default middle = self._chorder() if self.rng_children() else "<empty/>%s" return (self.start_tag() + self.serialize_annots()...
Return the serialization format for an element node.
def _element_format(self, occur): """Return the serialization format for an element node.""" if occur: occ = occur else: occ = self.occur if occ == 1: if hasattr(self, "default"): self.attr["nma:default"] = self.default els...
Add <interleave> if child order is arbitrary.
def _chorder(self): """Add <interleave> if child order is arbitrary.""" if (self.interleave and len([ c for c in self.children if ":" not in c.name ]) > 1): return "<interleave>%s</interleave>" return "%s"
Return the serialization format for a _list_ node.
def _list_format(self, occur): """Return the serialization format for a _list_ node.""" if self.keys: self.attr["nma:key"] = " ".join(self.keys) keys = ''.join([self.keymap[k].serialize(occur=2) for k in self.keys]) else: keys = ""...
Return the serialization format for a choice node.
def _choice_format(self, occur): """Return the serialization format for a choice node.""" middle = "%s" if self.rng_children() else "<empty/>%s" fmt = self.start_tag() + middle + self.end_tag() if self.occur != 2: return "<optional>" + fmt + "</optional>" else: ...
Return the serialization format for a case node.
def _case_format(self, occur): """Return the serialization format for a case node.""" if self.occur == 1: self.attr["nma:implicit"] = "true" ccnt = len(self.rng_children()) if ccnt == 0: return "<empty/>%s" if ccnt == 1 or not self.interleave: return self...
Main control function.
def emit(self, ctx, modules, fd): """Main control function. """ for (epos, etag, eargs) in ctx.errors: if error.is_error(error.err_level(etag)): raise error.EmitError("JTOX plugin needs a valid module") tree = {} mods = {} annots = {} f...
Process all children of `node`, except "rpc" and "notification".
def process_children(self, node, parent, pmod): """Process all children of `node`, except "rpc" and "notification". """ for ch in node.i_children: if ch.keyword in ["rpc", "notification"]: continue if ch.keyword in ["choice", "case"]: self.process_children...
Return the base type of `type`.
def base_type(self, type): """Return the base type of `type`.""" while 1: if type.arg == "leafref": node = type.i_type_spec.i_target_node elif type.i_typedef is None: break else: node = type.i_typedef type = ...
Should be called by any derived plugin's setup_ctx() function.
def _setup_ctx(self, ctx): "Should be called by any derived plugin's setup_ctx() function." ctx.strict = True ctx.canonical = True ctx.max_identifier_len = 64 ctx.implicit_errors = False # always add additional prefixes given on the command line self.namespace_p...
Skip whitespace and count position
def skip(self): """Skip whitespace and count position""" buflen = len(self.buf) while True: self.buf = self.buf.lstrip() if self.buf == '': self.readline() buflen = len(self.buf) else: self.offset += (buflen - l...
ret: string()
def get_comment(self): """ret: string()""" self.skip() offset = self.offset m = syntax.re_comment.match(self.buf) if m == None: return None else: cmt = m.group(0) self.set_buf(m.end()) # look for a multiline comment ...
ret: identifier | (prefix, identifier)
def get_keyword(self): """ret: identifier | (prefix, identifier)""" self.skip() m = syntax.re_keyword.match(self.buf) if m == None: error.err_add(self.errors, self.pos, 'SYNTAX_ERROR', 'illegal keyword: ' + self.buf) raise error.Abort ...
ret: string
def get_strings(self, need_quote=False): """ret: string""" self.skip() if self.buf[0] == ';' or self.buf[0] == '{' or self.buf[0] == '}': error.err_add(self.errors, self.pos, 'EXPECTED_ARGUMENT', self.buf[0]) raise error.Abort if self.bu...
Parse the string `text` containing a YANG statement. Return a Statement on success or None on failure
def parse(self, ctx, ref, text): """Parse the string `text` containing a YANG statement. Return a Statement on success or None on failure """ self.ctx = ctx self.pos = error.Position(ref) self.top = None try: self.tokenizer = YangTokenizer(text, self...
Add a validation phase to the framework. Can be used by plugins to do special validation of extensions.
def add_validation_phase(phase, before=None, after=None): """Add a validation phase to the framework. Can be used by plugins to do special validation of extensions.""" idx = 0 for x in _validation_phases: if x == before: _validation_phases.insert(idx, phase) return ...
Add a validation function to some phase in the framework. Function `f` is called for each valid occurance of each keyword in `keywords`. Can be used by plugins to do special validation of extensions.
def add_validation_fun(phase, keywords, f): """Add a validation function to some phase in the framework. Function `f` is called for each valid occurance of each keyword in `keywords`. Can be used by plugins to do special validation of extensions.""" for keyword in keywords: if (phase, keywo...
Add an element to the <keyword>'s list of refinements
def add_refinement_element(keyword, element, merge = False, v_fun=None): """Add an element to the <keyword>'s list of refinements""" for (key, valid_keywords, m, v_fun) in _refinements: if key == keyword: valid_keywords.append(element) return _refinements.append((keyword, [el...
Add an element to the <keyword>'s list of deviations. Can be used by plugins that add support for specific extension statements.
def add_deviation_element(keyword, element): """Add an element to the <keyword>'s list of deviations. Can be used by plugins that add support for specific extension statements.""" if keyword in _valid_deviations: _valid_deviations[keyword].append(element) else: _valid_deviations[keyword] = [eleme...
Validate `module`, which is a Statement representing a (sub)module
def validate_module(ctx, module): """Validate `module`, which is a Statement representing a (sub)module""" if module.i_is_validated: return def iterate(stmt, phase): # if the grammar is not yet checked or if it is checked and # valid, then we continue. if (hasattr(stmt, 'is...
find the modulename of the prefix, and set `stmt.keyword`
def v_init_extension(ctx, stmt): """find the modulename of the prefix, and set `stmt.keyword`""" (prefix, identifier) = stmt.raw_keyword (modname, revision) = \ prefix_to_modulename_and_revision(stmt.i_module, prefix, stmt.pos, ctx.errors) stmt.keyword =...
Verify that all typedefs and groupings are unique Called for every statement. Stores all typedefs in stmt.i_typedef, groupings in stmt.i_grouping
def v_grammar_unique_defs(ctx, stmt): """Verify that all typedefs and groupings are unique Called for every statement. Stores all typedefs in stmt.i_typedef, groupings in stmt.i_grouping """ defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFI...
verify that the extension matches the extension definition
def v_type_extension(ctx, stmt): """verify that the extension matches the extension definition""" (modulename, identifier) = stmt.keyword revision = stmt.i_extension_revision module = modulename_to_module(stmt.i_module, modulename, revision) if module is None: return if identifier not in...
verify that the referenced feature exists.
def v_type_if_feature(ctx, stmt, no_error_report=False): """verify that the referenced feature exists.""" stmt.i_feature = None # Verify the argument type expr = syntax.parse_if_feature_expr(stmt.arg) if stmt.i_module.i_version == '1': # version 1 allows only a single value as if-feature ...
verify that the referenced identity exists.
def v_type_base(ctx, stmt, no_error_report=False): """verify that the referenced identity exists.""" # Find the identity name = stmt.arg stmt.i_identity = None if name.find(":") == -1: prefix = None else: [prefix, name] = name.split(':', 1) if prefix is None or stmt.i_module....
One-pass augment expansion algorithm: First observation: since we validate each imported module, all nodes that are augmented by other modules already exist. For each node in the path to the target node, if it does not exist, it might get created by an augment later in this module. This only applies t...
def v_expand_2_augment(ctx, stmt): """ One-pass augment expansion algorithm: First observation: since we validate each imported module, all nodes that are augmented by other modules already exist. For each node in the path to the target node, if it does not exist, it might get created by an aug...
Make sure that all top-level definitions in a module are unique
def v_unique_name_defintions(ctx, stmt): """Make sure that all top-level definitions in a module are unique""" defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFINED', stmt.i_groupings)] def f(s): for (keyword, errcode, dict) in defs: ...
Make sure that each child of stmt has a unique name
def v_unique_name_children(ctx, stmt): """Make sure that each child of stmt has a unique name""" def sort_pos(p1, p2): if p1.line < p2.line: return (p1,p2) else: return (p2,p1) dict = {} chs = stmt.i_children def check(c): key = (c.i_module.i_module...
Make sure config true leaf-lists do nothave duplicate defaults
def v_unique_name_leaf_list(ctx, stmt): """Make sure config true leaf-lists do nothave duplicate defaults""" if not stmt.i_config: return seen = [] for defval in stmt.i_default: if defval in seen: err_add(ctx.errors, stmt.pos, 'DUPLICATE_DEFAULT', (defval)) else: ...
Make sure that the default case exists
def v_reference_choice(ctx, stmt): """Make sure that the default case exists""" d = stmt.search_one('default') if d is not None: m = stmt.search_one('mandatory') if m is not None and m.arg == 'true': err_add(ctx.errors, stmt.pos, 'DEFAULT_AND_MANDATORY', ()) ptr = attrsea...
Verify that all leafrefs in a leaf or leaf-list have correct path
def v_reference_leaf_leafref(ctx, stmt): """Verify that all leafrefs in a leaf or leaf-list have correct path""" if (hasattr(stmt, 'i_leafref') and stmt.i_leafref is not None and stmt.i_leafref_expanded is False): path_type_spec = stmt.i_leafref not_req_inst = not(path_type_spec...
Return type with name if `type` has name as one of its base types, and name is in the `names` list. otherwise, return None.
def has_type(type, names): """Return type with name if `type` has name as one of its base types, and name is in the `names` list. otherwise, return None.""" if type.arg in names: return type for t in type.search('type'): # check all union's member types r = has_type(t, names) if...
Search for a typedef in scope First search the hierarchy, then the module and its submodules.
def search_typedef(stmt, name): """Search for a typedef in scope First search the hierarchy, then the module and its submodules.""" mod = stmt.i_orig_module while stmt is not None: if name in stmt.i_typedefs: t = stmt.i_typedefs[name] if (mod is not None and ...
Check that the tgt's submodule is included by src, if they belong to the same module.
def is_submodule_included(src, tgt): """Check that the tgt's submodule is included by src, if they belong to the same module.""" if tgt is None or not hasattr(tgt, 'i_orig_module'): return True if (tgt.i_orig_module.keyword == 'submodule' and src.i_orig_module != tgt.i_orig_module and ...
Search for a grouping in scope First search the hierarchy, then the module and its submodules.
def search_grouping(stmt, name): """Search for a grouping in scope First search the hierarchy, then the module and its submodules.""" mod = stmt.i_orig_module while stmt is not None: if name in stmt.i_groupings: g = stmt.i_groupings[name] if (mod is not None and ...
Return the leaf that the path points to and the expanded path arg, or None on error.
def validate_leafref_path(ctx, stmt, path_spec, path, accept_non_leaf_target=False, accept_non_config_target=False): """Return the leaf that the path points to and the expanded path arg, or None on error.""" pathpos = path.pos # Unprefixed paths in t...
Derives a list of tuples containing (module name, prefix, xpath) per node in the statement.
def mk_path_list(stmt): """Derives a list of tuples containing (module name, prefix, xpath) per node in the statement. """ resolved_names = [] def resolve_stmt(stmt, resolved_names): if stmt.keyword in ['choice', 'case']: resolve_stmt(stmt.parent, resolved_names) ...
Returns the XPath path of the node. with_prefixes indicates whether or not to prefix every node. prefix_onchange modifies the behavior of with_prefixes and only adds prefixes when the prefix changes mid-XPath. prefix_to_module replaces prefixes with the module name of the prefix. resolve_top_pr...
def mk_path_str(stmt, with_prefixes=False, prefix_onchange=False, prefix_to_module=False, resolve_top_prefix_to_module=False): """Returns the XPath path of the node. with_prefixes indicates whether or not to prefix every node. prefix_onchange ...
Gets the XPath of the statement. Unless qualified=True, does not include prefixes unless the prefix changes mid-XPath. qualified will add a prefix to each node. prefix_to_module will resolve prefixes to module names instead. For RFC 8040, set prefix_to_module=True: /prefix:root/node/prefi...
def get_xpath(stmt, qualified=False, prefix_to_module=False): """Gets the XPath of the statement. Unless qualified=True, does not include prefixes unless the prefix changes mid-XPath. qualified will add a prefix to each node. prefix_to_module will resolve prefixes to module names instead. F...
Gets the qualified, top-level type of the node. This enters the typedef if defined instead of using the prefix to ensure absolute distinction.
def get_qualified_type(stmt): """Gets the qualified, top-level type of the node. This enters the typedef if defined instead of using the prefix to ensure absolute distinction. """ type_obj = stmt.search_one('type') fq_type_name = None if type_obj: if getattr(type_obj, 'i_typedef', No...
Recurses through the typedefs and returns the most primitive YANG type defined.
def get_primitive_type(stmt): """Recurses through the typedefs and returns the most primitive YANG type defined. """ type_obj = stmt.search_one('type') type_name = getattr(type_obj, 'arg', None) typedef_obj = getattr(type_obj, 'i_typedef', None) if typedef_obj: type_name = get_primit...
Return list of receiver's substmts with `keyword`.
def search(self, keyword, children=None, arg=None): """Return list of receiver's substmts with `keyword`. """ if children is None: children = self.substmts return [ ch for ch in children if (ch.keyword == keyword and (arg is None or ch.ar...
Return receiver's substmt with `keyword` and optionally `arg`.
def search_one(self, keyword, arg=None, children=None): """Return receiver's substmt with `keyword` and optionally `arg`. """ if children is None: children = self.substmts for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): ...
Return the main module to which the receiver belongs.
def main_module(self): """Return the main module to which the receiver belongs.""" if self.i_module.keyword == "submodule": return self.i_module.i_ctx.get_module( self.i_module.i_including_modulename) return self.i_module
debug function
def pprint(self, indent='', f=None): """debug function""" if self.arg is not None: print(indent + util.keyword_to_str(self.keyword) + " " + self.arg) else: print(indent + util.keyword_to_str(self.keyword)) if f is not None: f(self, indent) for x i...
Add `prefix` to all unprefixed names in `s`
def add_prefix(prefix, s): "Add `prefix` to all unprefixed names in `s`" # tokenize the XPath expression toks = xpath_lexer.scan(s) # add default prefix to unprefixed names toks2 = [_add_prefix(prefix, tok) for tok in toks] # build a string of the patched expression ls = [x.value for x in to...
Checks if the string `s` is a valid date string. Return True of False.
def chk_date_arg(s): """Checks if the string `s` is a valid date string. Return True of False.""" if re_date.search(s) is None: return False comp = s.split('-') try: dt = datetime.date(int(comp[0]), int(comp[1]), int(comp[2])) return True except Exception as e: r...
Checks if the string `s` is a valid enum string. Return True or False.
def chk_enum_arg(s): """Checks if the string `s` is a valid enum string. Return True or False.""" if len(s) == 0 or s[0].isspace() or s[-1].isspace(): return False else: return True
Checks if the string `s` is a valid fraction-digits argument. Return True or False.
def chk_fraction_digits_arg(s): """Checks if the string `s` is a valid fraction-digits argument. Return True or False.""" try: v = int(s) if v >= 1 and v <= 18: return True else: return False except ValueError: return False
Add `patch.plist` to `self.plist`.
def combine(self, patch): """Add `patch.plist` to `self.plist`.""" exclusive = set(["config", "default", "mandatory", "presence", "min-elements", "max-elements"]) kws = set([s.keyword for s in self.plist]) & exclusive add = [n for n in patch.plist if n.keyword not in...
Return the string representation of the receiver.
def serialize(self): """Return the string representation of the receiver.""" res = '<?xml version="1.0" encoding="UTF-8"?>' for ns in self.namespaces: self.top_grammar.attr["xmlns:" + self.namespaces[ns]] = ns res += self.top_grammar.start_tag() for ch in self.top_gra...
Return the instance representing mapped input modules.
def from_modules(self, modules, no_dc=False, no_a=False, record_defs=False, lax_yang_version=False, debug=0): """Return the instance representing mapped input modules.""" self.namespaces = { "urn:ietf:params:xml:ns:netmod:dsdl-annotations:1" : "nma", } if...
Create top-level elements of the hybrid schema.
def setup_top(self): """Create top-level elements of the hybrid schema.""" self.top_grammar = SchemaNode("grammar") self.top_grammar.attr = { "xmlns": "http://relaxng.org/ns/structure/1.0", "datatypeLibrary": "http://www.w3.org/2001/XMLSchema-datatypes"} self.tree...
Create the top-level structure for module `yam`.
def create_roots(self, yam): """Create the top-level structure for module `yam`.""" self.local_grammar = SchemaNode("grammar") self.local_grammar.attr = { "ns": yam.search_one("namespace").arg, "nma:module": self.module.arg} src_text = "YANG module '%s'" % yam.arg...
Transform YANG's `xpath` to a form suitable for Schematron. 1. Prefixes are added to unprefixed local names. Inside global groupings, the prefix is represented as the variable '$pref' which is substituted via Schematron abstract patterns. 2. '$root' is prepended to ever...
def yang_to_xpath(self, xpe): """Transform YANG's `xpath` to a form suitable for Schematron. 1. Prefixes are added to unprefixed local names. Inside global groupings, the prefix is represented as the variable '$pref' which is substituted via Schematron abstract patterns...
Add item uri:prefix for `module` to `self.namespaces`. The prefix to be actually used for `uri` is returned. If the namespace is already present, the old prefix is used. Prefix clashes are resolved by disambiguating `prefix`.
def add_namespace(self, module): """Add item uri:prefix for `module` to `self.namespaces`. The prefix to be actually used for `uri` is returned. If the namespace is already present, the old prefix is used. Prefix clashes are resolved by disambiguating `prefix`. """ uri...
Register `id_stmt` with its base identity, if any.
def register_identity(self, id_stmt): """Register `id_stmt` with its base identity, if any. """ bst = id_stmt.search_one("base") if bst: bder = self.identity_deps.setdefault(bst.i_identity, []) bder.append(id_stmt)
Add pattern def for `id_stmt` and all derived identities. The corresponding "ref" pattern is returned.
def add_derived_identity(self, id_stmt): """Add pattern def for `id_stmt` and all derived identities. The corresponding "ref" pattern is returned. """ p = self.add_namespace(id_stmt.main_module()) if id_stmt not in self.identities: # add named pattern def self.iden...