Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
(PathSeperators.FSLASH, PathSeperators.FSLASH),
('.', PathSeperators.DOT),
('/', PathSeperators.FSLASH),
])
def test_pretyped_pathsep(pathsep, compare):
parser = Parser(None, pathsep=pathsep)
assert compare == parser.pathsep
def test_seperators_from_str(sep, val):
assert val == PathSeperators.from_str(sep)
("/top_array/2", 42, 1, False, YAMLValueFormats.INT, PathSeperators.FSLASH),
])
def test_set_value(self, quiet_logger, yamlpath, value, tally, mustexist, vformat, pathsep):
yamldata = """---
aliases:
- &testAnchor Initial Value
top_array:
# Comment 1
- 1
# Comment 2
- 2
# Comment N
top_scalar: Top-level plain scalar string
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
default=False
* default_value (Any) The value to set at yaml_path should
it not already exist in data and mustexist is False;
default=None
* pathsep (PathSeperators) Forced YAML Path segment seperator; set
only when automatic inference fails;
default = PathSeperators.AUTO
Returns: (Generator) The requested YAML nodes as they are matched
Raises:
- `YAMLPathException` when YAML Path is invalid
"""
mustexist: bool = kwargs.pop("mustexist", False)
default_value: Any = kwargs.pop("default_value", None)
pathsep: PathSeperators = kwargs.pop("pathsep", PathSeperators.AUTO)
if self.data is None:
return
if isinstance(yaml_path, str):
yaml_path = YAMLPath(yaml_path, pathsep)
elif pathsep is not PathSeperators.AUTO:
yaml_path.seperator = pathsep
if mustexist:
matched_nodes: int = 0
for node_coords in self._get_required_nodes(self.data, yaml_path):
matched_nodes += 1
self.logger.debug(
"Processor::get_nodes: Relaying required node {}:"
.format(type(node_coords))
def search_for_paths(logger: ConsolePrinter, processor: EYAMLProcessor,
data: Any, terms: SearchTerms,
pathsep: PathSeperators = PathSeperators.DOT,
build_path: str = "",
seen_anchors: Optional[List[str]] = None,
**kwargs: bool) -> Generator[YAMLPath, None, None]:
"""
Recursively search a data structure for nodes matching an expression.
The nodes can be keys, values, and/or elements. When dealing with anchors
and their aliases, the caller indicates whether to include only the
original anchor or the anchor and all of its (duplicate) aliases.
"""
search_values: bool = kwargs.pop("search_values", True)
search_keys: bool = kwargs.pop("search_keys", False)
search_anchors: bool = kwargs.pop("search_anchors", False)
include_key_aliases: bool = kwargs.pop("include_key_aliases", True)
include_value_aliases: bool = kwargs.pop("include_value_aliases", False)
decrypt_eyaml: bool = kwargs.pop("decrypt_eyaml", False)
Returns: (Generator) The requested YAML nodes as they are matched
Raises:
- `YAMLPathException` when YAML Path is invalid
"""
mustexist: bool = kwargs.pop("mustexist", False)
default_value: Any = kwargs.pop("default_value", None)
pathsep: PathSeperators = kwargs.pop("pathsep", PathSeperators.AUTO)
if self.data is None:
return
if isinstance(yaml_path, str):
yaml_path = YAMLPath(yaml_path, pathsep)
elif pathsep is not PathSeperators.AUTO:
yaml_path.seperator = pathsep
if mustexist:
matched_nodes: int = 0
for node_coords in self._get_required_nodes(self.data, yaml_path):
matched_nodes += 1
self.logger.debug(
"Processor::get_nodes: Relaying required node {}:"
.format(type(node_coords))
)
self.logger.debug(node_coords)
yield node_coords
if matched_nodes < 1:
raise YAMLPathException(
"Required YAML Path does not match any nodes",
version="%(prog)s " + MY_VERSION)
required_group = parser.add_argument_group("required settings")
required_group.add_argument(
"-p", "--query",
required=True,
metavar="YAML_PATH",
help="YAML Path to query"
)
parser.add_argument(
"-t", "--pathsep",
default="dot",
choices=PathSeperators,
metavar=PathSeperators.get_choices(),
type=PathSeperators.from_str,
help="indicate which YAML Path seperator to use when rendering\
results; default=dot")
eyaml_group = parser.add_argument_group(
"EYAML options", "Left unset, the EYAML keys will default to your\
system or user defaults. Both keys must be set either here or in\
your system or user EYAML configuration file when using EYAML.")
eyaml_group.add_argument(
"-x", "--eyaml",
default="eyaml",
help="the eyaml binary to use when it isn't on the PATH")
eyaml_group.add_argument("-r", "--privatekey", help="EYAML private key")
eyaml_group.add_argument("-u", "--publickey", help="EYAML public key")
noise_group = parser.add_mutually_exclusive_group()
noise_group.add_argument(
Positional Parameters:
1. logger (ConsoleWriter) Instance of ConsoleWriter or any similar
wrapper (say, around stdlib logging modules)
Optional Parameters:
1. pathsep (string) A PathSeperators value for controlling the YAML
Path seperator
Returns: N/A
Raises: N/A
"""
self.log = logger
pathsep = kwargs.pop("pathsep", "auto")
if isinstance(pathsep, PathSeperators):
self.pathsep = pathsep
else:
try:
self.pathsep = PathSeperators.from_str(pathsep)
except NameError:
raise YAMLPathException(
"Unknown YAML Path seperator, {}.".format(pathsep)
, pathsep
)
search_method: Optional[PathSearchMethods] = None
search_attr: str = ""
seeking_regex_delim: bool = False
capturing_regex: bool = False
pathsep: str = str(self.seperator)
collector_level: int = 0
collector_operator: CollectorOperators = CollectorOperators.NONE
seeking_collector_operator: bool = False
# Empty paths yield empty queues
if not yaml_path:
return path_segments
# Infer the first possible position for a top-level Anchor mark
first_anchor_pos = 0
if self.seperator is PathSeperators.FSLASH and len(yaml_path) > 1:
first_anchor_pos = 1
seeking_anchor_mark = yaml_path[first_anchor_pos] == "&"
# Parse the YAML Path
# pylint: disable=locally-disabled,too-many-nested-blocks
for char in yaml_path:
demarc_count = len(demarc_stack)
if escape_next:
# Pass-through; capture this escaped character
escape_next = False
elif capturing_regex:
if char == demarc_stack[-1]:
# Stop the RegEx capture
capturing_regex = False
"-c", "--check",
help="check the value before replacing it")
parser.add_argument(
"-s", "--saveto", metavar="YAML_PATH",
help="save the old value to YAML_PATH before replacing it; implies\
--mustexist")
parser.add_argument(
"-m", "--mustexist", action="store_true",
help="require that the --change YAML_PATH already exist in YAML_FILE")
parser.add_argument(
"-b", "--backup", action="store_true",
help="save a backup YAML_FILE with an extra .bak file-extension")
parser.add_argument(
"-t", "--pathsep",
default="dot",
choices=PathSeperators,
metavar=PathSeperators.get_choices(),
type=PathSeperators.from_str,
help="indicate which YAML Path seperator to use when rendering\
results; default=dot")
eyaml_group = parser.add_argument_group(
"EYAML options", "Left unset, the EYAML keys will default to your\
system or user defaults. You do not need to supply a private key\
unless you enable --check and the old value is encrypted.")
eyaml_group.add_argument(
"-e", "--eyamlcrypt", action="store_true",
help="encrypt the new value using EYAML")
eyaml_group.add_argument(
"-x", "--eyaml", default="eyaml",
help="the eyaml binary to use when it isn't on the PATH")
eyaml_group.add_argument("-r", "--privatekey", help="EYAML private key")