text
stringlengths
81
112k
zip a directory tree into a BytesIO object def zip_dir(directory): """zip a directory tree into a BytesIO object""" result = io.BytesIO() dlen = len(directory) with ZipFile(result, "w") as zf: for root, dirs, files in os.walk(directory): for name in files: full = os....
Extended globbing function that supports ** and {opt1,opt2,opt3}. def iglob(path_glob): """Extended globbing function that supports ** and {opt1,opt2,opt3}.""" if _CHECK_RECURSIVE_GLOB.search(path_glob): msg = """invalid glob %r: recursive glob "**" must be used alone""" raise ValueError(msg % ...
Tell if the target is newer than the source. Returns true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Returns false if both exist and 'target' is the same age or younger than 'source'. Raise PackagingFileError if 'source' ...
Copy a file respecting dry-run and force flags. def copy_file(self, infile, outfile, check=True): """Copy a file respecting dry-run and force flags. """ self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying %s to %s', infile, outfile) if not self.dry_run: ms...
Commit recorded changes, turn off recording, return changes. def commit(self): """ Commit recorded changes, turn off recording, return changes. """ assert self.record result = self.files_written, self.dirs_created self._init_record() return result
Clear the cache. def clear(self): """ Clear the cache. """ not_removed = [] for fn in os.listdir(self.base): fn = os.path.join(self.base, fn) try: if os.path.islink(fn) or os.path.isfile(fn): os.remove(fn) ...
Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list ...
Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be removed. def remove(self, event, subscriber): """ Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be...
Publish a event and return a list of values returned by its subscribers. :param event: The event to publish. :param args: The positional arguments to pass to the event's subscribers. :param kwargs: The keyword arguments to pass to the event's ...
Default converter for the inc:// protocol. def inc_convert(self, value): """Default converter for the inc:// protocol.""" if not os.path.isabs(value): value = os.path.join(self.base, value) with codecs.open(value, 'r', encoding='utf-8') as f: result = json.load(f) ...
Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or writ...
Query the PyPI RSS feed and return a list of XML items. def _get(pypi_server): """ Query the PyPI RSS feed and return a list of XML items. """ response = requests.get(pypi_server) if response.status_code >= 300: raise HTTPError(status_code=response.status_code, ...
Constructs a request to the PyPI server and returns a list of :class:`yarg.parse.Package`. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> yarg.newest_packages() [<Package yarg>, <Package gray>, <Package ragy>] def newest_packages( pypi_server="https:/...
Produce a mapping of identifier: requirement from the section. def _get_requirements(model, section_name): """Produce a mapping of identifier: requirement from the section. """ if not model: return {} return {identify_requirment(r): r for r in ( requirementslib.Requirement.from_pipfile(...
Produce a mapping containing all candidates derived from `identifiers`. `identifiers` should provide a collection of requirement identifications from a section (i.e. `packages` or `dev-packages`). This function uses `trace` to filter out candidates in the state that are present because of an entry in t...
Lock specified (abstract) requirements into (concrete) candidates. The locking procedure consists of four stages: * Resolve versions and dependency graph (powered by ResolveLib). * Walk the graph to determine "why" each candidate came to be, i.e. what top-level requirements result in...
Configures and sets up all of the logging Returns the requested logging level, as its integer value. def setup_logging(verbosity, no_color, user_log_file): """Configures and sets up all of the logging Returns the requested logging level, as its integer value. """ # Determine the level to be logg...
Calls the standard formatter, but will indent all of the log messages by our current indentation level. def format(self, record): """ Calls the standard formatter, but will indent all of the log messages by our current indentation level. """ formatted = super(IndentingFo...
Return whether the handler is using sys.stdout. def _using_stdout(self): """ Return whether the handler is using sys.stdout. """ if WINDOWS and colorama: # Then self.stream is an AnsiToWin32 object. return self.stream.wrapped is sys.stdout return self.st...
Helper to convert config values to boolean as ConfigParser do. def _cast_boolean(value): """ Helper to convert config values to boolean as ConfigParser do. """ _BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False, '': Fals...
Return the value for option or default if defined. def getenv(option, default=undefined, cast=undefined): """ Return the value for option or default if defined. """ # We can't avoid __contains__ because value may be empty. if option in os.environ: value = os.environ[option] else: ...
Given a list of option strings this joins them in the most appropriate way and returns them in the form ``(formatted_string, any_prefix_is_slash)`` where the second item in the tuple is a flag that indicates if any of the option prefixes was a slash. def join_options(options): """Given a list of option...
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: t...
Writes re-indented text into the buffer. This rewraps and preserves paragraphs. def write_text(self, text): """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ text_width = max(self.width - self.current_indent, 11) indent = ' ' * self...
Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and ...
Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading. def section(self, name): """Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is...
Returns a better error message when invalid configuration option is provided. def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for...
Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator def _format_option_strings(self, option, mvarfmt=' <%s>', optse...
Ensure there is only one newline between usage and the first heading if there is no description. def format_usage(self, usage): """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = '\nUsage: %s\n' % self.indent_li...
Insert an OptionGroup at a given position. def insert_option_group(self, idx, *args, **kwargs): """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group
Get a list of all options, including those in option groups. def option_list_all(self): """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists). def _update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special...
Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work. def get_default_values(self): """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work...
Helper utility for reimporting previously imported modules while inside the env def safe_import(self, name): """Helper utility for reimporting previously imported modules while inside the env""" module = None if name not in self._modules: self._modules[name] = importlib.import_modul...
Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search for all packages :type working_set: :class:`pkg...
Returns the context appropriate paths for the environment. :return: A dictionary of environment specific paths to be used for installation operations :rtype: dict .. note:: The implementation of this is borrowed from a combination of pip and virtualenv and is likely to change at som...
Path to the environment python def python(self): """Path to the environment python""" py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix() if not py: return vistir.compat.Path(sys.executable).as_posix() return py
The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list def sys_path(self): """ The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list """ from .vendor.visti...
The prefix run inside the context of the environment :return: The python prefix inside the environment :rtype: :data:`sys.prefix` def sys_prefix(self): """ The prefix run inside the context of the environment :return: The python prefix inside the environment :rtype: :d...
Get the pip version in the environment. Useful for knowing which args we can use when installing. def pip_version(self): """ Get the pip version in the environment. Useful for knowing which args we can use when installing. """ from .vendor.packaging.version import pars...
Retrives the distributions installed on the library path of the environment :return: A set of distributions found on the library path :rtype: iterator def get_distributions(self): """ Retrives the distributions installed on the library path of the environment :return: A set of...
Find an egg by name in the given environment def find_egg(self, egg_dist): """Find an egg by name in the given environment""" site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() exc...
Determine whether the supplied distribution is in the environment. def dist_is_in_project(self, dist): """Determine whether the supplied distribution is in the environment.""" from .project import _normalized prefixes = [ _normalized(prefix) for prefix in self.base_paths["libdirs"]....
Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool def is_installed(self, pkgname): """Given a package name, returns whether it is installe...
Run a python command in the enviornment context. :param cmd: A command to run in the environment - runs with `python -c` :type cmd: str or list :param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir` :return: A finished command object ...
Runs the environment's inline activation script def run_activate_this(self): """Runs the environment's inline activation script""" if self.is_venv: activate_this = os.path.join(self.scripts_dir, "activate_this.py") if not os.path.isfile(activate_this): raise OSEr...
Helper context manager to activate the environment. This context manager will set the following variables for the duration of its activation: * sys.prefix * sys.path * os.environ["VIRTUAL_ENV"] * os.environ["PATH"] In addition, it will make any ...
A context manager which allows uninstallation of packages from the environment :param str pkgname: The name of a package to uninstall >>> env = Environment("/path/to/env/root") >>> with env.uninstall("pytz", auto_confirm=True, verbose=False) as uninstaller: cleaned = uninstalle...
Convert a string to a null-terminated bytes object. def stn(s, length, encoding, errors): """Convert a string to a null-terminated bytes object. """ s = s.encode(encoding, errors) return s[:length] + (length - len(s)) * NUL
Convert a null-terminated bytes object to a string. def nts(s, encoding, errors): """Convert a null-terminated bytes object to a string. """ p = s.find(b"\0") if p != -1: s = s[:p] return s.decode(encoding, errors)
Convert a number field to a python number. def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0o200): try: n = int(nts(s, "ascii", "strict") or "0", 8) except ValueError: ...
Convert a python number to a number field. def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar a...
Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in ...
Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: ...
Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() def filemode(mode): """Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() """ perm = [] for table in filemode_table: for bit, char in table: if ...
Return True if name points to a tar archive that we are able to handle, else return False. def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. """ try: t = open(name) t.close() return True except TarEr...
Initialize for writing with gzip compression. def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self...
Write string s to the stream. def write(self, s): """Write string s to the stream. """ if self.comptype == "gz": self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != "tar": s = self.cmp.compress(s) self.__write(s)
Write string s to the stream if a whole new block is ready to be written. def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.bu...
Close the _Stream object. No operation should be done on it afterwards. def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return if self.mode == "w" and self.comptype != "tar": s...
Initialize for reading a gzip compressed fileobj. def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = b"" # taken from gzip.GzipFile with some alterations if self.__read(2...
Set the stream's file pointer to pos. Negative seeking is forbidden. def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) ...
Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF. def read(self, size=None): """Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EO...
Return size bytes from the stream. def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) while c < size: buf = self.__read(self.bufsize) if not buf: ...
Return size bytes from stream. If internal buffer is empty, read another block from the stream. def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) while c < size: ...
Read data from the file. def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: ...
Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. def read(self, size=None): """Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. """ if self.closed: ...
Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line. def readline(self, size=-1): """Read one entire line from the file. If size is present and non-negative, return a string with at mos...
Seek to a position in the file. def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ if self.closed: raise ValueError("I/O operation on closed file") if whence == os.SEEK_SET: self.position = min(max(pos, 0), self.size) elif wh...
Return the TarInfo's attributes as a dictionary. def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "s...
Return a tar header as a string of 512 byte blocks. def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() if format == USTAR_FORMAT: return self.create_ustar_hea...
Return the object as a ustar header block. def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(i...
Return the object as a GNU header block sequence. def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_h...
Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, ...
Split a name longer than 100 chars into a prefix and a name part. def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix and a name part. """ prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = ...
Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. def _create_header(info, format, encoding, errors): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. ...
Return the string payload filled with zero bytes up to the next 512 byte border. def _create_payload(payload): """Return the string payload filled with zero bytes up to the next 512 byte border. """ blocks, remainder = divmod(len(payload), BLOCKSIZE) if remainder >...
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. def _create_gnu_long_header(cls, name, type, encoding, errors): """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. """ name = name.encode(encoding, errors) + NUL info = {} in...
Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. def _create_pax_generic_header(cls, pax_headers, type, encoding): """Return a POSIX.1-2008 extended or global header sequence that contains a list ...
Construct a TarInfo object from a 512 byte bytes object. def frombuf(cls, buf, encoding, errors): """Construct a TarInfo object from a 512 byte bytes object. """ if len(buf) == 0: raise EmptyHeaderError("empty header") if len(buf) != BLOCKSIZE: raise TruncatedHea...
Return the next TarInfo object from TarFile object tarfile. def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) obj....
Choose the right processing method depending on the type and call it. def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(t...
Process a builtin type or an unknown type which will be treated as a regular file. def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.of...
Process the blocks that hold a GNU longname or longlink member. def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. ...
Process a GNU sparse header plus extra headers. def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs ...
Process an extended or global header as described in POSIX.1-2008. def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A...
Process a GNU tar extended sparse header, version 0.0. def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match....
Process a GNU tar extended sparse header, version 0.1. def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2]))
Process a GNU tar extended sparse header, version 1.0. def _proc_gnusparse_10(self, next, pax_headers, tarfile): """Process a GNU tar extended sparse header, version 1.0. """ fields = None sparse = [] buf = tarfile.fileobj.read(BLOCKSIZE) fields, buf = buf.split(b"\n", 1...
Replace fields with supplemental information from a previous pax extended or global header. def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pa...
Decode a single field from a pax record. def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ try: return value.decode(encoding, "strict") except UnicodeDecodeError: return value.decode(...
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += ...
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression ...
Open uncompressed tar archive name for reading or writing. def taropen(cls, name, mode="r", fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") retu...
Open gzip compressed tar archive name for reading or writing. Appending is not allowed. def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1...
Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) ...
Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return if self.mode in "aw": ...
Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. def getmember(self, name): """Return a TarInfo object fo...
Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. def getmembers(self): """Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. """ ...
Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the ar...