text
stringlengths
81
112k
Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the m...
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation ...
Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmember...
Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mt...
Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above...
Extract the TarInfo object tarinfo to a physical file called targetpath. def _extract_member(self, tarinfo, targetpath, set_attrs=True): """Extract the TarInfo object tarinfo to a physical file called targetpath. """ # Fetch the TarInfo object for the given name # ...
Make a directory called targetpath. def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except Envi...
Make a file called targetpath. def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) target = bltn_open(targetpath, "wb") if tarinfo.sparse is not None: for offset, size in tarinf...
Make a file from a TarInfo object with an unknown type at targetpath. def makeunknown(self, tarinfo, targetpath): """Make a file from a TarInfo object with an unknown type at targetpath. """ self.makefile(tarinfo, targetpath) self._dbg(1, "tarfile: Unknown file typ...
Make a fifo called targetpath. def makefifo(self, tarinfo, targetpath): """Make a fifo called targetpath. """ if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError("fifo not supported by system")
Make a character or block device called targetpath. def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError("special devices not supported by system") mo...
Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitati...
Set owner of targetpath according to tarinfo. def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo....
Set file permissions of targetpath according to tarinfo. def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except EnvironmentError as e: ...
Set modification time of targetpath according to tarinfo. def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) ...
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no...
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ ...
Read through the entire archive file and look for readable members. def _load(self): """Read through the entire archive file and look for readable members. """ while True: tarinfo = self.next() if tarinfo is None: break self....
Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise IOError("%s is closed...
Find the target member of a symlink or hardlink member in the archive. def _find_link_target(self, tarinfo): """Find the target member of a symlink or hardlink member in the archive. """ if tarinfo.issym(): # Always search the entire archive. linkna...
Write debugging output to sys.stderr. def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: print(msg, file=sys.stderr)
Returns the absolute path to a given relative path. def path_to(self, p): """Returns the absolute path to a given relative path.""" if os.path.isabs(p): return p return os.sep.join([self._original_dir, p])
Returns a list of packages for pip-tools to consume. def _build_package_list(self, package_section): """Returns a list of packages for pip-tools to consume.""" from pipenv.vendor.requirementslib.utils import is_vcs ps = {} # TODO: Separate the logic for showing packages from the filters...
Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash) def _get_virtualenv_hash(self, name): """Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash) """ def get_name(name, location): name = ...
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 (call clear_pipfile_cache() afterwards if mutating) 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 g...
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"): ...
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=...
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)...
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.lockfi...
Given a source, find it. source can be a url or an index name. 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) ...
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) ...
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": ...
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",...
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 ...
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_co...
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...
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)]) omd.load([(4,4), (4,44), (5,5)]) omd.al...
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'), (2,222), (1,111)]) omd.allitems() == [(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...
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>...
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 are added for <key> and <key> will not be added as a key. ...
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]) omd.allitems() == [(1, 1), (1, 11), (1, 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 repl...
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.allitems() == [(1, 11)] Returns: <self>. def remo...
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 = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.pop...
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 dictionary. If <key> no longer has any values after a popvalue() call, <key> is ...
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()[0] is popped if <last> is False or allitems()[-1] is p...
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 p...
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 provi...
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: omd = omdict([(1,1), (1,11), (1,111), (2,2), (...
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,1...
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 in the dictionary. Returns: An iterator over eve...
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. def iterallvalues(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,1...
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>. def reverse(self): """ Reverse the order of all items i...
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: se...
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 or `-1` to indicate that this position shou...
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'|"([^"\\]*(?:\\.[^"\\]*)*)"' ...
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``. The `obj` can be used to identify the option in the orde...
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. def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to i...
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 multip...
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 :class:`DependencyGraph` instance def make_grap...
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 def get_dependent_dists(dists, dist): """Recursively generate a list of distributions from *dists* th...
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 def get_required_dists(dists, dist): """Recursively generate a list of distributions from *dists* that...
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.ve...
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.setdefa...
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...
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. :parameter name: is converted to a standard distributi...
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:`EggInfoDistribution` instances def get_distributions(self)...
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:`EggInfoDistribution` or ``None`` def get_distributio...
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 values are expected. If the directory is not found, returns ``None``. ...
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_resour...
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. def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a partic...
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 = sel...
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 requiremen...
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 ``None``. Examples of valid values are ``'sha1'``, ...
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): """ Ge...
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 informa...
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. def read_exports(self): """ Read exports data from a file in .ini f...
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): """ ...
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. :return: The absolute path where the resource is to be f...
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. def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the `...
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 ...
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 installat...
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 f...
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; If *path* is an absolute path and doesn't start ...
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 def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and r...
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 ...
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 list_installed_files(self): """ Iterates over the ``installed-files.txt`` entries and returns a tuple ``(path, hash, size)`` fo...
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 ``True``, each returned path is transformed in...
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.InstalledDistribution` or :class:`...
Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str`` def add_missing(self, distribution, requirement): """ ...
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) ...
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 :type skip_disconnected: ``bool`` def to_dot(sel...
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 s...
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. def encode_unicode(f): """Cerberus error messages expect regular binar...
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 app...
Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` 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) sel...