INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Registers a proper name to the database.
def register_proper_name(self, name): """Registers a proper name to the database.""" with self.proper_names_db_path.open("a") as f: f.write(u"{0}\n".format(name))
Parse Pipfile into a TOMLFile and cache it
def parsed_pipfile(self): """Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)""" contents = self.read_pipfile() # use full contents to get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key...
Pipfile. lock divided by PyPI and external dependencies.
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for...
Returns a list of all packages.
def all_packages(self): """Returns a list of all packages.""" p = dict(self.parsed_pipfile.get("dev-packages", {})) p.update(self.parsed_pipfile.get("packages", {})) return p
Creates the Pipfile filled with juicy defaults.
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(...
Writes the given data structure out as TOML.
def write_toml(self, data, path=None): """Writes the given data structure out as TOML.""" if path is None: path = self.pipfile_location data = convert_toml_outline_tables(data) try: formatted_data = tomlkit.dumps(data).rstrip() except Exception: ...
Write out the lockfile.
def write_lockfile(self, content): """Write out the lockfile. """ s = self._lockfile_encoder.encode(content) open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"} with vistir.contextmanagers.atomic_open_for_write( self.lockfile_location, **open_kwarg...
Given a source find it.
def find_source(self, source): """ Given a source, find it. source can be a url or an index name. """ if not is_valid_url(source): try: source = self.get_source(name=source) except SourceNotFound: source = self.get_source(u...
Get the equivalent package name in pipfile
def get_package_name_in_pipfile(self, package_name, dev=False): """Get the equivalent package name in pipfile""" key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): ...
Adds a given index to the Pipfile.
def add_index_to_pipfile(self, index, verify_ssl=True): """Adds a given index to the Pipfile.""" # Read and append Pipfile. p = self.parsed_pipfile try: self.get_source(url=index) except SourceNotFound: source = {"url": index, "verify_ssl": verify_ssl} ...
Ensures proper casing of Pipfile packages
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
Verify proper casing is retrieved when available for each dependency in the section.
def proper_case_section(self, section): """Verify proper casing is retrieved, when available, for each dependency in the section. """ # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Repl...
Return a native Python type from the list of compiled nodes. If the result is a single node its value is returned. Otherwise the nodes are concatenated as strings. If the result can be parsed with: func: ast. literal_eval the parsed value is returned. Otherwise the string is returned.
def native_concat(nodes): """Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the s...
Same as: meth: CodeGenerator. visit_Output but do not call to_string on output nodes in generated code.
def visit_Output(self, node, frame): """Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code. """ if self.has_known_extends and frame.require_output_check: return finalize = self.environment.finalize fina...
Clear all existing key: value items and import all key: value items from <mapping >. If multiple values exist for the same key in <mapping > they are all be imported.
def load(self, *args, **kwargs): """ Clear all existing key:value items and import all key:value items from <mapping>. If multiple values exist for the same key in <mapping>, they are all be imported. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) ...
Update this dictionary with the items from <mapping > replacing existing key: value items with shared keys before adding new key: value items.
def updateall(self, *args, **kwargs): """ Update this dictionary with the items from <mapping>, replacing existing key:value items with shared keys before adding new key:value items. Example: omd = omdict([(1,1), (2,2)]) omd.updateall([(2,'two'), (1,'one'), (...
<replacements and <leftovers > are modified directly ala pass by reference.
def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): """ <replacements and <leftovers> are modified directly, ala pass by reference. """ for key, value in items: # If there are existing items with key <key> that h...
Returns: The list of values for <key > if <key > is in the dictionary else <default >. If <default > is not provided an empty list is returned.
def getlist(self, key, default=[]): """ Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned. """ if key in self: return [node.value for node in self._map[key]] ret...
Similar to setdefault () except <defaultlist > is a list of values to set for <key >. If <key > already exists its existing list of values is returned.
def setdefaultlist(self, key, defaultlist=[None]): """ Similar to setdefault() except <defaultlist> is a list of values to set for <key>. If <key> already exists, its existing list of values is returned. If <key> isn't a key and <defaultlist> is an empty list, [], no values ...
Add the values in <valuelist > to the list of values for <key >. If <key > is not in the dictionary the values in <valuelist > become the values for <key >.
def addlist(self, key, valuelist=[]): """ Add the values in <valuelist> to the list of values for <key>. If <key> is not in the dictionary, the values in <valuelist> become the values for <key>. Example: omd = omdict([(1,1)]) omd.addlist(1, [11, 111]) ...
Sets <key > s list of values to <values >. Existing items with key <key > are first replaced with new values from <values >. Any remaining old items that haven t been replaced with new values are deleted and any new values from <values > that don t have corresponding items with <key > to replace are appended to the end...
def setlist(self, key, values): """ Sets <key>'s list of values to <values>. Existing items with key <key> are first replaced with new values from <values>. Any remaining old items that haven't been replaced with new values are deleted, and any new values from <values> that don't...
Removes all <values > from the values of <key >. If <key > has no remaining values after removevalues () the key is popped.
def removevalues(self, key, values): """ Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.al...
If <key > is in the dictionary pop it and return its list of values. If <key > is not in the dictionary return <default >. KeyError is raised if <default > is not provided and <key > is not in the dictionary.
def poplist(self, key, default=_absent): """ If <key> is in the dictionary, pop it and return its list of values. If <key> is not in the dictionary, return <default>. KeyError is raised if <default> is not provided and <key> is not in the dictionary. Example: omd = omd...
If <value > is provided pops the first or last ( key value ) item in the dictionary if <key > is in the dictionary.
def popvalue(self, key, value=_absent, default=_absent, last=True): """ If <value> is provided, pops the first or last (key,value) item in the dictionary if <key> is in the dictionary. If <value> is not provided, pops the first or last value for <key> if <key> is in the dictiona...
Pop and return a key: value item.
def popitem(self, fromall=False, last=True): """ Pop and return a key:value item. If <fromall> is False, items()[0] is popped if <last> is False or items()[-1] is popped if <last> is True. All remaining items with the same key are removed. If <fromall> is True, allitems...
Pop and return a key: valuelist item comprised of a key and that key s list of values. If <last > is False a key: valuelist item comprised of keys () [ 0 ] and its list of values is popped and returned. If <last > is True a key: valuelist item comprised of keys () [ - 1 ] and its list of values is popped and returned.
def poplistitem(self, last=True): """ Pop and return a key:valuelist item comprised of a key and that key's list of values. If <last> is False, a key:valuelist item comprised of keys()[0] and its list of values is popped and returned. If <last> is True, a key:valuelist item compr...
Raises: KeyError if <key > is provided and not in the dictionary. Returns: List created from itervalues ( <key > ). If <key > is provided and is a dictionary key only values of items with key <key > are returned.
def values(self, key=_absent): """ Raises: KeyError if <key> is provided and not in the dictionary. Returns: List created from itervalues(<key>).If <key> is provided and is a dictionary key, only values of items with key <key> are returned. """ if key is not _...
Parity with dict. iteritems () except the optional <key > parameter has been added. If <key > is provided only items with the provided key are iterated over. KeyError is raised if <key > is provided and not in the dictionary.
def iteritems(self, key=_absent): """ Parity with dict.iteritems() except the optional <key> parameter has been added. If <key> is provided, only items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: ...
Parity with dict. itervalues () except the optional <key > parameter has been added. If <key > is provided only values from items with the provided key are iterated over. KeyError is raised if <key > is provided and not in the dictionary.
def itervalues(self, key=_absent): """ Parity with dict.itervalues() except the optional <key> parameter has been added. If <key> is provided, only values from items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. ...
Example: omd = omdict ( [ ( 1 1 ) ( 1 11 ) ( 1 111 ) ( 2 2 ) ( 3 3 ) ] ) omd. iterallitems () == ( 1 1 ) - > ( 1 11 ) - > ( 1 111 ) - > ( 2 2 ) - > ( 3 3 ) omd. iterallitems ( 1 ) == ( 1 1 ) - > ( 1 11 ) - > ( 1 111 )
def iterallitems(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3) omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111) Raises: KeyError if <key> is provided and not...
Example: omd = omdict ( [ ( 1 1 ) ( 1 11 ) ( 1 111 ) ( 2 2 ) ( 3 3 ) ] ) omd. iterallvalues () == 1 - > 11 - > 111 - > 2 - > 3
def iterallvalues(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3 Returns: An iterator over the values of every item in the dictionary. ''' if key is not _absent: ...
Reverse the order of all items in the dictionary.
def reverse(self): """ Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>. """ for key in si...
Return 2 sets: - conflicting requirements: set of ( installed wanted ) reqs tuples - missing requirements: set of reqs
def check_requirements(self, reqs): # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]] """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = ...
Given an iterable of arguments and an iterable of nargs specifications it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second.
def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed ...
Given an argument string this attempts to split it into small parts.
def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.gr...
Adds a new option named dest to the parser. The destination is not inferred ( unlike with optparse ) and needs to be explicitly provided. Action can be any of store store_const append appnd_const or count.
def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ...
Adds a positional argument named dest to the parser.
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argume...
Parses positional arguments and returns ( values args order ) for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.
def parse_args(self, args): """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple time...
Makes a dependency graph from the given distributions.
def make_graph(dists, scheme='default'): """Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a ...
Recursively generate a list of distributions from * dists * that are dependent on * dist *.
def get_dependent_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are dependent on *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibExcept...
Recursively generate a list of distributions from * dists * that are required by * dist *.
def get_required_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are required by *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibExceptio...
A convenience method for making a dist given just a name and version.
def make_dist(name, version, **kwargs): """ A convenience method for making a dist given just a name and version. """ summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' ...
Clear the cache setting it to its initial state.
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
Add a distribution to the cache.: param dist: The distribution to add.
def add(self, dist): """ Add a distribution to the cache. :param dist: The distribution to add. """ if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
Scan the path for distributions and populate the cache with those that are found.
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in ...
The * name * and * version * parameters are converted into their filename - escaped form i. e. any - characters are replaced with _ other than the one in dist - info and the one separating the name from the version number.
def distinfo_dirname(cls, name, version): """ The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` other than the one in ``'dist-info'`` and the one separating the name from the version number. ...
Provides an iterator that looks for distributions and returns: class: InstalledDistribution or: class: EggInfoDistribution instances for each one of them.
def get_distributions(self): """ Provides an iterator that looks for distributions and returns :class:`InstalledDistribution` or :class:`EggInfoDistribution` instances for each one of them. :rtype: iterator of :class:`InstalledDistribution` and :class:`EggInfoDis...
Looks for a named distribution on the path.
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribu...
Iterates over all distributions to find which distributions provide * name *. If a * version * is provided it will be used to filter the results.
def provides_distribution(self, name, version=None): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one value...
Return the path to a resource file.
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
Return all of the exported entries in a particular category.
def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned. """ for dist in self.get_distri...
A set of distribution names and versions provided by this distribution.: return: A set of name ( version ) strings.
def provides(self): """ A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings. """ plist = self.metadata.provides s = '%s (%s)' % (self.name, self.version) if s not in plist: plist.append(s) ...
Say if this instance matches ( fulfills ) a requirement.: param req: The requirement to match.: rtype req: str: return: True if it matches else False.
def matches_requirement(self, req): """ Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. """ # Requirement may contain extras - parse to lose those # from ...
Get the hash of some data using a particular hash algorithm if specified.
def get_hash(self, data, hasher=None): """ Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ...
Get the list of installed files for the distribution: return: A list of tuples of path hash and size. Note that hash and size might be None for some entries. The path is exactly as stored in the file ( which is as in PEP 376 ).
def _get_records(self): """ Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376). ...
Return the information exported by this distribution.: return: A dictionary of exports mapping an export category to a dict of: class: ExportEntry instances describing the individual export entries and keyed by name.
def exports(self): """ Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name. """ ...
Read exports data from a file in. ini format.
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} ...
Write a dictionary of exports to a file in. ini format.: param exports: A dictionary of exports mapping an export category to a list of: class: ExportEntry instances describing the individual export entries.
def write_exports(self, exports): """ Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. ...
NOTE: This API may change in the future.
def get_resource_path(self, relative_path): """ NOTE: This API may change in the future. Return the absolute path to a resource file with the given relative path. :param relative_path: The path, relative to .dist-info, of the resource of interest. ...
Writes the RECORD file using the paths iterable passed in. Any existing RECORD file is silently overwritten.
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.joi...
Checks that the hashes and sizes of the files in RECORD are matched by the files themselves. Returns a ( possibly empty ) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path exists size or hash according to what didn t match ( existence is checked first then size then hash ) the e...
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' ...
A dictionary of shared locations whose keys are in the set prefix purelib platlib scripts headers data and namespace. The corresponding value is the absolute path of that category for this distribution and takes into account any paths selected by the user at installation time ( e. g. via command - line arguments ). In ...
def shared_locations(self): """ A dictionary of shared locations whose keys are in the set 'prefix', 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'. The corresponding value is the absolute path of that category for this distribution, and takes into account any...
Write shared location information to the SHARED file in. dist - info.: param paths: A dictionary as described in the documentation for: meth: shared_locations.: param dry_run: If True the action is logged but no file is actually written.: return: The path of the file written to.
def write_shared_locations(self, paths, dry_run=False): """ Write shared location information to the SHARED file in .dist-info. :param paths: A dictionary as described in the documentation for :meth:`shared_locations`. :param dry_run: If True, the action is logged but no file is ...
Returns a path located under the. dist - info directory. Returns a string representing the path.
def get_distinfo_file(self, path): """ Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; ...
Iterates over the RECORD entries and returns paths for each line if the path is pointing to a file located in the. dist - info directory or one of its subdirectories.
def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths """ base = os.path.dirname(...
Checks that the hashes and sizes of the files in RECORD are matched by the files themselves. Returns a ( possibly empty ) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path exists size or hash according to what didn t match ( existence is checked first then size then hash ) the e...
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' ...
Iterates over the installed - files. txt entries and returns a tuple ( path hash size ) for each line.
def list_installed_files(self): """ Iterates over the ``installed-files.txt`` entries and returns a tuple ``(path, hash, size)`` for each line. :returns: a list of (path, hash, size) """ def _md5(path): f = open(path, 'rb') try: c...
Iterates over the installed - files. txt entries and returns paths for each line if the path is pointing to a file located in the. egg - info directory or one of its subdirectories.
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``Tru...
Add an edge from distribution * x * to distribution * y * with the given * label *.
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.In...
Add a missing * requirement * for the given * distribution *.
def add_missing(self, distribution, requirement): """ Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str...
Prints only a subgraph
def repr_node(self, dist, level=1): """Prints only a subgraph""" output = [self._repr_dist(dist)] for other, label in self.adjacency_list[dist]: dist = self._repr_dist(other) if label is not None: dist = '%s [%s]' % (dist, label) output.append(...
Writes a DOT output for the graph to the provided file * f *.
def to_dot(self, f, skip_disconnected=True): """Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations ...
Perform a topological sort of the graph.: return: A tuple the first element of which is a topologically sorted list of distributions and the second element of which is a list of distributions that cannot be sorted because they have circular dependencies and so form a cycle.
def topological_sort(self): """ Perform a topological sort of the graph. :return: A tuple, the first element of which is a topologically sorted list of distributions, and the second element of which is a list of distributions that cannot be sorted because they h...
Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can t be printed.
def encode_unicode(f): """Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function. """ @wraps(f) def wrapped(obj, er...
Dictionary with errors of an * of - rule mapped to the index of the definition it occurred in. Returns: obj: None if not applicable.
def definitions_errors(self): """ Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns :obj:`None` if not applicable. """ if not self.is_logic_error: return None result = defaultdict(list) for error in se...
Add an error to the tree.
def add(self, error): """ Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` """ if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
Returns all errors for a particular path.
def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors ...
Returns a node for a path.
def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None:...
Adds an error or sub - tree to: attr: tree.
def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. """ field = path[0] ...
Recursively rewrites the error path to correctly represent logic errors
def _rewrite_error_path(self, error, offset=0): """ Recursively rewrites the error path to correctly represent logic errors """ if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path...
Dispatches a hook dictionary on a given piece of data.
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **k...
This script is used to set get or unset values from a. env file.
def cli(ctx, file, quote): '''This script is used to set, get or unset values from a .env file.''' ctx.obj = {} ctx.obj['FILE'] = file ctx.obj['QUOTE'] = quote
Display all the stored key/ value.
def list(ctx): '''Display all the stored key/value.''' file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) for k, v in dotenv_as_dict.items(): click.echo('%s=%s' % (k, v))
Store the given key/ value.
def set(ctx, key, value): '''Store the given key/value.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key, value = set_key(file, key, value, quote) if success: click.echo('%s=%s' % (key, value)) else: exit(1)
Retrieve the value for the given key.
def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
Removes the given key.
def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
Run command with environment variables present.
def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
Check whether the distribution is in the current Python installation.
def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.wor...
Group locally installed packages based on given specifications.
def _group_installed_names(packages): """Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed pa...
Prepare paths for distlib. wheel. Wheel to install into.
def _build_paths(): """Prepare paths for distlib.wheel.Wheel to install into. """ paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "pl...
Dumps a TOMLDocument into a string.
def dumps(data): # type: (_TOMLDocument) -> str """ Dumps a TOMLDocument into a string. """ if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
Find all files under the base and set allfiles to the absolute pathnames of files found.
def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = ...
Add a file to the manifest.
def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
Return sorted files in directory order
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in...
Process a directive which either adds some files from allfiles to files or removes some files from files.
def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANI...
Validate a directive.: param directive: The directive to validate.: return: A tuple of action patterns thedir dir_patterns
def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns """ words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', ...
Select strings ( presumably filenames ) from self. files that match pattern a Unix - style wildcard ( glob ) pattern.
def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' ...
Remove strings ( presumably filenames ) from files that match pattern.
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place...
Translate a shell - like wildcard pattern to a compiled regular expression.
def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it'...
Translate a shell - like glob pattern to a regular expression.
def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmat...