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 members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: print(filemode(tarinfo.mode), end=' ') print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): print("%10s" % ("%d,%d" \ % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: print("%10d" % tarinfo.size, end=' ') print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6], end=' ') print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') if verbose: if tarinfo.issym(): print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): print("link to", tarinfo.linkname, end=' ') print()
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 about the file size. def addfile(self, tarinfo, fileobj=None): """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 about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
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 getmembers(). def extractall(self, path=".", members=None): """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 getmembers(). """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0o700 # Do not set_attrs directories, as we will do that further down self.extract(tarinfo, path, set_attrs=not tarinfo.isdir()) # Reverse sort directories. directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
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, mtime, mode) are set unless `set_attrs' is False. def extract(self, member, path="", set_attrs=True): """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, mtime, mode) are set unless `set_attrs' is False. """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member # Prepare the link target for makelink(). if tarinfo.islnk(): tarinfo._link_target = os.path.join(path, tarinfo.linkname) try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name), set_attrs=set_attrs) except EnvironmentError as e: if self.errorlevel > 0: raise else: if e.filename is None: self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
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, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() def extractfile(self, member): """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, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member if tarinfo.isreg(): return self.fileobject(self, tarinfo) elif tarinfo.type not in SUPPORTED_TYPES: # If a member's type is unknown, it is treated as a # regular file. return self.fileobject(self, tarinfo) elif tarinfo.islnk() or tarinfo.issym(): if isinstance(self.fileobj, _Stream): # A small but ugly workaround for the case that someone tries # to extract a (sym)link as a file-object from a non-seekable # stream of tar blocks. raise StreamError("cannot extract (sym)link as file object") else: # A (sym)link's file object is its target's file object. return self.extractfile(self._find_link_target(tarinfo)) else: # If there's no data associated with the member (directory, chrdev, # blkdev, etc.), return None instead of a file object. return None
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 # and build the destination pathname, replacing # forward slashes to platform specific separators. targetpath = targetpath.rstrip("/") targetpath = targetpath.replace("/", os.sep) # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): # Create directories that are not part of the archive with # default permissions. os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) else: self._dbg(1, tarinfo.name) if tarinfo.isreg(): self.makefile(tarinfo, targetpath) elif tarinfo.isdir(): self.makedir(tarinfo, targetpath) elif tarinfo.isfifo(): self.makefifo(tarinfo, targetpath) elif tarinfo.ischr() or tarinfo.isblk(): self.makedev(tarinfo, targetpath) elif tarinfo.islnk() or tarinfo.issym(): self.makelink(tarinfo, targetpath) elif tarinfo.type not in SUPPORTED_TYPES: self.makeunknown(tarinfo, targetpath) else: self.makefile(tarinfo, targetpath) if set_attrs: self.chown(tarinfo, targetpath) if not tarinfo.issym(): self.chmod(tarinfo, targetpath) self.utime(tarinfo, targetpath)
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 EnvironmentError as e: if e.errno != errno.EEXIST: raise
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 tarinfo.sparse: target.seek(offset) copyfileobj(source, target, size) else: copyfileobj(source, target, tarinfo.size) target.seek(tarinfo.size) target.truncate() target.close()
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 type %r, " \ "extracted as regular file." % tarinfo.type)
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") mode = tarinfo.mode if tarinfo.isblk(): mode |= stat.S_IFBLK else: mode |= stat.S_IFCHR os.mknod(targetpath, mode, os.makedev(tarinfo.devmajor, tarinfo.devminor))
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 limitation), we try to make a copy of the referenced file instead of a link. """ try: # For systems that support symbolic and hard links. if tarinfo.issym(): os.symlink(tarinfo.linkname, targetpath) else: # See extract(). if os.path.exists(tarinfo._link_target): os.link(tarinfo._link_target, targetpath) else: self._extract_member(self._find_link_target(tarinfo), targetpath) except symlink_exception: if tarinfo.issym(): linkpath = os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname) else: linkpath = tarinfo.linkname else: try: self._extract_member(self._find_link_target(tarinfo), targetpath) except KeyError: raise ExtractError("unable to resolve link inside archive")
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.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError as e: raise ExtractError("could not change owner")
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: raise ExtractError("could not change mode")
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)) except EnvironmentError as e: raise ExtractError("could not change modification time")
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 more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m # Read the next block. self.fileobj.seek(self.offset) tarinfo = None while True: try: tarinfo = self.tarinfo.fromtarfile(self) except EOFHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue except InvalidHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue elif self.offset == 0: raise ReadError(str(e)) except EmptyHeaderError: if self.offset == 0: raise ReadError("empty file") except TruncatedHeaderError as e: if self.offset == 0: raise ReadError(str(e)) except SubsequentHeaderError as e: raise ReadError(str(e)) break if tarinfo is not None: self.members.append(tarinfo) else: self._loaded = True return tarinfo
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. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member
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._loaded = True
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" % self.__class__.__name__) if mode is not None and self.mode not in mode: raise IOError("bad operation for mode %r" % self.mode)
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. linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname limit = None else: # Search the archive before the link, because a hard link is # just a reference to an already archived file. linkname = tarinfo.linkname limit = tarinfo member = self._getmember(linkname, tarinfo=limit, normalize=True) if member is None: raise KeyError("linkname %r not found" % linkname) return member
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 for supplying pip-tools for k, v in self.parsed_pipfile.get(package_section, {}).items(): # Skip editable VCS deps. if hasattr(v, "keys"): # When a vcs url is gven without editable it only appears as a key # Eliminate any vcs, path, or url entries which are not editable # Since pip-tools can't do deep resolution on them, even setuptools-installable ones if ( is_vcs(v) or is_vcs(k) or (is_installable_file(k) or is_installable_file(v)) or any( ( prefix in v and (os.path.isfile(v[prefix]) or is_valid_url(v[prefix])) ) for prefix in ["path", "file"] ) ): # If they are editable, do resolve them if "editable" not in v: # allow wheels to be passed through if not ( hasattr(v, "keys") and v.get("path", v.get("file", "")).endswith(".whl") ): continue ps.update({k: v}) else: ps.update({k: v}) else: ps.update({k: v}) else: # Since these entries have no attributes we know they are not editable # So we can safely exclude things that need to be editable in order to be resolved # First exclude anything that is a vcs entry either in the key or value if not ( any(is_vcs(i) for i in [k, v]) or # Then exclude any installable files that are not directories # Because pip-tools can resolve setup.py for example any(is_installable_file(i) for i in [k, v]) or # Then exclude any URLs because they need to be editable also # Things that are excluded can only be 'shallow resolved' any(is_valid_url(i) for i in [k, v]) ): ps.update({k: v}) return ps
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 = self._sanitize(name) hash = hashlib.sha256(location.encode()).digest()[:6] encoded_hash = base64.urlsafe_b64encode(hash).decode() return name, encoded_hash[:8] clean_name, encoded_hash = get_name(name, self.pipfile_location) venv_name = "{0}-{1}".format(clean_name, encoded_hash) # This should work most of the time for # Case-sensitive filesystems, # In-project venv # "Proper" path casing (on non-case-sensitive filesystems). if ( not fnmatch.fnmatch("A", "a") or self.is_venv_in_project() or get_workon_home().joinpath(venv_name).exists() ): return clean_name, encoded_hash # Check for different capitalization of the same project. for path in get_workon_home().iterdir(): if not is_virtual_environment(path): continue try: env_name, hash_ = path.name.rsplit("-", 1) except ValueError: continue if len(hash_) != 8 or env_name.lower() != name.lower(): continue return get_name(env_name, self.pipfile_location.replace(name, env_name)) # Use the default if no matching env exists. return clean_name, encoded_hash
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 get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key not in _pipfile_cache: parsed = self._parse_pipfile(contents) _pipfile_cache[cache_key] = parsed return _pipfile_cache[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 key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
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(make_option_group(index_group, config_parser)) install = config_parser.option_groups[0] indexes = ( " ".join(install.get_option("--extra-index-url").default) .lstrip("\n") .split("\n") ) sources = [DEFAULT_SOURCE,] for i, index in enumerate(indexes): if not index: continue source_name = "pip_index_{}".format(i) verify_ssl = index.startswith("https") sources.append( {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name} ) data = { u"source": sources, # Default packages. u"packages": {}, u"dev-packages": {}, } # Default requires. required_python = python if not python: if self.virtualenv_location: required_python = self.which("python", self.virtualenv_location) else: required_python = self.which("python") version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION if version and len(version) >= 3: data[u"requires"] = {"python_version": version[: len("2.7")]} self.write_toml(data)
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: document = tomlkit.document() for section in ("packages", "dev-packages"): document[section] = tomlkit.container.Table() # Convert things to inline tables — fancy :) for package in data.get(section, {}): if hasattr(data[section][package], "keys"): table = tomlkit.inline_table() table.update(data[section][package]) document[section][package] = table else: document[section][package] = tomlkit.string(data[section][package]) formatted_data = tomlkit.dumps(document).rstrip() if ( vistir.compat.Path(path).absolute() == vistir.compat.Path(self.pipfile_location).absolute() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
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_kwargs ) as f: f.write(s) # Write newline at end of document. GH-319. # Only need '\n' here; the file object handles the rest. if not s.endswith(u"\n"): f.write(u"\n")
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) except SourceNotFound: source = self.get_source(url=source) else: source = self.get_source(url=source) return 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) for name in section.keys(): if pep423_name(name) == package_name: return name return None
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} else: return source["name"] = self.src_name_from_url(index) # Add the package to the group. if "source" not in p: p["source"] = [source] else: p["source"].append(source) # Write Pipfile. self.write_toml(p)
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)] # Replace each package with proper casing. for dep in unknown_names: try: # Get new casing for package name. new_casing = proper_case(dep) except IOError: # Unable to normalize package name. continue if new_casing != dep: changed_values = True self.register_proper_name(new_casing) # Replace old value with new value. old_value = section[dep] section[new_casing] = old_value del section[dep] # Return whether or not values have been changed. return changed_values
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 string is returned. """ head = list(islice(nodes, 2)) if not head: return None if len(head) == 1: out = head[0] else: out = u''.join([text_type(v) for v in chain(head, nodes)]) try: return literal_eval(out) except (ValueError, SyntaxError, MemoryError): return out
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 finalize_context = getattr(finalize, 'contextfunction', False) finalize_eval = getattr(finalize, 'evalcontextfunction', False) finalize_env = getattr(finalize, 'environmentfunction', False) if finalize is not None: if finalize_context or finalize_eval: const_finalize = None elif finalize_env: def const_finalize(x): return finalize(self.environment, x) else: const_finalize = finalize else: def const_finalize(x): return x # If we are inside a frame that requires output checking, we do so. outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # Try to evaluate as many chunks as possible into a static string at # compile time. body = [] for child in node.nodes: try: if const_finalize is None: raise nodes.Impossible() const = child.as_const(frame.eval_ctx) if not has_safe_repr(const): raise nodes.Impossible() except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, because otherwise the as_const # function would raise an Impossible exception at that point try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = const_finalize(const) except Exception: # if something goes wrong here we evaluate the node at runtime # for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(native_concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ',') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') close += 1 self.visit(item, frame) if close > 0: self.write(')' * close) if frame.buffer is not None: self.write(',') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(native_concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') self.indent() for argument in arguments: self.newline(argument) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') elif finalize_eval: self.write('context.eval_ctx, ') elif finalize_env: self.write('environment, ') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent()
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.allitems() == [(4,4), (4,44), (5,5)] Returns: <self>. 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)]) omd.load([(4,4), (4,44), (5,5)]) omd.allitems() == [(4,4), (4,44), (5,5)] Returns: <self>. """ self.clear() self.updateall(*args, **kwargs) return self
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'), (2, 'two'), (2, 222), (1, 111)] Returns: <self>. 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'), (2,222), (1,111)]) omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)] Returns: <self>. """ self._update_updateall(False, *args, **kwargs) return self
<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 have yet to be # marked for replacement, mark that item's value to be replaced by # <value> by appending it to <replacements>. if key in self and key not in replacements: replacements[key] = [value] elif (key in self and not replace_at_most_one and len(replacements[key]) < len(self.values(key))): replacements[key].append(value) else: if replace_at_most_one: replacements[key] = [value] else: leftovers.append((key, value))
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]] return 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. Returns: List of <key>'s values if <key> exists in the dictionary, otherwise <default>. 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 are added for <key> and <key> will not be added as a key. Returns: List of <key>'s values if <key> exists in the dictionary, otherwise <default>. """ if key in self: return self.getlist(key) self.addlist(key, defaultlist) return defaultlist
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)] omd.addlist(2, [2]) omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)] Returns: <self>. 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]) omd.allitems() == [(1, 1), (1, 11), (1, 111)] omd.addlist(2, [2]) omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)] Returns: <self>. """ for value in valuelist: self.add(key, value) return self
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 of the list of all items. If values is an empty list, [], <key> is deleted, equivalent in action to del self[<key>]. Example: omd = omdict([(1,1), (2,2)]) omd.setlist(1, [11, 111]) omd.allitems() == [(1,11), (2,2), (1,111)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, [None]) omd.allitems() == [(1,None), (2,2)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, []) omd.allitems() == [(2,2)] Returns: <self>. 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 have corresponding items with <key> to replace are appended to the end of the list of all items. If values is an empty list, [], <key> is deleted, equivalent in action to del self[<key>]. Example: omd = omdict([(1,1), (2,2)]) omd.setlist(1, [11, 111]) omd.allitems() == [(1,11), (2,2), (1,111)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, [None]) omd.allitems() == [(1,None), (2,2)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, []) omd.allitems() == [(2,2)] Returns: <self>. """ if not values and key in self: self.pop(key) else: it = zip_longest( list(self._map.get(key, [])), values, fillvalue=_absent) for node, value in it: if node is not _absent and value is not _absent: node.value = value elif node is _absent: self.add(key, value) elif value is _absent: self._map[key].remove(node) self._items.removenode(node) return self
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 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.allitems() == [(1, 11)] Returns: <self>. """ self.setlist(key, [v for v in self.getlist(key) if v not in values]) return self
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.poplist(1) == [1, 11, 111] omd.allitems() == [(2,2), (3,3)] omd.poplist(2) == [2] omd.allitems() == [(3,3)] Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. Returns: List of <key>'s values. 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 = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplist(1) == [1, 11, 111] omd.allitems() == [(2,2), (3,3)] omd.poplist(2) == [2] omd.allitems() == [(3,3)] Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. Returns: List of <key>'s values. """ if key in self: values = self.getlist(key) del self._map[key] for node, nodekey, nodevalue in self._items: if nodekey == key: self._items.removenode(node) return values elif key not in self._map and default is not _absent: return default raise KeyError(key)
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 removed from the dictionary. If <key> isn't in the dictionary and <default> was provided, return default. KeyError is raised if <default> is not provided and <key> is not in the dictionary. ValueError is raised if <value> is provided but isn't a value for <key>. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)]) omd.popvalue(1) == 111 omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)] omd.popvalue(1, last=False) == 1 omd.allitems() == [(1,11), (2,2), (3,3), (2,22)] omd.popvalue(2, 2) == 2 omd.allitems() == [(1,11), (3,3), (2,22)] omd.popvalue(1, 11) == 11 omd.allitems() == [(3,3), (2,22)] omd.popvalue('not a key', default='sup') == 'sup' Params: last: Boolean whether to return <key>'s first value (<last> is False) or last value (<last> is True). Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. ValueError if <value> isn't a value for <key>. Returns: The first or last of <key>'s values. 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 dictionary. If <key> no longer has any values after a popvalue() call, <key> is removed from the dictionary. If <key> isn't in the dictionary and <default> was provided, return default. KeyError is raised if <default> is not provided and <key> is not in the dictionary. ValueError is raised if <value> is provided but isn't a value for <key>. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)]) omd.popvalue(1) == 111 omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)] omd.popvalue(1, last=False) == 1 omd.allitems() == [(1,11), (2,2), (3,3), (2,22)] omd.popvalue(2, 2) == 2 omd.allitems() == [(1,11), (3,3), (2,22)] omd.popvalue(1, 11) == 11 omd.allitems() == [(3,3), (2,22)] omd.popvalue('not a key', default='sup') == 'sup' Params: last: Boolean whether to return <key>'s first value (<last> is False) or last value (<last> is True). Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. ValueError if <value> isn't a value for <key>. Returns: The first or last of <key>'s values. """ def pop_node_with_index(key, index): node = self._map[key].pop(index) if not self._map[key]: del self._map[key] self._items.removenode(node) return node if key in self: if value is not _absent: if last: pos = self.values(key)[::-1].index(value) else: pos = self.values(key).index(value) if pos == -1: raise ValueError(value) else: index = (len(self.values(key)) - 1 - pos) if last else pos return pop_node_with_index(key, index).value else: return pop_node_with_index(key, -1 if last else 0).value elif key not in self._map and default is not _absent: return default raise KeyError(key)
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 popped if <last> is True. Any remaining items with the same key remain. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem() == (3,3) omd.popitem(fromall=False, last=False) == (1,1) omd.popitem(fromall=False, last=False) == (2,2) omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem(fromall=True, last=False) == (1,1) omd.popitem(fromall=True, last=False) == (1,11) omd.popitem(fromall=True, last=True) == (3,3) omd.popitem(fromall=True, last=False) == (1,111) Params: fromall: Whether to pop an item from items() (<fromall> is True) or allitems() (<fromall> is False). last: Boolean whether to pop the first item or last item of items() or allitems(). Raises: KeyError if the dictionary is empty. Returns: The first or last item from item() or allitem(). 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()[0] is popped if <last> is False or allitems()[-1] is popped if <last> is True. Any remaining items with the same key remain. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem() == (3,3) omd.popitem(fromall=False, last=False) == (1,1) omd.popitem(fromall=False, last=False) == (2,2) omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem(fromall=True, last=False) == (1,1) omd.popitem(fromall=True, last=False) == (1,11) omd.popitem(fromall=True, last=True) == (3,3) omd.popitem(fromall=True, last=False) == (1,111) Params: fromall: Whether to pop an item from items() (<fromall> is True) or allitems() (<fromall> is False). last: Boolean whether to pop the first item or last item of items() or allitems(). Raises: KeyError if the dictionary is empty. Returns: The first or last item from item() or allitem(). """ if not self._items: raise KeyError('popitem(): %s is empty' % self.__class__.__name__) if fromall: node = self._items[-1 if last else 0] key = node.key return key, self.popvalue(key, last=last) else: key = list(self._map.keys())[-1 if last else 0] return key, self.pop(key)
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. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplistitem(last=True) == (3,[3]) omd.poplistitem(last=False) == (1,[1,11,111]) Params: last: Boolean whether to pop the first or last key and its associated list of values. Raises: KeyError if the dictionary is empty. Returns: A two-tuple comprised of the first or last key and its associated list of values. 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 comprised of keys()[-1] and its list of values is popped and returned. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplistitem(last=True) == (3,[3]) omd.poplistitem(last=False) == (1,[1,11,111]) Params: last: Boolean whether to pop the first or last key and its associated list of values. Raises: KeyError if the dictionary is empty. Returns: A two-tuple comprised of the first or last key and its associated list of values. """ if not self._items: s = 'poplistitem(): %s is empty' % self.__class__.__name__ raise KeyError(s) key = self.keys()[-1 if last else 0] return key, self.poplist(key)
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 _absent and key in self._map: return self.getlist(key) return list(self.itervalues())
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), (3,3)]) omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111) omd.iteritems() -> (1,1) -> (2,2) -> (3,3) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over the items() of the dictionary, or only items with the key <key> if <key> is provided. 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: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111) omd.iteritems() -> (1,1) -> (2,2) -> (3,3) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over the items() of the dictionary, or only items with the key <key> if <key> is provided. """ if key is not _absent: if key in self: items = [(node.key, node.value) for node in self._map[key]] return iter(items) raise KeyError(key) items = six.iteritems(self._map) return iter((key, nodes[0].value) for (key, nodes) in items)
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.itervalues(1) -> 1 -> 11 -> 111 omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3 Raises: KeyError if <key> is provided and isn't in the dictionary. Returns: An iterator over the values() of the dictionary, or only the values of key <key> if <key> is provided. 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.itervalues(1) -> 1 -> 11 -> 111 omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3 Raises: KeyError if <key> is provided and isn't in the dictionary. Returns: An iterator over the values() of the dictionary, or only the values of key <key> if <key> is provided. """ if key is not _absent: if key in self: return iter([node.value for node in self._map[key]]) raise KeyError(key) return iter([nodes[0].value for nodes in six.itervalues(self._map)])
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 every item in the diciontary. If <key> is provided, only items with the key <key> are iterated over. 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 in the dictionary. Returns: An iterator over every item in the diciontary. If <key> is provided, only items with the key <key> are iterated over. ''' if key is not _absent: # Raises KeyError if <key> is not in self._map. return self.iteritems(key) return self._items.iteritems()
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,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: if key in self: return iter(self.getlist(key)) raise KeyError(key) return self._items.itervalues()
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 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 six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
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 = set() if reqs: ws = WorkingSet(self._lib_dirs) for req in reqs: try: if ws.find(Requirement.parse(req)) is None: missing.add(req) except VersionConflict as e: conflicting.add((str(e.args[0].as_requirement()), str(e.args[1]))) return conflicting, missing
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 should eat up all the remainders. Missing items are filled with `None`. 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 or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args)
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.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv
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 order list that is returned from the parser. 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``, ``append``, ``appnd_const`` or ``count``. 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 opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
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 identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
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 times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order
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_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 :class:`DependencyGraph` instance """ scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_distribution(dist) for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) provided.setdefault(name, []).append((version, dist)) # now make the edges for dist in dists: requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires) for req in requires: try: matcher = scheme.matcher(req) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive matched = False if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: graph.add_edge(dist, provider, req) matched = True break if not matched: graph.add_missing(dist, req) return graph
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* 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 DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) dep = [dist] # dependent distributions todo = graph.reverse_list[dist] # list of nodes we should inspect while todo: d = todo.pop() dep.append(d) for succ in graph.reverse_list[d]: if succ not in dep: todo.append(succ) dep.pop(0) # remove dist from dep, was there to prevent infinite loops return dep
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 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 DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) req = [] # required distributions todo = graph.adjacency_list[dist] # list of nodes we should inspect while todo: d = todo.pop()[0] req.append(d) for pred in graph.adjacency_list[d]: if pred not in req: todo.append(pred) return req
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' return Distribution(md)
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 self._yield_distributions(): if isinstance(dist, InstalledDistribution): self._cache.add(dist) else: self._cache_egg.add(dist) if gen_dist: self._cache.generated = True if gen_egg: self._cache_egg.generated = True
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 distribution name by replacing any runs of non- alphanumeric characters with a single ``'-'``. :type name: string :parameter version: is converted to a standard version string. Spaces become dots, and all other non-alphanumeric characters (except dots) become dashes, with runs of multiple dashes condensed to a single dash. :type version: string :returns: directory name :rtype: string 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. :parameter name: is converted to a standard distribution name by replacing any runs of non- alphanumeric characters with a single ``'-'``. :type name: string :parameter version: is converted to a standard version string. Spaces become dots, and all other non-alphanumeric characters (except dots) become dashes, with runs of multiple dashes condensed to a single dash. :type version: string :returns: directory name :rtype: string""" name = name.replace('-', '_') return '-'.join([name, version]) + DISTINFO_EXT
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): """ 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 """ if not self._cache_enabled: for dist in self._yield_distributions(): yield dist else: self._generate_cache() for dist in self._cache.path.values(): yield dist if self._include_egg: for dist in self._cache_egg.path.values(): yield dist
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_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:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
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``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string 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 values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string """ matcher = None if version is not None: try: matcher = self._scheme.matcher('%s (%s)' % (name, version)) except ValueError: raise DistlibException('invalid name or version: %r, %r' % (name, version)) for dist in self.get_distributions(): # We hit a problem on Travis where enum34 was installed and doesn't # have a provides attribute ... if not hasattr(dist, 'provides'): logger.debug('No "provides": %s', dist) else: provided = dist.provides for p in provided: p_name, p_ver = parse_name_and_version(p) if matcher is None: if p_name == name: yield dist break else: if p_name == name and matcher.match(p_ver): yield dist break
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. :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 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_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: yield d[name] else: for v in d.values(): yield v
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) return plist
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 what's passed to the matcher r = parse_requirement(req) scheme = get_scheme(self.metadata.scheme) try: matcher = scheme.matcher(r.requirement) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive result = False for p in self.provides: p_name, p_ver = parse_name_and_version(p) if p_name != name: continue try: result = matcher.match(p_ver) break except UnsupportedVersionError: pass return result
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'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str 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 ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str """ if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(data).digest() digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii') return '%s%s' % (prefix, digest)
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). """ results = [] r = self.get_distinfo_resource('RECORD') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as record_reader: # Base location is parent dir of .dist-info dir #base_location = os.path.dirname(self.path) #base_location = os.path.abspath(base_location) for row in record_reader: missing = [None for i in range(len(row), 3)] path, checksum, size = row + missing #if not os.path.isabs(path): # path = path.replace('/', os.sep) # path = os.path.join(base_location, path) results.append((path, checksum, size)) return results
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. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: result = self.read_exports() return result
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 format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return 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. """ rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
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 found. 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. :return: The absolute path where the resource is to be found. """ r = self.get_distinfo_resource('RESOURCES') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as resources_reader: for relative, destination in resources_reader: if relative == relative_path: return destination raise KeyError('no resource file with relative path %r ' 'is installed' % relative_path)
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 ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
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 expected value and the actual value. 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' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] base = os.path.dirname(self.path) record_path = self.get_distinfo_file('RECORD') for path, hash_value, size in self.list_installed_files(): if not os.path.isabs(path): path = os.path.join(base, path) if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) elif os.path.isfile(path): actual_size = str(os.path.getsize(path)) if size and actual_size != size: mismatches.append((path, 'size', size, actual_size)) elif hash_value: if '=' in hash_value: hasher = hash_value.split('=', 1)[0] else: hasher = None with open(path, 'rb') as f: actual_hash = self.get_hash(f.read(), hasher) if actual_hash != hash_value: mismatches.append((path, 'hash', hash_value, actual_hash)) return mismatches
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 the case of the 'namespace' key, this would be a list of absolute paths for the roots of namespace packages in this distribution. The first time this property is accessed, the relevant information is read from the SHARED file in the .dist-info directory. 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 paths selected by the user at installation time (e.g. via command-line arguments). In the case of the 'namespace' key, this would be a list of absolute paths for the roots of namespace packages in this distribution. The first time this property is accessed, the relevant information is read from the SHARED file in the .dist-info directory. """ result = {} shared_path = os.path.join(self.path, 'SHARED') if os.path.isfile(shared_path): with codecs.open(shared_path, 'r', encoding='utf-8') as f: lines = f.read().splitlines() for line in lines: key, value = line.split('=', 1) if key == 'namespace': result.setdefault(key, []).append(value) else: result[key] = value return result
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 actually written. :return: The path of the file written to. """ shared_path = os.path.join(self.path, 'SHARED') logger.info('creating %s', shared_path) if dry_run: return None lines = [] for key in ('prefix', 'lib', 'headers', 'scripts', 'data'): path = paths[key] if os.path.isdir(paths[key]): lines.append('%s=%s' % (key, path)) for ns in paths.get('namespace', ()): lines.append('namespace=%s' % ns) with codecs.open(shared_path, 'w', encoding='utf-8') as f: f.write('\n'.join(lines)) return shared_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; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str 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; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str """ # Check if it is an absolute path # XXX use relpath, add tests if path.find(os.sep) >= 0: # it's an absolute path? distinfo_dirname, path = path.split(os.sep)[-2:] if distinfo_dirname != self.path.split(os.sep)[-1]: raise DistlibException( 'dist-info file %r does not belong to the %r %s ' 'distribution' % (path, self.name, self.version)) # The file must be relative if path not in DIST_FILES: raise DistlibException('invalid path for a dist-info file: ' '%r at %r' % (path, self.path)) return os.path.join(self.path, 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. :returns: iterator of paths 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(self.path) for path, checksum, size in self._get_records(): # XXX add separator or use real relpath algo if not os.path.isabs(path): path = os.path.join(base, path) if path.startswith(self.path): yield path
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 expected value and the actual value. 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' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) return mismatches
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)`` for each line. :returns: a list of (path, hash, size) """ def _md5(path): f = open(path, 'rb') try: content = f.read() finally: f.close() return hashlib.md5(content).hexdigest() def _size(path): return os.stat(path).st_size record_path = os.path.join(self.path, 'installed-files.txt') result = [] if os.path.exists(record_path): with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() p = os.path.normpath(os.path.join(self.path, line)) # "./" is present as a marker between installed files # and installation metadata files if not os.path.exists(p): logger.warning('Non-existent file: %s', p) if p.endswith(('.pyc', '.pyo')): continue #otherwise fall through and fail if not os.path.isdir(p): result.append((p, _md5(p), _size(p))) result.append((record_path, None, None)) return result
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 into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths 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 ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths """ record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): skip = True with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line == './': skip = False continue if not skip: p = os.path.normpath(os.path.join(self.path, line)) if p.startswith(self.path): if absolute: yield p else: yield line
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:`distutils2.database.EggInfoDistribution` :type label: ``str`` or ``None`` 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.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type label: ``str`` or ``None`` """ self.adjacency_list[x].append((y, label)) # multiple edges are allowed, so be careful if x not in self.reverse_list[y]: self.reverse_list[y].append(x)
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): """ Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str`` """ logger.debug('%s missing %r', distribution, requirement) self.missing.setdefault(distribution, []).append(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) output.append(' ' * level + str(dist)) suboutput = self.repr_node(other, level + 1) subs = suboutput.split('\n') output.extend(subs[1:]) return '\n'.join(output)
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(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 :type skip_disconnected: ``bool`` """ disconnected = [] f.write("digraph dependencies {\n") for dist, adjs in self.adjacency_list.items(): if len(adjs) == 0 and not skip_disconnected: disconnected.append(dist) for other, label in adjs: if not label is None: f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, other.name, label)) else: f.write('"%s" -> "%s"\n' % (dist.name, other.name)) if not skip_disconnected and len(disconnected) > 0: f.write('subgraph disconnected {\n') f.write('label = "Disconnected"\n') f.write('bgcolor = red\n') for dist in disconnected: f.write('"%s"' % dist.name) f.write('\n') f.write('}\n') f.write('}\n')
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 have circular dependencies and so form a cycle. """ result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): alist[k] = v[:] while True: # See what we can remove in this run to_remove = [] for k, v in list(alist.items())[:]: if not v: to_remove.append(k) del alist[k] if not to_remove: # What's left in alist (if anything) is a cycle. break # Remove from the adjacency list of others for k, v in alist.items(): alist[k] = [(d, r) for d, r in v if d not in to_remove] logger.debug('Moving to result: %s', ['%s (%s)' % (d.name, d.version) for d in to_remove]) result.extend(to_remove) return result, list(alist.keys())
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 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, error): def _encode(value): """Helper encoding unicode strings into binary utf-8""" if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) error.document_path = _encode(error.document_path) error.schema_path = _encode(error.schema_path) error.constraint = _encode(error.constraint) error.value = _encode(error.value) error.info = _encode(error.info) return f(obj, error) return wrapped if PYTHON_VERSION < 3 else f
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 self.child_errors: i = error.schema_path[len(self.schema_path)] result[i].append(error) return result
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) self.errors.sort() else: super(ErrorTree, self).add(error)