func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def run_step(context):
logger.debug("started")
(pipeline_name,
use_parent_context,
pipe_arg,
skip_parse,
raise_error,
loader,
) = get_arguments(context)
try:
if use_parent_context:
logger.info(f"pyping {pipeline_name}, using parent context.")
... | Run another pipeline from this step.
The parent pipeline is the current, executing pipeline. The invoked, or
child pipeline is the pipeline you are calling from this step.
Args:
context: dictionary-like pypyr.context.Context. context is mandatory.
Uses the following context keys i... |
def get_arguments(context):
context.assert_key_has_value(key='pype', caller=__name__)
pype = context.get_formatted('pype')
try:
pipeline_name = pype['name']
if pipeline_name is None:
raise KeyInContextHasNoValueError(
"pypyr.steps.pype ['pype']['name'] exists... | Parse arguments for pype from context and assign default values.
Args:
context: pypyr.context.Context. context is mandatory.
Returns:
tuple (pipeline_name, #str
use_parent_context, #bool
pipe_arg, #str
skip_parse, #bool
raise_error #b... |
def get_pipeline_path(pipeline_name, working_directory):
logger.debug("starting")
# look for name.yaml in the pipelines/ sub-directory
logger.debug(f"current directory is {working_directory}")
# looking for {cwd}/pipelines/[pipeline_name].yaml
pipeline_path = os.path.abspath(os.path.join(
... | Look for the pipeline in the various places it could be.
First checks the cwd. Then checks pypyr/pipelines dir.
Args:
pipeline_name: string. Name of pipeline to find
working_directory: string. Path in which to look for pipeline_name.yaml
Returns:
Absolute path to the pipeline_name... |
def get_pipeline_definition(pipeline_name, working_dir):
logger.debug("starting")
pipeline_path = get_pipeline_path(
pipeline_name=pipeline_name,
working_directory=working_dir)
logger.debug(f"Trying to open pipeline at path {pipeline_path}")
try:
with open(pipeline_path) as ... | Open and parse the pipeline definition yaml.
Parses pipeline yaml and returns dictionary representing the pipeline.
pipeline_name.yaml should be in the working_dir/pipelines/ directory.
Args:
pipeline_name: string. Name of pipeline. This will be the file-name of
the pipelin... |
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag, node.value) | How to serialize this class back to yaml. |
def get_value(self, context):
if self.value:
return expressions.eval_string(self.value, context)
else:
# Empty input raises cryptic EOF syntax err, this more human
# friendly
raise ValueError('!py string expression is empty. It must be a '
... | Run python eval on the input string. |
def foreach_loop(self, context):
logger.debug("starting")
# Loop decorators only evaluated once, not for every step repeat
# execution.
foreach = context.get_formatted_iterable(self.foreach_items)
foreach_length = len(foreach)
logger.info(f"foreach decorator will... | Run step once for each item in foreach_items.
On each iteration, the invoked step can use context['i'] to get the
current iterator value.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. |
def invoke_step(self, context):
logger.debug("starting")
logger.debug(f"running step {self.module}")
self.run_step_function(context)
logger.debug(f"step {self.module} done") | Invoke 'run_step' in the dynamically loaded step module.
Don't invoke this from outside the Step class. Use
pypyr.dsl.Step.run_step instead.
invoke_step just does the bare module step invocation, it does not
evaluate any of the decorator logic surrounding the step. So unless
you... |
def run_conditional_decorators(self, context):
logger.debug("starting")
# The decorator attributes might contain formatting expressions that
# change whether they evaluate True or False, thus apply formatting at
# last possible instant.
run_me = context.get_formatted_as_... | Evaluate the step decorators to decide whether to run step or not.
Use pypyr.dsl.Step.run_step if you intend on executing the step the
same way pypyr does.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. |
def run_foreach_or_conditional(self, context):
logger.debug("starting")
# friendly reminder [] list obj (i.e empty) evals False
if self.foreach_items:
self.foreach_loop(context)
else:
# since no looping required, don't pollute output with looping info
... | Run the foreach sequence or the conditional evaluation.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. |
def run_step(self, context):
logger.debug("starting")
# the in params should be added to context before step execution.
self.set_step_input_context(context)
if self.while_decorator:
self.while_decorator.while_loop(context,
... | Run a single pipeline step.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. |
def set_step_input_context(self, context):
logger.debug("starting")
if self.in_parameters is not None:
parameter_count = len(self.in_parameters)
if parameter_count > 0:
logger.debug(
f"Updating context with {parameter_count} 'in' "
... | Append step's 'in' parameters to context, if they exist.
Append the[in] dictionary to the context. This will overwrite
existing values if the same keys are already in there. I.e if
in_parameters has {'eggs': 'boiled'} and key 'eggs' already
exists in context, context['eggs'] hereafter w... |
def exec_iteration(self, counter, context, step_method):
logger.debug("starting")
context['retryCounter'] = counter
logger.info(f"retry: running step with counter {counter}")
try:
step_method(context)
result = True
except Exception as ex_info:
... | Run a single retry iteration.
This method abides by the signature invoked by poll.while_until_true,
which is to say (counter, *args, **kwargs). In a normal execution
chain, this method's args passed by self.retry_loop where context
and step_method set. while_until_true injects counter a... |
def retry_loop(self, context, step_method):
logger.debug("starting")
context['retryCounter'] = 0
sleep = context.get_formatted_as_type(self.sleep, out_type=float)
if self.max:
max = context.get_formatted_as_type(self.max, out_type=int)
logger.info(f"retry... | Run step inside a retry loop.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate - after method execution will contain the new
updated context.
step_method: (method/function) This is the method/function that
... |
def exec_iteration(self, counter, context, step_method):
logger.debug("starting")
context['whileCounter'] = counter
logger.info(f"while: running step with counter {counter}")
step_method(context)
logger.debug(f"while: done step {counter}")
result = False
... | Run a single loop iteration.
This method abides by the signature invoked by poll.while_until_true,
which is to say (counter, *args, **kwargs). In a normal execution
chain, this method's args passed by self.while_loop where context
and step_method set. while_until_true injects counter as... |
def while_loop(self, context, step_method):
logger.debug("starting")
context['whileCounter'] = 0
if self.stop is None and self.max is None:
# the ctor already does this check, but guess theoretically
# consumer could have messed with the props since ctor
... | Run step inside a while loop.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate - after method execution will contain the new
updated context.
step_method: (method/function) This is the method/function that
... |
def run_step(context):
logger.debug("started")
deprecated(context)
context.assert_key_has_value(key='fetchYaml', caller=__name__)
fetch_yaml_input = context.get_formatted('fetchYaml')
if isinstance(fetch_yaml_input, str):
file_path = fetch_yaml_input
destination_key_expression =... | Load a yaml file into the pypyr context.
Yaml parsed from the file will be merged into the pypyr context. This will
overwrite existing values if the same keys are already in there.
I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'}
already exists, returned context['eggs'] will be 'b... |
def run_step(context):
logger.debug("started")
deprecated(context)
ObjectRewriterStep(__name__, 'fileFormatYaml', context).run_step(
YamlRepresenter())
logger.debug("done") | Parse input yaml file and substitute {tokens} from context.
Loads yaml into memory to do parsing, so be aware of big files.
Args:
context: pypyr.context.Context. Mandatory.
- fileFormatYaml
- in. mandatory.
str, path-like, or an iterable (list/tuple) of
... |
def wait_until_true(interval, max_attempts):
def decorator(f):
logger.debug("started")
def sleep_looper(*args, **kwargs):
logger.debug(f"Looping every {interval} seconds for "
f"{max_attempts} attempts")
for i in range(1, max_attempts + 1):
... | Decorator that executes a function until it returns True.
Executes wrapped function at every number of seconds specified by interval,
until wrapped function either returns True or max_attempts are exhausted,
whichever comes 1st. The wrapped function can have any given signature.
Use me if you always w... |
def while_until_true(interval, max_attempts):
def decorator(f):
logger.debug("started")
def sleep_looper(*args, **kwargs):
if max_attempts:
logger.debug(f"Looping every {interval} seconds for "
f"{max_attempts} attempts")
else... | Decorator that executes a function until it returns True.
Executes wrapped function at every number of seconds specified by interval,
until wrapped function either returns True or max_attempts are exhausted,
whichever comes 1st.
The difference between while_until_true and wait_until_true is that the
... |
def run_step(context):
logger.debug("started")
deprecated(context)
StreamRewriterStep(__name__, 'fileFormat', context).run_step()
logger.debug("done") | Parse input file and substitutes {tokens} from context.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileFormat
- in. mandatory.
str, path-like, or an iterable (list/tuple) of
... |
def deprecated(context):
if 'fileFormatIn' in context:
context.assert_keys_have_values(__name__,
'fileFormatIn',
'fileFormatOut')
context['fileFormat'] = {'in': context['fileFormatIn'],
... | Create new style in params from deprecated. |
def run_step(context):
logger.debug("started")
format_expression = context.get('nowUtcIn', None)
if format_expression:
formatted_expression = context.get_formatted_string(format_expression)
context['nowUtc'] = datetime.now(
timezone.utc).strftime(formatted_expression)
el... | pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
of possible expressions, check here:
... |
def run_step(context):
logger.debug("started")
assert context, f"context must have value for {__name__}"
deprecated(context)
context.assert_key_has_value('env', __name__)
found_get = env_get(context)
found_set = env_set(context)
found_unset = env_unset(context)
# at least 1 of envGe... | Get, set, unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
Input context is:
env:
get: {dict}
set: {dict}
unset: [list]
At least one of env's sub-keys (get, set or unset) must exist.
This step will run whatever combination of ... |
def env_get(context):
get = context['env'].get('get', None)
exists = False
if get:
logger.debug("start")
for k, v in get.items():
logger.debug(f"setting context {k} to $ENV {v}")
context[k] = os.environ[v]
logger.info(f"saved {len(get)} $ENVs to context."... | Get $ENVs into the pypyr context.
Context is a dictionary or dictionary-like. context is mandatory.
context['env']['get'] must exist. It's a dictionary.
Values are the names of the $ENVs to write to the pypyr context.
Keys are the pypyr context item to which to write the $ENV values.
For example,... |
def env_set(context):
env_set = context['env'].get('set', None)
exists = False
if env_set:
logger.debug("started")
for k, v in env_set.items():
logger.debug(f"setting ${k} to context[{v}]")
os.environ[k] = context.get_formatted_string(v)
logger.info(f"set... | Set $ENVs to specified string. from the pypyr context.
Args:
context: is dictionary-like. context is mandatory.
context['env']['set'] must exist. It's a dictionary.
Values are strings to write to $ENV.
Keys are the names of the $ENV values to which to writ... |
def env_unset(context):
unset = context['env'].get('unset', None)
exists = False
if unset:
logger.debug("started")
for env_var_name in unset:
logger.debug(f"unsetting ${env_var_name}")
try:
del os.environ[env_var_name]
except KeyError:... | Unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
context['env']['unset'] must exist. It's a list.
List items are the names of the $ENV values to unset.
For example, say input context is:
key1: value1
key2: value2
key3: value3
env:
... |
def deprecated(context):
env = context.get('env', None)
get_info, set_info, unset_info = context.keys_of_type_exist(
('envGet', dict),
('envSet', dict),
('envUnset', list)
)
found_at_least_one = (get_info.key_in_context or set_info.key_in_context
or... | Handle deprecated context input. |
def run_step(context):
logger.debug("started")
assert context, f"context must have value for {__name__}"
deprecated(context)
context.assert_key_has_value('assert', __name__)
assert_this = context['assert']['this']
is_equals_there = 'equals' in context['assert']
if is_equals_there:
... | Assert that something is True or equal to something else.
Args:
context: dictionary-like pypyr.context.Context. context is mandatory.
Uses the following context keys in context:
- assert
- this. mandatory. Any type. If assert['equals'] not specified,
ev... |
def deprecated(context):
assert_context = context.get('assert', None)
# specifically do "key in dict" to avoid python bool eval thinking
# None/Empty values mean the key isn't there.
if 'assertThis' in context:
assert_this = context['assertThis']
assert_context = context['assert'] =... | Handle deprecated context input. |
def run_step(context):
logger.debug("started")
assert context, f"context must have value for {__name__}"
deprecated(context)
found_at_least_one = False
context.assert_key_has_value('tar', __name__)
tar = context['tar']
if 'extract' in tar:
found_at_least_one = True
tar_e... | Archive and/or extract tars with or without compression.
Args:
context: dictionary-like. Mandatory.
Expects the following context:
tar:
extract:
- in: /path/my.tar
out: /out/path
archive:
- in: /dir/to/archive
... |
def get_file_mode_for_reading(context):
format = context['tar'].get('format', None)
if format or format == '':
mode = f"r:{context.get_formatted_string(format)}"
else:
mode = 'r:*'
return mode | Get file mode for reading from tar['format'].
This should return r:*, r:gz, r:bz2 or r:xz. If user specified something
wacky in tar.Format, that's their business.
In theory r:* will auto-deduce the correct format. |
def get_file_mode_for_writing(context):
format = context['tar'].get('format', None)
# slightly weird double-check because falsy format could mean either format
# doesn't exist in input, OR that it exists and is empty. Exists-but-empty
# has special meaning - default to no compression.
if format... | Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business. |
def tar_archive(context):
logger.debug("start")
mode = get_file_mode_for_writing(context)
for item in context['tar']['archive']:
# value is the destination tar. Allow string interpolation.
destination = context.get_formatted_string(item['out'])
# key is the source to archive
... | Archive specified path to a tar archive.
Args:
context: dictionary-like. context is mandatory.
context['tar']['archive'] must exist. It's a dictionary.
keys are the paths to archive.
values are the destination output paths.
Example:
tar:
archive:... |
def tar_extract(context):
logger.debug("start")
mode = get_file_mode_for_reading(context)
for item in context['tar']['extract']:
# in is the path to the tar to extract. Allows string interpolation.
source = context.get_formatted_string(item['in'])
# out is the outdir, dhur. Allo... | Extract all members of tar archive to specified path.
Args:
context: dictionary-like. context is mandatory.
context['tar']['extract'] must exist. It's a dictionary.
keys are the path to the tar to extract.
values are the destination paths.
Example:
tar:
... |
def deprecated(context):
tar = context.get('tar', None)
# at least 1 of tarExtract or tarArchive must exist in context
tar_extract, tar_archive = context.keys_of_type_exist(
('tarExtract', list),
('tarArchive', list))
found_at_least_one = (tar_extract.key_in_context
... | Handle deprecated context input. |
def run_step(context):
logger.debug("started")
CmdStep(name=__name__, context=context).run_step(is_shell=True)
logger.debug("done") | Run shell command without shell interpolation.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execute.
save: bool. defaul... |
def run_step(context):
logger.debug("started")
assert context, f"context must have value for {__name__}"
context.assert_key_has_value('envGet', __name__)
# allow a list OR a single getenv dict
if isinstance(context['envGet'], list):
get_items = context['envGet']
else:
get_it... | Get $ENVs, allowing a default if not found.
Set context properties from environment variables, and specify a default
if the environment variable is not found.
This differs from pypyr.steps.env get, which raises an error if attempting
to read an $ENV that doesn't exist.
Args:
context. mand... |
def get_args(get_item):
if not isinstance(get_item, dict):
raise ContextError('envGet must contain a list of dicts.')
env = get_item.get('env', None)
if not env:
raise KeyNotInContextError(
'context envGet[env] must exist in context for envGet.')
key = get_item.get('key'... | Parse env, key, default out of input dict.
Args:
get_item: dict. contains keys env/key/default
Returns:
(env, key, has_default, default) tuple, where
env: str. env var name.
key: str. save env value to this context key.
has_default: bool. True if default spe... |
def run_step(context):
logger.debug("started")
context.assert_key_has_value(key='pycode', caller=__name__)
logger.debug(f"Executing python string: {context['pycode']}")
locals_dictionary = locals()
exec(context['pycode'], globals(), locals_dictionary)
# It looks like this dance might be unn... | Executes dynamic python code.
Context is a dictionary or dictionary-like.
Context must contain key 'pycode'
Will exec context['pycode'] as dynamically interpreted python statements.
context is mandatory. When you execute the pipeline, it should look
something like this:
pipeline-runner [na... |
def get_parsed_context(context_arg):
assert context_arg, ("pipeline must be invoked with context arg set. For "
"this yaml parser you're looking for something "
"like: "
"pypyr pipelinename './myyamlfile.yaml'")
logger.debug("starti... | Parse input context string and returns context as dictionary. |
def get_parser():
parser = argparse.ArgumentParser(
allow_abbrev=True,
description='pypyr pipeline runner')
parser.add_argument('pipeline_name',
help='Name of pipeline to run. It should exist in the '
'./pipelines directory.')
parser.add_a... | Return ArgumentParser for pypyr cli. |
def main(args=None):
if args is None:
args = sys.argv[1:]
parsed_args = get_args(args)
try:
return pypyr.pipelinerunner.main(
pipeline_name=parsed_args.pipeline_name,
pipeline_context_input=parsed_args.pipeline_context,
working_dir=parsed_args.working... | Entry point for pypyr cli.
The setup_py entry_point wraps this in sys.exit already so this effectively
becomes sys.exit(main()).
The __main__ entry point similarly wraps sys.exit(). |
def run_step(self, is_shell):
assert is_shell is not None, ("is_shell param must exist for CmdStep.")
# why? If shell is True, it is recommended to pass args as a string
# rather than as a sequence.
if is_shell:
args = self.cmd_text
else:
args = s... | Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell. |
def run_step(context):
logger.debug("started")
context.assert_key_has_value(key='contextClear', caller=__name__)
for k in context['contextClear']:
logger.debug(f"removing {k} from context")
# slightly unorthodox pop returning None means you don't get a KeyError
# if key doesn't ... | Remove specified keys from context.
Args:
Context is a dictionary or dictionary-like.
context['contextClear'] must exist. It's a dictionary.
Will iterate context['contextClear'] and remove those keys from
context.
For example, say input context is:
key1: value1
... |
def run_step(context):
logger.debug("started")
pypyr.steps.cmd.run_step(context)
logger.debug("done") | Run command, program or executable.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execute.
save: bool. defaults False. s... |
def run_step(context):
logger.debug("started")
context.assert_key_has_value(key='defaults', caller=__name__)
context.set_defaults(context['defaults'])
logger.info(f"set {len(context['defaults'])} context item defaults.")
logger.debug("done") | Set hierarchy into context with substitutions if it doesn't exist yet.
context is a dictionary or dictionary-like.
context['defaults'] must exist. It's a dictionary.
Will iterate context['defaults'] and add these as new values where
their keys don't already exist. While it's doing so, it will leave
... |
def get_pipeline_steps(pipeline, steps_group):
logger.debug("starting")
assert pipeline
assert steps_group
logger.debug(f"retrieving {steps_group} steps from pipeline")
if steps_group in pipeline:
steps = pipeline[steps_group]
if steps is None:
logger.warn(
... | Get the steps attribute of module pipeline.
If there is no steps sequence on the pipeline, return None. Guess you
could theoretically want to run a pipeline with nothing in it. |
def run_failure_step_group(pipeline, context):
logger.debug("starting")
try:
assert pipeline
# if no on_failure exists, it'll do nothing.
run_step_group(pipeline_definition=pipeline,
step_group_name='on_failure',
context=context)
exc... | Run the on_failure step group if it exists.
This function will swallow all errors, to prevent obfuscating the error
condition that got it here to begin with. |
def run_pipeline_steps(steps, context):
logger.debug("starting")
assert isinstance(
context, dict), "context must be a dictionary, even if empty {}."
if steps is None:
logger.debug("No steps found to execute.")
else:
step_count = 0
for step in steps:
step... | Run the run_step(context) method of each step in steps.
Args:
steps: list. Sequence of Steps to execute
context: pypyr.context.Context. The pypyr context. Will mutate. |
def run_step_group(pipeline_definition, step_group_name, context):
logger.debug(f"starting {step_group_name}")
assert step_group_name
steps = get_pipeline_steps(pipeline=pipeline_definition,
steps_group=step_group_name)
run_pipeline_steps(steps=steps, context=context)... | Get the specified step group from the pipeline and run its steps. |
def ensure_dir(path):
os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True) | Create all parent directories of path if they don't exist.
Args:
path. Path-like object. Create parent dirs to this path.
Return:
None. |
def get_glob(path):
if isinstance(path, str):
return glob.glob(path, recursive=True)
if isinstance(path, os.PathLike):
# hilariously enough, glob doesn't like path-like. Gotta be str.
return glob.glob(str(path), recursive=True)
elif isinstance(path, (list, tuple)):
# eac... | Process the input path, applying globbing and formatting.
Do note that this will returns files AND directories that match the glob.
No tilde expansion is done, but *, ?, and character ranges expressed with
[] will be correctly matched.
Escape all special characters ('?', '*' and '['). For a literal m... |
def is_same_file(path1, path2):
return (
path1 and path2
and os.path.isfile(path1) and os.path.isfile(path2)
and os.path.samefile(path1, path2)) | Return True if path1 is the same file as path2.
The reason for this dance is that samefile throws if either file doesn't
exist.
Args:
path1: str or path-like.
path2: str or path-like.
Returns:
bool. True if the same file, False if not. |
def move_file(src, dest):
try:
os.replace(src, dest)
except Exception as ex_replace:
logger.error(f"error moving file {src} to "
f"{dest}. {ex_replace}")
raise | Move source file to destination.
Overwrites dest.
Args:
src: str or path-like. source file
dest: str or path-like. destination file
Returns:
None.
Raises:
FileNotFoundError: out path parent doesn't exist.
OSError: if any IO operations go wrong. |
def move_temp_file(src, dest):
try:
move_file(src, dest)
except Exception:
try:
os.remove(src)
except Exception as ex_clean:
# at this point, something's deeply wrong, so log error.
# raising the original error, though, not this error in the
... | Move src to dest. Delete src if something goes wrong.
Overwrites dest.
Args:
src: str or path-like. source file
dest: str or path-like. destination file
Returns:
None.
Raises:
FileNotFoundError: out path parent doesn't exist.
OSError: if any IO operations go w... |
def files_in_to_out(self, in_path, out_path=None):
in_paths = get_glob(in_path)
in_count = len(in_paths)
if in_count == 0:
logger.debug(f'in path found {in_count} paths.')
else:
logger.debug(f'in path found {in_count} paths:')
for path in in_p... | Write in files to out, calling the line_handler on each line.
Calls file_in_to_out under the hood to format the in_path payload. The
formatting processing is done by the self.formatter instance.
Args:
in_path: str, path-like, or an iterable (list/tuple) of
stri... |
def in_to_out(self, in_path, out_path=None):
if is_same_file(in_path, out_path):
logger.debug(
"in path and out path are the same file. writing to temp "
"file and then replacing in path with the temp file.")
out_path = None
logger.debug(f... | Load file into object, formats, writes object to out.
If in_path and out_path point to the same thing it will in-place edit
and overwrite the in path. Even easier, if you do want to edit a file
in place, don't specify out_path, or set it to None.
Args:
in_path: str or path-... |
def in_to_out(self, in_path, out_path=None):
is_in_place_edit = False
if is_same_file(in_path, out_path):
logger.debug(
"in path and out path are the same file. writing to temp "
"file and then replacing in path with the temp file.")
out_p... | Write a single file in to out, running self.formatter on each line.
If in_path and out_path point to the same thing it will in-place edit
and overwrite the in path. Even easier, if you do want to edit a file
in place, don't specify out_path, or set it to None.
Args:
in_path... |
def dump(self, file, payload):
json.dump(payload, file, indent=2, ensure_ascii=False) | Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None. |
def run_step(context):
logger.debug("started")
deprecated(context)
StreamReplacePairsRewriterStep(__name__, 'fileReplace', context).run_step()
logger.debug("done") | Parse input file and replace a search string.
This also does string substitutions from context on the fileReplacePairs.
It does this before it search & replaces the in file.
Be careful of order. If fileReplacePairs is not an ordered collection,
replacements could evaluate in any given order. If this i... |
def run_step(context):
logger.debug("started")
deprecated(context)
ObjectRewriterStep(__name__, 'fileFormatJson', context).run_step(
JsonRepresenter())
logger.debug("done") | Parse input json file and substitute {tokens} from context.
Loads json into memory to do parsing, so be aware of big files.
Args:
context: pypyr.context.Context. Mandatory.
- fileFormatJson
- in. mandatory.
str, path-like, or an iterable (list/... |
def set_logging_config(log_level, handlers):
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=log_level,
handlers=handlers) | Set python logging library config.
Run this ONCE at the start of your process. It formats the python logging
module's output.
Defaults logging level to INFO = 20) |
def set_root_logger(root_log_level, log_path=None):
handlers = []
console_handler = logging.StreamHandler()
handlers.append(console_handler)
if log_path:
file_handler = logging.FileHandler(log_path)
handlers.append(file_handler)
set_logging_config(root_log_level, handlers=handle... | Set the root logger 'pypyr'. Do this before you do anything else.
Run once and only once at initialization. |
def get_parsed_context(context_arg):
if not context_arg:
logger.debug("pipeline invoked without context arg set. For "
"this json parser you're looking for something "
"like: "
"pypyr pipelinename '{\"key1\":\"value1\","
... | Parse input context string and returns context as dictionary. |
def get_parsed_context(pipeline, context_in_string):
logger.debug("starting")
if 'context_parser' in pipeline:
parser_module_name = pipeline['context_parser']
logger.debug(f"context parser found: {parser_module_name}")
parser_module = pypyr.moduleloader.get_module(parser_module_name... | Execute get_parsed_context handler if specified.
Dynamically load the module specified by the context_parser key in pipeline
dict and execute the get_parsed_context function on that module.
Args:
pipeline: dict. Pipeline object.
context_in_string: string. Argument string used to initialize... |
def main(
pipeline_name,
pipeline_context_input,
working_dir,
log_level,
log_path,
):
pypyr.log.logger.set_root_logger(log_level, log_path)
logger.debug("starting pypyr")
# pipelines specify steps in python modules that load dynamically.
# make it easy for the operator so that t... | Entry point for pypyr pipeline runner.
Call this once per pypyr run. Call me if you want to run a pypyr pipeline
from your own code. This function does some one-off 1st time initialization
before running the actual pipeline.
pipeline_name.yaml should be in the working_dir/pipelines/ directory.
Ar... |
def prepare_context(pipeline, context_in_string, context):
logger.debug("starting")
parsed_context = get_parsed_context(
pipeline=pipeline,
context_in_string=context_in_string)
context.update(parsed_context)
logger.debug("done") | Prepare context for pipeline run.
Args:
pipeline: dict. Dictionary representing the pipeline.
context_in_string: string. Argument string used to initialize context.
context: pypyr.context.Context. Merge any new context generated from
context_in_string into this context inst... |
def load_and_run_pipeline(pipeline_name,
pipeline_context_input=None,
working_dir=None,
context=None,
parse_input=True,
loader=None):
logger.debug(f"you asked to run pipeline: {pipe... | Load and run the specified pypyr pipeline.
This function runs the actual pipeline by name. If you are running another
pipeline from within a pipeline, call this, not main(). Do call main()
instead for your 1st pipeline if there are pipelines calling pipelines.
By default pypyr uses file loader. This m... |
def run_pipeline(pipeline,
context,
pipeline_context_input=None,
parse_input=True):
logger.debug("starting")
try:
if parse_input:
logger.debug("executing context_parser")
prepare_context(pipeline=pipeline,
... | Run the specified pypyr pipeline.
This function runs the actual pipeline. If you are running another
pipeline from within a pipeline, call this, not main(). Do call main()
instead for your 1st pipeline if there are pipelines calling pipelines.
Pipeline and context should be already loaded.
Args:
... |
def run_step(context):
logger.debug("started")
context.assert_child_key_has_value('fileWriteYaml', 'path', __name__)
out_path = context.get_formatted_string(context['fileWriteYaml']['path'])
# doing it like this to safeguard against accidentally dumping all context
# with potentially sensitive ... | Write payload out to yaml file.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileWriteYaml
- path. mandatory. path-like. Write output file to
here. Will create directories in path for you.
... |
def run_step(context):
logger.debug("started")
debug = context.get('debug', None)
if debug:
keys = debug.get('keys', None)
format = debug.get('format', False)
if keys:
logger.debug(f"Writing to output: {keys}")
if isinstance(keys, str):
pa... | Print debug info to console.
context is a dictionary or dictionary-like.
If you use pypyr.steps.debug as a simple step (i.e you do NOT specify the
debug input context), it will just dump the entire context to stdout.
Configure the debug step with the following optional context item:
debug:
... |
def run_step(context):
logger.debug("started")
assert context, ("context must be set for echo. Did you set "
"'echoMe=text here'?")
context.assert_key_exists('echoMe', __name__)
if isinstance(context['echoMe'], str):
val = context.get_formatted('echoMe')
else:
... | Simple echo. Outputs context['echoMe'].
Args:
context: dictionary-like. context is mandatory.
context must contain key 'echoMe'
context['echoMe'] will echo the value to logger.
This logger could well be stdout.
When you execute the pipeline, it should... |
def get_error_name(error):
error_type = type(error)
if error_type.__module__ in ['__main__', 'builtins']:
return error_type.__name__
else:
return f'{error_type.__module__}.{error_type.__name__}' | Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Exception object.
Returns:
... |
def get_module(module_abs_import):
logger.debug("starting")
logger.debug(f"loading module {module_abs_import}")
try:
imported_module = importlib.import_module(module_abs_import)
logger.debug("done")
return imported_module
except ModuleNotFoundError as err:
msg = ("Th... | Use importlib to get the module dynamically.
Get instance of the module specified by the module_abs_import.
This means that module_abs_import must be resolvable from this package.
Args:
module_abs_import: string. Absolute name of module to import.
Raises:
PyModuleNotFoundError: if mod... |
def set_working_directory(working_directory):
logger.debug("starting")
logger.debug(f"adding {working_directory} to sys.paths")
sys.path.append(working_directory)
logger.debug("done") | Add working_directory to sys.paths.
This allows dynamic loading of arbitrary python modules in cwd.
Args:
working_directory: string. path to add to sys.paths |
def assert_child_key_has_value(self, parent, child, caller):
assert parent, ("parent parameter must be specified.")
assert child, ("child parameter must be specified.")
self.assert_key_has_value(parent, caller)
try:
child_exists = child in self[parent]
except... | Assert that context contains key that has child which has a value.
Args:
parent: parent key
child: validate this sub-key of parent exists AND isn't None.
caller: string. calling function name - this used to construct
error messages
Raises:
... |
def assert_key_has_value(self, key, caller):
assert key, ("key parameter must be specified.")
self.assert_key_exists(key, caller)
if self[key] is None:
raise KeyInContextHasNoValueError(
f"context['{key}'] must have a value for {caller}.") | Assert that context contains key which also has a value.
Args:
key: validate this key exists in context AND has a value that isn't
None.
caller: string. calling function name - this used to construct
error messages
Raises:
KeyNot... |
def assert_key_type_value(self,
context_item,
caller,
extra_error_text=''):
assert context_item, ("context_item parameter must be specified.")
if extra_error_text is None or extra_error_text == '':
... | Assert that keys exist of right type and has a value.
Args:
context_item: ContextItemInfo tuple
caller: string. calling function name - this used to construct
error messages
extra_error_text: append to end of error message.
Raises:
... |
def assert_keys_exist(self, caller, *keys):
assert keys, ("*keys parameter must be specified.")
for key in keys:
self.assert_key_exists(key, caller) | Assert that context contains keys.
Args:
keys: validates that these keys exists in context
caller: string. calling function or module name - this used to
construct error messages
Raises:
KeyNotInContextError: When key doesn't exist in context. |
def assert_keys_have_values(self, caller, *keys):
for key in keys:
self.assert_key_has_value(key, caller) | Check that keys list are all in context and all have values.
Args:
*keys: Will check each of these keys in context
caller: string. Calling function name - just used for informational
messages
Raises:
KeyNotInContextError: Key doesn't exist
... |
def assert_keys_type_value(self,
caller,
extra_error_text,
*context_items):
assert context_items, ("context_items parameter must be specified.")
for context_item in context_items:
self.asser... | Assert that keys exist of right type and has a value.
Args:
caller: string. calling function name - this used to construct
error messages
extra_error_text: append to end of error message. This can happily
be None or ''.
*... |
def get_formatted(self, key):
val = self[key]
if isinstance(val, str):
try:
return self.get_processed_string(val)
except KeyNotInContextError as err:
# Wrapping the KeyError into a less cryptic error for end-user
# friendli... | Return formatted value for context[key].
If context[key] is a type string, will just format and return the
string.
If context[key] is a special literal type, like a py string or sic
string, will run the formatting implemented by the custom tag
representer.
If context[key... |
def get_formatted_iterable(self, obj, memo=None):
if memo is None:
memo = {}
obj_id = id(obj)
already_done = memo.get(obj_id, None)
if already_done is not None:
return already_done
if isinstance(obj, str):
new = self.get_formatted_stri... | Recursively loop through obj, formatting as it goes.
Interpolates strings from the context dictionary.
This is not a full on deepcopy, and it's on purpose not a full on
deepcopy. It will handle dict, list, set, tuple for iteration, without
any especial cuteness for other types or types... |
def get_formatted_string(self, input_string):
if isinstance(input_string, str):
try:
return self.get_processed_string(input_string)
except KeyNotInContextError as err:
# Wrapping the KeyError into a less cryptic error for end-user
... | Return formatted value for input_string.
get_formatted gets a context[key] value.
get_formatted_string is for any arbitrary string that is not in the
context.
Only valid if input_string is a type string.
Return a string interpolated from the context dictionary.
If inpu... |
def get_formatted_as_type(self, value, default=None, out_type=str):
if value is None:
value = default
if isinstance(value, SpecialTagDirective):
result = value.get_value(self)
return types.cast_to_type(result, out_type)
if isinstance(value, str):
... | Return formatted value for input value, returns as out_type.
Caveat emptor: if out_type is bool and value a string,
return will be True if str is 'True'. It will be False for all other
cases.
Args:
value: the value to format
default: if value is None, set to thi... |
def get_processed_string(self, input_string):
# arguably, this doesn't really belong here, or at least it makes a
# nonsense of the function name. given how py and strings
# look and feel pretty much like strings from user's perspective, and
# given legacy code back when sic str... | Run token substitution on input_string against context.
You probably don't want to call this directly yourself - rather use
get_formatted, get_formatted_iterable, or get_formatted_string because
these contain more friendly error handling plumbing and context logic.
If you do want to ca... |
def keys_of_type_exist(self, *keys):
# k[0] = key name, k[1] = exists, k2 = expected type
keys_exist = [(key, key in self.keys(), expected_type)
for key, expected_type in keys]
return tuple(ContextItemInfo(
key=k[0],
key_in_context=k[1],
... | Check if keys exist in context and if types are as expected.
Args:
*keys: *args for keys to check in context.
Each arg is a tuple (str, type)
Returns:
Tuple of namedtuple ContextItemInfo, same order as *keys.
ContextItemInfo(key,
... |
def merge(self, add_me):
def merge_recurse(current, add_me):
for k, v in add_me.items():
# key supports interpolation
k = self.get_formatted_string(k)
# str not mergable, so it doesn't matter if it exists in dest
i... | Merge add_me into context and applies interpolation.
Bottom-up merge where add_me merges into context. Applies string
interpolation where the type is a string. Where a key exists in
context already, add_me's value will overwrite what's in context
already.
Supports nested hierar... |
def set_defaults(self, defaults):
def defaults_recurse(current, defaults):
for k, v in defaults.items():
# key supports interpolation
k = self.get_formatted_string(k)
if k in current:
if types.are_all_this_type... | Set defaults in context if keys do not exist already.
Adds the input dict (defaults) into the context, only where keys in
defaults do not already exist in context. Supports nested hierarchies.
Example:
Given a context like this:
key1: value1
key2:
... |
def run_step(self, rewriter):
assert rewriter, ("FileRewriter instance required to run "
"FileInRewriterStep.")
rewriter.files_in_to_out(in_path=self.path_in, out_path=self.path_out) | Do the file in to out rewrite.
Doesn't do anything more crazy than call files_in_to_out on the
rewriter.
Args:
rewriter: pypyr.filesystem.FileRewriter instance. |
def run_step(self, representer):
assert representer, ("ObjectRepresenter instance required to run "
"ObjectRewriterStep.")
rewriter = ObjectRewriter(self.context.get_formatted_iterable,
representer)
super().run_step(rewriter... | Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance. |
def run_step(self):
rewriter = StreamRewriter(self.context.iter_formatted_strings)
super().run_step(rewriter) | Do the file in-out rewrite. |
def run_step(self):
formatted_replacements = self.context.get_formatted_iterable(
self.replace_pairs)
iter = StreamReplacePairsRewriterStep.iter_replace_strings(
formatted_replacements)
rewriter = StreamRewriter(iter)
super().run_step(rewriter) | Write in to out, replacing strings per the replace_pairs. |
def iter_replace_strings(replacements):
def function_iter_replace_strings(iterable_strings):
for string in iterable_strings:
yield reduce((lambda s, kv: s.replace(*kv)),
replacements.items(),
string)
... | Create a function that uses replacement pairs to process a string.
The returned function takes an iterator and yields on each processed
line.
Args:
replacements: Dict containing 'find_string': 'replace_string' pairs
Returns:
function with signature: iterator of... |
def run_step(context):
logger.debug("started")
context.assert_key_has_value(key='contextSetf', caller=__name__)
for k, v in context['contextSetf'].items():
logger.debug(f"setting context {k} to value from context {v}")
context[context.get_formatted_iterable(
k)] = context.ge... | Set new context keys from formatting expressions with substitutions.
Context is a dictionary or dictionary-like.
context['contextSetf'] must exist. It's a dictionary.
Will iterate context['contextSetf'] and save the values as new keys to the
context.
For example, say input context is:
key1... |
def cast_to_type(obj, out_type):
in_type = type(obj)
if out_type is in_type:
# no need to cast.
return obj
else:
return out_type(obj) | Cast obj to out_type if it's not out_type already.
If the obj happens to be out_type already, it just returns obj as is.
Args:
obj: input object
out_type: type.
Returns:
obj cast to out_type. Usual python conversion / casting rules apply. |
def get_pipeline_yaml(file):
tag_representers = [PyString, SicString]
yaml_loader = get_yaml_parser_safe()
for representer in tag_representers:
yaml_loader.register_class(representer)
pipeline_definition = yaml_loader.load(file)
return pipeline_definition | Return pipeline yaml from open file object.
Use specific custom representers to model the custom pypyr pipeline yaml
format, to load in special literal types like py and sic strings.
If looking to extend the pypyr pipeline syntax with special types, add
these to the tag_representers list.
Args:
... |
def get_yaml_parser_roundtrip():
yaml_writer = yamler.YAML(typ='rt', pure=True)
# if this isn't here the yaml doesn't format nicely indented for humans
yaml_writer.indent(mapping=2, sequence=4, offset=2)
return yaml_writer | Create the yaml parser object with this factory method.
The round-trip parser preserves:
- comments
- block style and key ordering are kept, so you can diff the round-tripped
source
- flow style sequences ( ‘a: b, c, d’) (based on request and test by
Anthony Sottile)
- anchor names that... |
def get_yaml_parser_roundtrip_for_context():
yaml_writer = get_yaml_parser_roundtrip()
# Context is a dict data structure, so can just use a dict representer
yaml_writer.Representer.add_representer(
Context,
yamler.representer.RoundTripRepresenter.represent_dict)
return yaml_writer | Create a yaml parser that can serialize the pypyr Context.
Create yaml parser with get_yaml_parser_roundtrip, adding Context.
This allows the yaml parser to serialize the pypyr Context. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.