code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunable_key) if tunable_key in self.tune and \ is_vault_time(self.tune[tunable_key]): ...
def tunable(self, obj)
A tunable resource maps against a backend...
3.869743
3.679953
1.051574
filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) return open(dest_file, 'w')
def export_handle(self, directory)
Get a filehandle for exporting
2.567287
2.426052
1.058216
if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(obj, str): secret_h.write(obj) elif isinstance(obj, dict): secret_h.write(yaml.safe_dump(obj))
def export(self, directory)
Export exportable resources decoding as needed
4.970262
4.917152
1.010801
for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % (self, src_file)) dest_file = "%s/%s" % (tmp_d...
def freeze(self, tmp_dir)
Copies a secret into a particular location
3.979307
3.730126
1.066803
if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'present': raise aomi_excep \ .Validation('state must be either "absent" or "present"') self.present = obj.get('state', 'present').lower() == '...
def grok_state(self, obj)
Determine the desired state of this resource based on data present
5.36597
5.472352
0.98056
if 'tags' in obj and not isinstance(obj['tags'], list): raise aomi_excep.Validation('tags must be a list') if self.present: check_obj(self.required_fields, self.name(), obj)
def validate(self, obj)
Base validation method. Will inspect class attributes to dermine just what should be present
9.380311
10.016512
0.936485
if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff = NOOP if self.present and self.existing: if isinstance(sel...
def diff(self, obj=None)
Determine if something has changed or not
3.788765
3.627814
1.044366
result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: self.existing = result['data'] else: self.existing = result else: self.existing = None
def fetch(self, vault_client)
Populate internal representation of remote Vault resource contents
3.126786
3.04901
1.025509
if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) elif self.present and self.existing: if self.diff() == CHANGED or self.diff() == OVERWRITE: LOG.inf...
def sync(self, vault_client)
Update remove Vault resource contents if needed
2.534804
2.434077
1.041382
if not is_tagged(self.tags, self.opt.tags): LOG.info("Skipping %s as it does not have requested tags", self.path) return False if not specific_path_check(self.path, self.opt): LOG.info("Skipping %s as it does not match specified paths", ...
def filtered(self)
Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options
4.578071
3.974052
1.151991
if resource.present and not resource.existing: return ADD elif not resource.present and resource.existing: return DEL elif resource.present and resource.existing: return OVERWRITE return NOOP
def diff_write_only(resource)
A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs
5.027645
5.345846
0.940477
val = None if self.no_resource: return val LOG.debug("Reading from %s", self) try: val = client.read(self.path) except hvac.exceptions.InvalidRequest as vault_exception: if str(vault_exception).startswith('no handler for route'): ...
def read(self, client)
Read from Vault while handling non surprising errors.
6.67265
5.851274
1.140376
val = None if not self.no_resource: val = client.write(self.path, **self.obj()) return val
def write(self, client)
Write to Vault while handling non-surprising errors.
12.507758
10.152688
1.231965
path_bits = directory.split(os.sep) for i in range(0, len(path_bits) - 1): check_path = path_bits[0:len(path_bits) - i] check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name) if os.path.exists(check_file): return abspath(check_file) return None
def find_file(name, directory)
Searches up from a directory looking for a file
2.319482
2.263886
1.024558
handle = open(search_file, 'r') for line in handle.readlines(): if string in line: return True return False
def in_file(string, search_file)
Looks in a file for a string.
3.054974
2.965742
1.030087
directory = os.path.dirname(abspath(opt.secretfile)) gitignore_file = find_file('.gitignore', directory) if gitignore_file: secrets_path = subdir_path(abspath(opt.secrets), gitignore_file) if secrets_path: if not in_file(secrets_path, gitignore_file): e_msg =...
def gitignore(opt)
Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly
5.115482
4.750357
1.076863
filestat = os.stat(abspath(filename)) if stat.S_ISREG(filestat.st_mode) == 0 and \ stat.S_ISLNK(filestat.st_mode) == 0: e_msg = "Secret file %s must be a real file or symlink" % filename raise aomi.exceptions.AomiFile(e_msg) if platform.system() != "Windows": if filestat...
def secret_file(filename)
Will check the permissions of things which really should be secret files
2.737761
2.661729
1.028565
msg = '' for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg msg = "%s%s" % (msg, k) elif isinstance(k, list): found = False ...
def validate_obj(keys, obj)
Super simple "object" validation.
2.482145
2.396677
1.035661
if opt.exclude: if path in opt.exclude: return False if opt.include: if path not in opt.include: return False return True
def specific_path_check(path, opt)
Will make checks against include/exclude to determine if we actually care about the path in question.
2.670403
2.18777
1.220605
msg = validate_obj(keys, obj) if msg: raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name))
def check_obj(keys, name, obj)
Do basic validation on an object
11.473044
11.685358
0.981831
sanitized_mount = mount if sanitized_mount.startswith('/'): sanitized_mount = sanitized_mount[1:] if sanitized_mount.endswith('/'): sanitized_mount = sanitized_mount[:-1] sanitized_mount = sanitized_mount.replace('//', '/') return sanitized_mount
def sanitize_mount(mount)
Returns a quote-unquote sanitized mount path
1.910767
1.852084
1.031685
if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \ (len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)): return raise aomi.exceptions.Validation('Invalid GPG Fingerprint')
def gpg_fingerprint(key)
Validates a GPG key fingerprint This handles both pre and post GPG 2.1
3.325623
3.322686
1.000884
try: if sys.version_info >= (3, 0): # isn't a python 3 str actually unicode if not isinstance(string, str): string.decode('utf-8') else: string.decode('utf-8') except UnicodeError: raise aomi.exceptions.Validation('Not a unicode s...
def is_unicode_string(string)
Validates that we are some kinda unicode string
6.042114
5.375237
1.124065
str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def is_unicode(string)
Validates that the object itself is some kinda string
2.80436
2.752491
1.018845
try: return s % meta except (ValueError, TypeError, KeyError): # replace the missing fields by %% keys = substitution_pattern.finditer(s) for m in keys: key = m.group('key') if not isinstance(meta, dict) or key not in meta: if print_wa...
def safe_modulo(s, meta, checked='', print_warning=True, stacklevel=2)
Safe version of the modulo operation (%) of strings Parameters ---------- s: str string to apply the modulo operation with meta: dict or tuple meta informations to insert (usually via ``s % meta``) checked: {'KEY', 'VALUE'}, optional Security parameter for the recursive stru...
3.579489
3.425786
1.044867
params = self.params # Remove the summary and dedent the rest s = self._remove_summary(s) for section in sections: key = '%s.%s' % (base, section.lower().replace(' ', '_')) params[key] = self._get_section(s, section) return s
def get_sections(self, s, base, sections=['Parameters', 'Other Parameters'])
Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or the :attr:`text_sections` attribute. Parameters ----...
4.077246
5.799473
0.703037
def func(f): doc = f.__doc__ self.get_sections(doc or '', *args, **kwargs) return f return func
def get_sectionsf(self, *args, **kwargs)
Decorator method to extract sections from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_sections` method. Note, that the first argument will be the docstring of the specified function Returns ------- fun...
5.539353
4.885455
1.133846
if isinstance(obj, types.MethodType) and six.PY2: obj = obj.im_func try: obj.__doc__ = doc except AttributeError: # probably python2 class if (self.python2_classes != 'raise' and (inspect.isclass(obj) and six.PY2)): ...
def _set_object_doc(self, obj, doc, stacklevel=3)
Convenience method to set the __doc__ attribute of a python object
4.612105
4.535912
1.016798
doc = func.__doc__ and self.dedents(func.__doc__, stacklevel=4) return self._set_object_doc(func, doc)
def dedent(self, func)
Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute
9.406574
11.573382
0.812777
s = dedents(s) return safe_modulo(s, self.params, stacklevel=stacklevel)
def dedents(self, s, stacklevel=3)
Dedent a string and substitute with the :attr:`params` attribute Parameters ---------- s: str string to dedent and insert the sections of the :attr:`params` attribute stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when ...
12.30417
8.839872
1.391894
def replace(func): doc = func.__doc__ and self.with_indents( func.__doc__, indent=indent, stacklevel=4) return self._set_object_doc(func, doc) return replace
def with_indent(self, indent=0)
Substitute in the docstring of a function with indented :attr:`params` Parameters ---------- indent: int The number of spaces that the substitution should be indented Returns ------- function Wrapper that takes a function as input and substitutes...
8.882352
8.370282
1.061177
# we make a new dictionary with objects that indent the original # strings if necessary. Note that the first line is not indented d = {key: _StrWithIndentation(val, indent) for key, val in six.iteritems(self.params)} return safe_modulo(s, d, stacklevel=stacklevel)
def with_indents(self, s, indent=0, stacklevel=3)
Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented stacklevel: int The stacklevel for the warning raised...
10.805821
10.922541
0.989314
self.params[ base_key + '.no_' + '|'.join(params)] = self.delete_params_s( self.params[base_key], params)
def delete_params(self, base_key, *params)
Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for the ``'Paramete...
8.589986
5.516328
1.557193
patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params) return re.sub(patt, '', '\n' + s.strip() + '\n').strip()
def delete_params_s(s, params)
Delete the given parameters from a string Same as :meth:`delete_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters section params: list of str The names of the parameters to delete ...
6.636959
7.840426
0.846505
if not args and not kwargs: warn("Neither args nor kwargs are given. I do nothing for %s" % ( base_key)) return ext = '.no' + ('_args' if args else '') + ('_kwargs' if kwargs else '') self.params[base_key + ext] = self.delete_kwargs_s( ...
def delete_kwargs(self, base_key, args=None, kwargs=None)
Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. The resulting key will be stored in ``base_key + 'no_args'`` if `args` is not None and `kwargs` is None ``base_key + 'no_kwargs'`` if `args` is Non...
5.142584
4.529362
1.135388
if not args and not kwargs: return s types = [] if args is not None: types.append('`?`?\*%s`?`?' % args) if kwargs is not None: types.append('`?`?\*\*%s`?`?' % kwargs) return cls.delete_types_s(s, types)
def delete_kwargs_s(cls, s, args=None, kwargs=None)
Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. Parameters ---------- s: str The string to delete the args and kwargs from args: None or str The string for the args to delete kwar...
4.211986
4.27927
0.984277
self.params['%s.%s' % (base_key, out_key)] = self.delete_types_s( self.params[base_key], types)
def delete_types(self, base_key, out_key, *types)
Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the description of the param. This method works for ``'Results'`` l...
4.86662
5.128544
0.948928
patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\n.+?\n(?=\S+|$)' for s in types) return re.sub(patt, '', '\n' + s.strip() + '\n',).strip()
def delete_types_s(s, types)
Delete the given types from a string Same as :meth:`delete_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to delete Return...
7.231215
8.22069
0.879636
self.params[base_key + '.' + '|'.join(params)] = self.keep_params_s( self.params[base_key], params)
def keep_params(self, base_key, *params)
Method to keep only specific parameters from a parameter documentation. This method extracts the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the param. This method works for `...
5.843093
5.966871
0.979256
patt = '(?s)' + '|'.join( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params) return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip()
def keep_params_s(s, params)
Keep the given parameters from a string Same as :meth:`keep_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters like section params: list of str The parameter names to keep Ret...
7.237906
8.021378
0.902327
self.params['%s.%s' % (base_key, out_key)] = self.keep_types_s( self.params[base_key], types)
def keep_types(self, base_key, out_key, *types)
Method to keep only specific parameters from a parameter documentation. This method extracts the given `type` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only the description of the type. This method works for the...
4.762043
6.454972
0.737733
patt = '|'.join('(?<=\n)' + s + '\n(?s).+?\n(?=\S+|$)' for s in types) return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip()
def keep_types_s(s, types)
Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to keep Returns ...
7.544096
9.734316
0.775
def func(f): self.params[key] = f.__doc__ or '' return f return func
def save_docstring(self, key)
Descriptor method to save a docstring from a function Like the :meth:`get_sectionsf` method this method serves as a descriptor for functions but saves the entire docstring
7.051225
8.998319
0.783616
summary = summary_patt.search(s).group() if base is not None: self.params[base + '.summary'] = summary return summary
def get_summary(self, s, base=None)
Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the sum...
6.606109
5.327863
1.239917
def func(f): doc = f.__doc__ self.get_summary(doc or '', *args, **kwargs) return f return func
def get_summaryf(self, *args, **kwargs)
Extract the summary from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_summary` method. Note, that the first argument will be the docstring of the specified function Returns ------- function ...
5.30587
5.047936
1.051097
# Remove the summary and dedent s = self._remove_summary(s) ret = '' if not self._all_sections_patt.match(s): m = self._extended_summary_patt.match(s) if m is not None: ret = m.group().strip() if base is not None: self....
def get_extended_summary(self, s, base=None)
Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the su...
5.054804
4.070634
1.241773
def func(f): doc = f.__doc__ self.get_extended_summary(doc or '', *args, **kwargs) return f return func
def get_extended_summaryf(self, *args, **kwargs)
Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_extended_s...
4.988726
4.779762
1.043718
summary = self.get_summary(s) extended_summary = self.get_extended_summary(s) ret = (summary + '\n\n' + extended_summary).strip() if base is not None: self.params[base + '.full_desc'] = ret return ret
def get_full_description(self, s, base=None)
Get the full description from a docstring This here and the line above is the full description (i.e. the combination of the :meth:`get_summary` and the :meth:`get_extended_summary`) output Parameters ---------- s: str The docstring to use base: str o...
3.430628
2.317099
1.48057
def func(f): doc = f.__doc__ self.get_full_description(doc or '', *args, **kwargs) return f return func
def get_full_descriptionf(self, *args, **kwargs)
Extract the full description from a function docstring This function can be used as a decorator to extract the full descriptions of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_f...
4.708909
5.000437
0.9417
if isinstance(data, dict): return MergableDict(data=data, context=context) elif isiterable(data): return MergableList( data=[cls.make_mergable_if_possible(i, context) for i in data], context=context ) else: ...
def make_mergable_if_possible(cls, data, context)
Makes an object mergable if possible. Returns the virgin object if cannot convert it to a mergable instance. :returns: :class:`.Mergable` or type(data)
2.438419
2.61523
0.932392
for data in args: if isinstance(data, str): to_merge = load_string(data, self.context) if not to_merge: continue else: to_merge = data if not self.can_merge(to_merge): raise TypeErro...
def merge(self, *args)
Merges this instance with new instances, in-place. :param \\*args: Configuration values to merge with current instance. :type \\*args: iterable
4.009711
4.211769
0.952025
if not path.exists(filename): raise FileNotFoundError(filename) loaded_yaml = load_yaml(filename, self.context) if loaded_yaml: self.merge(loaded_yaml)
def load_file(self, filename)
load file which contains yaml configuration entries.and merge it by current instance :param files: files to load and merge into existing configuration instance :type files: list
4.340519
4.304214
1.008435
if not force and self._instance is not None: raise ConfigurationAlreadyInitializedError( 'Configuration manager object is already initialized.' ) self.__class__._instance = Root(init_value, context=context)
def initialize(self, init_value, context=None, force=False)
Initialize the configuration manager :param force: force initialization even if it's already initialized :return:
6.350728
5.810679
1.092941
e_name = None if element.name == 'default': if isinstance(element.node, jinja2.nodes.Getattr): e_name = element.node.node.name else: e_name = element.node.name return e_name
def grok_filter_name(element)
Extracts the name, which may be embedded, for a Jinja2 filter node
3.87625
3.448783
1.123947
if isinstance(element.iter, jinja2.nodes.Filter): if element.iter.name == 'default' \ and element.iter.node.name not in default_vars: default_vars.append(element.iter.node.name) default_vars = default_vars + grok_vars(element) return default_vars
def grok_for_node(element, default_vars)
Properly parses a For loop element
3.913004
3.973114
0.984871
if isinstance(element.test, jinja2.nodes.Filter) and \ element.test.name == 'default': default_vars.append(element.test.node.name) return default_vars + grok_vars(element)
def grok_if_node(element, default_vars)
Properly parses a If element
4.496698
4.939954
0.910271
default_vars = [] iterbody = None if hasattr(elements, 'body'): iterbody = elements.body elif hasattr(elements, 'nodes'): iterbody = elements.nodes for element in iterbody: if isinstance(element, jinja2.nodes.Output): default_vars = default_vars + grok_vars(...
def grok_vars(elements)
Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set
2.062679
2.094708
0.984709
fs_loader = FileSystemLoader(os.path.dirname(template_path)) env = Environment(loader=fs_loader, autoescape=True, trim_blocks=True, lstrip_blocks=True) env.filters['b64encode'] = portable_b64encode env.filters['b64decode'] = f_b64dec...
def jinja_env(template_path)
Sets up our Jinja environment, loading the few filters we have
2.518377
2.499398
1.007594
missing = [] default_vars = grok_vars(parsed_content) for var in template_vars: if var not in default_vars and var not in obj: missing.append(var) if missing: e_msg = "Missing required variables %s" % \ ','.join(missing) raise aomi_excep.AomiData...
def missing_vars(template_vars, parsed_content, obj)
If we find missing variables when rendering a template we want to give the user a friendly error
4.448077
4.951842
0.898267
template_path = abspath(filename) env = jinja_env(template_path) template_base = os.path.basename(template_path) try: parsed_content = env.parse(env .loader .get_source(env, template_base)) template_vars = meta.fi...
def render(filename, obj)
Render a template, maybe mixing in extra variables
3.979529
3.952885
1.006741
if not hasattr(opt, '_vars_cache'): cli_opts = cli_hash(opt.extra_vars) setattr(opt, '_vars_cache', merge_dicts(load_var_files(opt, cli_opts), cli_opts)) return getattr(opt, '_vars_cache')
def load_vars(opt)
Loads variable from cli and var files, passing in cli options as a seed (although they can be overwritten!). Note, turn this into an object so it's a nicer "cache".
5.173191
4.219335
1.226068
obj = {} if p_obj: obj = p_obj for var_file in opt.extra_vars_file: LOG.debug("loading vars from %s", var_file) obj = merge_dicts(obj.copy(), load_var_file(var_file, obj)) return obj
def load_var_files(opt, p_obj=None)
Load variable files, merge, return contents
3.744824
3.51087
1.066637
rendered = render(filename, obj) ext = os.path.splitext(filename)[1][1:] v_obj = dict() if ext == 'json': v_obj = json.loads(rendered) elif ext == 'yaml' or ext == 'yml': v_obj = yaml.safe_load(rendered) else: LOG.warning("assuming yaml for unrecognized extension %s"...
def load_var_file(filename, obj)
Loads a varible file, processing it as a template
2.835887
2.796707
1.01401
help_file = "templates/%s-help.yml" % builtin help_file = resource_filename(__name__, help_file) help_obj = {} if os.path.exists(help_file): help_data = yaml.safe_load(open(help_file)) if 'name' in help_data: help_obj['name'] = help_data['name'] if 'help' in he...
def load_template_help(builtin)
Loads the help for a given template
1.957188
1.971229
0.992877
for template in resource_listdir(__name__, "templates"): builtin, ext = os.path.splitext(os.path.basename(abspath(template))) if ext == '.yml': continue help_obj = load_template_help(builtin) if 'name' in help_obj: print("%-*s %s" % (20, builtin, help_ob...
def builtin_list()
Show a listing of all our builtin templates
5.280513
4.57773
1.153522
help_obj = load_template_help(builtin) if help_obj.get('name') and help_obj.get('help'): print("The %s template" % (help_obj['name'])) print(help_obj['help']) else: print("No help for %s" % builtin) if help_obj.get('args'): for arg, arg_help in iteritems(help_obj['a...
def builtin_info(builtin)
Show information on a particular builtin template
3.406408
3.136505
1.086052
LOG.debug("Using Secretfile %s", opt.secretfile) secretfile_path = abspath(opt.secretfile) obj = load_vars(opt) return render(secretfile_path, obj)
def render_secretfile(opt)
Renders and returns the Secretfile construct
5.596804
5.579105
1.003172
vault_path = '' user = '' user_path_bits = userpass.split('/') if len(user_path_bits) == 1: user = user_path_bits[0] vault_path = "auth/userpass/users/%s/password" % user LOG.debug("Updating password for user %s at the default path", user) elif len(user_path_bits) == 2: ...
def update_user_password(client, userpass)
Will update the password for a userpass user
3.200877
3.1743
1.008373
vault_path, key = path_pieces(path) mount = mount_for_path(vault_path, client) if not mount: client.revoke_self_token() raise aomi.exceptions.VaultConstraint('invalid path') if backend_type(mount, client) != 'generic': client.revoke_self_token() raise aomi.exception...
def update_generic_password(client, path)
Will update a single key in a generic secret backend as thought it were a password
3.879926
3.868456
1.002965
if path.startswith('user:'): update_user_password(client, path[5:]) else: update_generic_password(client, path)
def password(client, path)
Will attempt to contextually update a password in Vault
4.084379
3.943459
1.035735
home = os.environ['HOME'] if 'HOME' in os.environ else \ os.environ['USERPROFILE'] filename = os.environ.get(env, os.path.join(home, default)) filename = abspath(filename) if os.path.exists(filename): return filename return None
def vault_file(env, default)
The path to a misc Vault file This function will check for the env override on a file path, compute a fully qualified OS appropriate path to the desired file and return it if it exists. Otherwise returns None
2.825025
2.842294
0.993924
if not time_string or len(time_string) < 2: raise aomi.exceptions \ .AomiData("Invalid timestring %s" % time_string) last_char = time_string[len(time_string) - 1] if last_char == 's': return int(time_string[0:len(time_string) - 1]) elif last_char == 'm': c...
def vault_time_to_s(time_string)
Will convert a time string, as recognized by other Vault tooling, into an integer representation of seconds
2.004739
2.011218
0.996779
capture = kwargs.get("get_output", False) args = [arg for arglist in args for arg in (arglist if isinstance(arglist, list) else [arglist])] if opts.verbose: print("Running {}".format(" ".join(args))) live_output = opts.verbose and not capture runner = subprocess.check_call if live_ou...
def run(*args, **kwargs)
Execute a command. Command can be passed as several arguments, each being a string or a list of strings; lists are flattened. If opts.verbose is True, output of the command is shown. If the command exits with non-zero, print an error message and exit. If keyward argument get_output is True, output ...
3.157805
2.890233
1.092578
my_thread = threading.current_thread() if isinstance(my_thread, threads.CauldronThread): my_thread.is_executing = on
def set_executing(on: bool)
Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file.
7.495532
3.677866
2.038011
open_funcs = [ functools.partial(codecs.open, source_path, encoding='utf-8'), functools.partial(open, source_path, 'r') ] for open_func in open_funcs: try: with open_func() as f: return f.read() except Exception: pass return...
def get_file_contents(source_path: str) -> str
Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be displayed when the step is run alert the user to the erro...
3.311915
3.311557
1.000108
return templating.render_template( template_name='embedded-step.py.txt', source_contents=get_file_contents(source_path) )
def load_step_file(source_path: str) -> str
Loads the source for a step file at the given path location and then renders it in a template to add additional footer data. The footer is used to force the display to flush the print buffer and breathe the step to open things up for resolution. This shouldn't be necessary, but it seems there's an asyn...
9.003632
7.015581
1.283377
module_name = step.definition.name.rsplit('.', 1)[0] target_module = types.ModuleType(module_name) dunders = dict( __file__=step.source_path, __package__='.'.join( [project.id.replace('.', '-')] + step.filename.rsplit('.', 1)[0].split(os.sep) ) ) ...
def create_module( project: 'projects.Project', step: 'projects.ProjectStep' )
Creates an artificial module that will encompass the code execution for the specified step. The target module is populated with the standard dunder attributes like __file__ to simulate the normal way that Python populates values when loading a module. :param project: The currently open project....
3.666894
2.891369
1.268221
target_module = create_module(project, step) source_code = load_step_file(step.source_path) try: code = InspectLoader.source_to_code(source_code, step.source_path) except SyntaxError as error: return render_syntax_error(project, error) def exec_test(): step.test_local...
def run( project: 'projects.Project', step: 'projects.ProjectStep', ) -> dict
Carries out the execution of the step python source file by loading it into an artificially created module and then executing that module and returning the result. :param project: The currently open project. :param step: The project step for which the run execution will take place. ...
4.765064
4.606212
1.034487
return render_error( project=project, error=error, stack=[dict( filename=getattr(error, 'filename'), location=None, line_number=error.lineno, line=error.text.rstrip() )] )
def render_syntax_error( project: 'projects.Project', error: SyntaxError ) -> dict
Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for dis...
4.846557
4.518755
1.072542
data = dict( type=error.__class__.__name__, message='{}'.format(error), stack=( stack if stack is not None else render_stack.get_formatted_stack_frame(project) ) ) return dict( success=False, error=error, mess...
def render_error( project: 'projects.Project', error: Exception, stack: typing.List[dict] = None ) -> dict
Renders an Exception to an error response that includes rendered text and html error messages for display. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for display. :param stack: Optionally specify a parsed stack. If this ...
4.062944
3.604517
1.127181
r = Response() r.update(server=server_runner.get_server_data()) cmd, args = parse_command_args(r) if r.failed: return flask.jsonify(r.serialize()) try: commander.execute(cmd, args, r) if not r.thread: return flask.jsonify(r.serialize()) if not asyn...
def execute(asynchronous: bool = False)
:param asynchronous: Whether or not to allow asynchronous command execution that returns before the command is complete with a run_uid that can be used to track the continued execution of the command until completion.
3.829269
3.624287
1.056558
uid_list = list(server_runner.active_execution_responses.keys()) while len(uid_list) > 0: uid = uid_list.pop() response = server_runner.active_execution_responses.get(uid) if not response: continue try: del server_runner.active_execution_responses[...
def abort()
...
5.44665
5.427266
1.003572
environ.configs.remove(key, include_persists=persists) environ.configs.save() environ.log( '[REMOVED]: "{}" from configuration settings'.format(key) )
def remove_key(key: str, persists: bool = True)
Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists:
12.047275
15.707185
0.766991
if key.endswith('_path') or key.endswith('_paths'): for index in range(len(value)): value[index] = environ.paths.clean(value[index]) if len(value) == 1: value = value[0] environ.configs.put(**{key: value}, persists=persists) environ.configs.save() environ.log('[SE...
def set_key(key: str, value: typing.List[str], persists: bool = True)
Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param value: :param persists:
4.332791
4.510735
0.960551
data = self.load().persistent if data is None: return self directory = os.path.dirname(self._source_path) if not os.path.exists(directory): os.makedirs(directory) path = self._source_path with open(path, 'w+') as f: json.dum...
def save(self) -> 'Configuration'
Saves the configuration settings object to the current user's home directory :return:
3.06245
3.508927
0.87276
if not hasattr(self, "_userinfo"): userinfo = { "name": self.user_name, "email": self.user_email, "url": self.user_url } if self.user_id: u = self.user if u.email: use...
def _get_userinfo(self)
Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields.
3.317911
3.103774
1.068992
d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url() } return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%...
def get_as_text(self)
Return this comment as plain text. Useful for emails.
3.046254
2.65402
1.147789
if 'contents' in data: return FILE_WRITE_ENTRY(**data) return FILE_COPY_ENTRY(**data)
def entry_from_dict( data: dict ) -> typing.Union[FILE_WRITE_ENTRY, FILE_COPY_ENTRY]
Converts the given data dictionary into either a file write or file copy entry depending on the keys in the dictionary. The dictionary should contain either ('path', 'contents') keys for file write entries or ('source', 'destination') keys for file copy entries.
3.014413
2.972456
1.014115
def deploy_entry(entry): if not entry: return if hasattr(entry, 'source') and hasattr(entry, 'destination'): return copy(entry) if hasattr(entry, 'path') and hasattr(entry, 'contents'): return write(entry) raise ValueError('Unrecognized dep...
def deploy(files_list: typing.List[tuple])
Iterates through the specified files_list and copies or writes each entry depending on whether its a file copy entry or a file write entry. :param files_list: A list of file write entries and file copy entries
3.807211
3.243529
1.173787
output_directory = os.path.dirname(environ.paths.clean(output_path)) if not os.path.exists(output_directory): os.makedirs(output_directory) return output_directory
def make_output_directory(output_path: str) -> str
Creates the parent directory or directories for the specified output path if they do not already exist to prevent incomplete directory path errors during copying/writing operations. :param output_path: The path of the destination file or directory that will be written. :return: The abso...
3.59081
3.558196
1.009166
source_path = environ.paths.clean(copy_entry.source) output_path = environ.paths.clean(copy_entry.destination) copier = shutil.copy2 if os.path.isfile(source_path) else shutil.copytree make_output_directory(output_path) for i in range(3): try: copier(source_path, output_pat...
def copy(copy_entry: FILE_COPY_ENTRY)
Copies the specified file from its source location to its destination location.
2.84787
2.79423
1.019197
output_path = environ.paths.clean(write_entry.path) make_output_directory(output_path) writer.write_file(output_path, write_entry.contents)
def write(write_entry: FILE_WRITE_ENTRY)
Writes the contents of the specified file entry to its destination path.
6.613562
5.352689
1.235559
# Prevent anything unusual from causing buffer issues restore_default_configuration() stdout_interceptor = RedirectBuffer(sys.stdout) sys.stdout = stdout_interceptor step.report.stdout_interceptor = stdout_interceptor stderr_interceptor = RedirectBuffer(sys.stderr) sys.stderr = stder...
def enable(step: 'projects.ProjectStep')
Create a print equivalent function that also writes the output to the project page. The write_through is enabled so that the TextIOWrapper immediately writes all of its input data directly to the underlying BytesIO buffer. This is needed so that we can safely access the buffer data in a multi-threaded e...
5.500185
5.852269
0.939838
def restore(target, default_value): if target == default_value: return default_value if not isinstance(target, RedirectBuffer): return target try: target.active = False target.close() except Exception: pass ...
def restore_default_configuration()
Restores the sys.stdout and the sys.stderr buffer streams to their default values without regard to what step has currently overridden their values. This is useful during cleanup outside of the running execution block
3.778895
3.536451
1.068556
template_path = environ.paths.resources('web', 'project.html') with open(template_path, 'r') as f: dom = f.read() dom = dom.replace( '<!-- CAULDRON:EXPORT -->', templating.render_template( 'notebook-script-header.html', uuid=project.uuid, ve...
def create( project: 'projects.Project', destination_directory, destination_filename: str = None ) -> file_io.FILE_WRITE_ENTRY
Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given project that will be saved in the destination directory with the given filename. :param project: The project for which the rendered HTML file will be created :param destination_directory: The absolute path to the folder...
4.098711
3.892166
1.053067
os.chdir(my_directory) cmd = [ 'docker', 'run', '-it', '--rm', '-v', '{}:/cauldron'.format(my_directory), '-p', '5010:5010', 'cauldron_app', '/bin/bash' ] return os.system(' '.join(cmd))
def run_container()
Runs an interactive container
3.562523
3.603865
0.988528
command = sys.argv[1].strip().lower() print('[COMMAND]:', command) if command == 'test': return run_test() elif command == 'build': return run_build() elif command == 'up': return run_container() elif command == 'serve': import cauldron cauldron.run...
def run()
Execute the Cauldron container command
4.69331
4.033986
1.163442
@wraps(func) def check_identity(*args, **kwargs): code = server_runner.authorization['code'] comparison = request.headers.get('Cauldron-Authentication-Code') return ( abort(401) if code and code != comparison else func(*args, **kwargs) )...
def gatekeeper(func)
This function is used to handle authorization code authentication of protected endpoints. This form of authentication is not recommended because it's not very secure, but can be used in places where SSH tunneling or similar strong connection security is not possible. The function looks for a spe...
7.362538
5.247385
1.403087
r = _get_report() r.append_body(render.inspect(source))
def inspect(source: dict)
Inspects the data and structure of the source dictionary object and adds the results to the display for viewing. :param source: A dictionary object to be inspected. :return:
27.2446
32.005329
0.851252
r = _get_report() r.append_body(render.header( header_text, level=level, expand_full=expand_full ))
def header(header_text: str, level: int = 1, expand_full: bool = False)
Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, such as <h1>, <h2>, ... :param expand_full: Whether or not the header will e...
7.799566
8.894834
0.876865