INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Escape a string. Calls: func: escape and ensures that for subclasses the correct type is returned.
def escape(cls, s): """Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv
Ensure that if a link can be found for this that it is found.
def populate_link(self, finder, upgrade, require_hashes): # type: (PackageFinder, bool, bool) -> None """Ensure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. If requi...
Return whether I am pinned to an exact version.
def is_pinned(self): # type: () -> bool """Return whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. """ specifiers = self.specifier return (len(specifiers) == 1 and next(iter(specifiers)).operator ...
Return a hash - comparer that considers my option - and URL - based hashes to be known - good.
def hashes(self, trust_internet=True): # type: (bool) -> Hashes """Return a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones...
Move self. _temp_build_dir to self. _ideal_build_dir/ self. req. name
def _correct_build_location(self): # type: () -> None """Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a tempo...
Remove the source files from this requirement if they are marked for deletion
def remove_temporary_source(self): # type: () -> None """Remove the source files from this requirement, if they are marked for deletion""" if self.source_dir and os.path.exists( os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)): logger.debug('Removing...
Find an installed distribution that satisfies or conflicts with this requirement and set self. satisfied_by or self. conflicts_with appropriately.
def check_if_exists(self, use_user_site): # type: (bool) -> bool """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately. """ if self.req is None: return False ...
Load the pyproject. toml file.
def load_pyproject_toml(self): # type: () -> None """Load the pyproject.toml file. After calling this routine, all of the attributes related to PEP 517 processing for this requirement have been set. In particular, the use_pep517 attribute can be used to determine whether we shou...
Ensure that project metadata is available.
def prepare_metadata(self): # type: () -> None """Ensure that project metadata is available. Under PEP 517, call the backend hook to prepare the metadata. Under legacy processing, call setup.py egg-info. """ assert self.source_dir with indent_log(): ...
Return a pkg_resources. Distribution for this requirement
def get_dist(self): # type: () -> Distribution """Return a pkg_resources.Distribution for this requirement""" if self.metadata_directory: base_dir, distinfo = os.path.split(self.metadata_directory) metadata = pkg_resources.PathMetadata( base_dir, self.meta...
Uninstall the distribution currently satisfying this requirement.
def uninstall(self, auto_confirm=False, verbose=False, use_user_site=False): # type: (bool, bool, bool) -> Optional[UninstallPathSet] """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_...
Marshal cmd line args into a requirement set.
def populate_requirement_set(requirement_set, # type: RequirementSet args, # type: List[str] options, # type: Values finder, # type: PackageFinder session, ...
Create a package finder appropriate to this requirement command.
def _build_package_finder( self, options, # type: Values session, # type: PipSession platform=None, # type: Optional[str] python_versions=None, # type: Optional[List[str]] abi=None, # type: Optional[str] implementa...
Represent a list of integers as a sequence of ranges: (( start_0 end_0 ) ( start_1 end_1 )... ) such that the original integers are exactly those x such that start_i < = x < end_i for some i.
def intranges_from_list(list_): """Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i. Ranges are encoded as single integers (start << 32 | end), not as tuples. ...
Determine if int_ falls into one of the ranges in ranges.
def intranges_contain(int_, ranges): """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _...
Return the hash digest of a file.
def _hash_of_file(path, algorithm): """Return the hash digest of a file.""" with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
Return information about the OS distribution that is compatible with Python s: func: platform. linux_distribution supporting a subset of its parameters.
def linux_distribution(self, full_distribution_name=True): """ Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`. ""...
Return the distro ID of the OS distribution as a string.
def id(self): """Return the distro ID of the OS distribution, as a string. For details, see :func:`distro.id`. """ def normalize(distro_id, table): distro_id = distro_id.lower().replace(' ', '_') return table.get(distro_id, distro_id) distro_id = self.os...
Return the name of the OS distribution as a string.
def name(self, pretty=False): """ Return the name of the OS distribution, as a string. For details, see :func:`distro.name`. """ name = self.os_release_attr('name') \ or self.lsb_release_attr('distributor_id') \ or self.distro_release_attr('name') \ ...
Return the version of the OS distribution as a string.
def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distr...
Return the version of the OS distribution as a tuple of version numbers.
def version_parts(self, best=False): """ Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. """ version_str = self.version(best=best) if version_str: version_regex = re.compile(r'(\...
Return certain machine - readable information about the OS distribution.
def info(self, pretty=False, best=False): """ Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`. """ return dict( id=self.id(), version=self.version(pretty, best), version_parts...
Get the information items from the specified os - release file.
def _os_release_info(self): """ Get the information items from the specified os-release file. Returns: A dictionary containing all information items. """ if os.path.isfile(self.os_release_file): with open(self.os_release_file) as release_file: ...
Get the information items from the lsb_release command output.
def _lsb_release_info(self): """ Get the information items from the lsb_release command output. Returns: A dictionary containing all information items. """ if not self.include_lsb: return {} with open(os.devnull, 'w') as devnull: try: ...
Parse the output of the lsb_release command.
def _parse_lsb_release_content(lines): """ Parse the output of the lsb_release command. Parameters: * lines: Iterable through the lines of the lsb_release output. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: ...
Get the information items from the specified distro release file.
def _distro_release_info(self): """ Get the information items from the specified distro release file. Returns: A dictionary containing all information items. """ if self.distro_release_file: # If it was specified, we use it and parse what we can, even if ...
Parse a distro release file.
def _parse_distro_release_file(self, filepath): """ Parse a distro release file. Parameters: * filepath: Path name of the distro release file. Returns: A dictionary containing all information items. """ try: with open(filepath) as fp: ...
Parse a line from a distro release file.
def _parse_distro_release_content(line): """ Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information ite...
Calculate the dependency tree for the package root_key and return a collection of all its dependencies. Uses a DFS traversal algorithm.
def dependency_tree(installed_keys, root_key): """ Calculate the dependency tree for the package `root_key` and return a collection of all its dependencies. Uses a DFS traversal algorithm. `installed_keys` should be a {key: requirement} mapping, e.g. {'django': from_line('django==1.8')} `r...
Returns a collection of package names to ignore when performing pip - sync based on the currently installed environment. For example when pip - tools is installed in the local environment it should be ignored including all of its dependencies ( e. g. click ). When pip - tools is not installed locally click should also ...
def get_dists_to_ignore(installed): """ Returns a collection of package names to ignore when performing pip-sync, based on the currently installed environment. For example, when pip-tools is installed in the local environment, it should be ignored, including all of its dependencies (e.g. click). W...
Calculate which packages should be installed or uninstalled given a set of compiled requirements and a list of currently installed modules.
def diff(compiled_requirements, installed_dists): """ Calculate which packages should be installed or uninstalled, given a set of compiled requirements and a list of currently installed modules. """ requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements} satisfied =...
Install and uninstalls the given sets of modules.
def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None): """ Install and uninstalls the given sets of modules. """ if not to_uninstall and not to_install: click.echo("Everything up-to-date") pip_flags = [] if not verbose: pip_flags += ['-q'] if ...
Return a new spontaneous environment. A spontaneous environment is an unnamed and unaccessible ( in theory ) environment that is used for templates generated from a string and not from the file system.
def get_spontaneous_environment(*args): """Return a new spontaneous environment. A spontaneous environment is an unnamed and unaccessible (in theory) environment that is used for templates generated from a string and not from the file system. """ try: env = _spontaneous_environments.get(arg...
Perform a sanity check on the environment.
def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_sta...
Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensio...
def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_b...
Iterates over the extensions by priority.
def iter_extensions(self): """Iterates over the extensions by priority.""" return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
Get an item or attribute of an object but prefer the attribute. Unlike: meth: getitem the attribute * must * be a bytestring.
def getattr(self, obj, attribute): """Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring. """ try: return getattr(obj, attribute) except AttributeError: pass try: ...
Invokes a filter on a value the same way the compiler does it.
def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None): """Invokes a filter on a value the same way the compiler does it. Note that on Python 3 this might return a coroutine in case the filter is running from an environment in async mode and ...
Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source - or bytecode. This is useful for debugging or to extract information from templates.
def parse(self, source, name=None, filename=None): """Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates....
Internal parsing function used by parse and compile.
def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, encode_filename(filename)).parse()
Lex the given sourcecode and return a generator that yields tokens as tuples in the form ( lineno token_type value ). This can be useful for: ref: extension development <writing - extensions > and debugging templates.
def lex(self, source, name=None, filename=None): """Lex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development <writing-extensions>` and debugging templates. This do...
Called by the parser to do the preprocessing and filtering for all the extensions. Returns a: class: ~jinja2. lexer. TokenStream.
def _tokenize(self, source, name, filename=None, state=None): """Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. """ source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(sou...
Compile a node or template source code. The name parameter is the load name of the template after it was joined using: meth: join_path if necessary not the filename on the file system. the filename parameter is the estimated filename of the template on the file system. If the template came from a database or memory thi...
def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. ...
A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.
def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the sa...
Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a: class: Template. If the parent parameter is not None: meth: join_path is called to get the real template name before loading.
def get_template(self, name, parent=None, globals=None): """Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a :class:`Template`. If the `parent` parameter is not `None`, :meth:`join_path` is called to get the real templ...
Works like: meth: get_template but tries a number of templates before it fails. If it cannot find any of the templates it will raise a: exc: TemplatesNotFound exception.
def select_template(self, names, parent=None, globals=None): """Works like :meth:`get_template` but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a :exc:`TemplatesNotFound` exception. .. versionadded:: 2.3 .. versionchanged:...
Does a typecheck and dispatches to: meth: select_template if an iterable of template names is given otherwise to: meth: get_template.
def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3 ""...
Load a template from a string. This parses the source given and returns a: class: Template object.
def from_string(self, source, globals=None, template_class=None): """Load a template from a string. This parses the source given and returns a :class:`Template` object. """ globals = self.make_globals(globals) cls = template_class or self.template_class return cls.from_c...
Return a dict for the globals.
def make_globals(self, d): """Return a dict for the globals.""" if not d: return self.globals return dict(self.globals, **d)
Creates a template object from a module. This is used by the module loader to create a template object.
def from_module_dict(cls, environment, module_dict, globals): """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals)
Create a new: class: Context for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to True the data is passed as it to the context without adding the globals.
def new_context(self, vars=None, shared=False, locals=None): """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context witho...
This method works like the: attr: module attribute when called without arguments but it will evaluate the template on every call rather than caching it. It s also possible to provide a dict which is then used as context. The arguments are the same as for the: meth: new_context method.
def make_module(self, vars=None, shared=False, locals=None): """This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. ...
Return the source line number of a line number in the generated bytecode as they are not in sync.
def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line ...
The debug info mapping.
def debug_info(self): """The debug info mapping.""" return [tuple(imap(int, x.split('='))) for x in self._debug_info.split('&')]
This is a stand - in function for urllib3. util. parse_url
def _get_parsed_url(url): # type: (S) -> Url """ This is a stand-in function for `urllib3.util.parse_url` The orignal function doesn't handle special characters very well, this simply splits out the authentication section, creates the parsed url, then puts the authentication section back in, by...
Given a url remove the password and insert 4 dashes
def remove_password_from_url(url): # type: (S) -> S """ Given a url, remove the password and insert 4 dashes :param url: The url to replace the authentication in :type url: S :return: The new URL without authentication :rtype: S """ parsed = _get_parsed_url(url) if parsed.auth:...
Ensures that the environment is good for unicode on Python 3.
def _verify_python3_env(): """Ensures that the environment is good for unicode on Python 3.""" if PY2: return try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc != 'ascii': return ext...
On Windows the files in. svn are read - only so when rmtree () tries to remove them an exception is thrown. We catch that here remove the read - only attribute and hopefully continue without problems.
def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" # if file type currently read only if os.stat...
Gives the display value for a given path making it relative to cwd if possible.
def display_path(path): # type: (Union[str, Text]) -> str """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path...
Is path is a directory containing setup. py or pyproject. toml?
def is_installable_dir(path): # type: (str) -> bool """Is path is a directory containing setup.py or pyproject.toml? """ if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True pyproject_toml = os.path.join(p...
Returns true if the page appears to be the index page of an svn repository
def is_svn_page(html): # type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]] """ Returns true if the page appears to be the index page of an svn repository """ return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I...
Yield pieces of data from a file - like object until EOF.
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): """Yield pieces of data from a file-like object until EOF.""" while True: chunk = file.read(size) if not chunk: break yield chunk
Convert a path to its canonical case - normalized absolute version.
def normalize_path(path, resolve_symlinks=True): # type: (str, bool) -> str """ Convert a path to its canonical, case-normalized, absolute version. """ path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) return os...
Like os. path. splitext but take off. tar too
def splitext(path): # type: (str) -> Tuple[str, str] """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext
Like os. renames () but handles renaming across devices.
def renames(old, new): # type: (str, str) -> None """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, ...
Return True if path is within sys. prefix if we re running in a virtualenv.
def is_local(path): # type: (str) -> bool """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." """ if not running_under_virtualenv(): return True return normalize_path(path).startswith(normal...
Return True if given Distribution is an editable install.
def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return ...
Return a list of installed Distribution objects.
def get_installed_distributions(local_only=True, skip=stdlib_pkgs, include_editables=True, editables_only=False, user_only=False): # type: (bool, Container[str], bool, bool, bool) -> List[...
Return the path for the. egg - link file if it exists otherwise None.
def egg_link_path(dist): # type: (Distribution) -> Optional[str] """ Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site...
Unzip the file ( with path filename ) to the destination location. All files are written based on system defaults and umask ( i. e. permissions are not preserved ) except that regular file members with any execute permissions ( user group or world ) have chmod + x applied after being written. Note that for windows any ...
def unzip_file(filename, location, flatten=True): # type: (str, str, bool) -> None """ Unzip the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execut...
Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable in addition to 0. Defaults to None which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess. Popen ().
def call_subprocess( cmd, # type: List[str] show_stdout=True, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mappin...
Return the contents of * filename *.
def read_text_file(filename): # type: (str) -> str """Return the contents of *filename*. Try to decode the file contents with utf-8, the preferred system encoding (e.g., cp1252 on some Windows machines), and latin1, in that order. Decoding a byte string with latin1 will never raise an error. In the...
Return a context manager used by captured_stdout/ stdin/ stderr that temporarily replaces the sys stream * stream_name * with a StringIO.
def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. """ orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name...
Get the installed version of dist_name avoiding pkg_resources cache
def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having t...
Return the URL for a VCS requirement.
def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): """ Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. """ egg_project_name = pkg_resources.to_filename(pr...
Parse out and remove the auth information from a netloc.
def split_auth_from_netloc(netloc): """ Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). """ if '@' not in netloc: return netloc, (None, None) # Split from the right because that's how urllib.parse.urlsplit() # behaves if more than o...
Replace the password in a netloc with **** if it exists.
def redact_netloc(netloc): # type: (str) -> str """ Replace the password in a netloc with "****", if it exists. For example, "user:pass@example.com" returns "user:****@example.com". """ netloc, (user, password) = split_auth_from_netloc(netloc) if user is None: return netloc pass...
Protection of pip. exe from modification on Windows
def protect_pip_from_modification_on_windows(modifying_pip): """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_info[0]), "pip{}.{}....
Check if the python version in use match the requires_python specifier.
def check_requires_python(requires_python): # type: (Optional[str]) -> bool """ Check if the python version in use match the `requires_python` specifier. Returns `True` if the version of python in use matches the requirement. Returns `False` if the version of python in use does not matches the ...
Initialize the enhanced click completion
def init(complete_options=False, match_incomplete=None): """Initialize the enhanced click completion Parameters ---------- complete_options : bool always complete the options, even when the user hasn't typed a first dash (Default value = False) match_incomplete : func a function wit...
The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use.
def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = OrderedDict() for hit in hits: name = hit['name'] summary = ...
Add install_req as a requirement to install.
def add_requirement( self, install_req, # type: InstallRequirement parent_req_name=None, # type: Optional[str] extras_requested=None # type: Optional[Iterable[str]] ): # type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501 """A...
Resolve what operations need to be done
def resolve(self, requirement_set): # type: (RequirementSet) -> None """Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operat...
Set a requirement to be installed.
def _set_req_to_reinstall(self, req): # type: (InstallRequirement) -> None """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if not self.use_user_site or dist_in_usersite(req...
Check if req_to_install should be skipped.
def _check_skip_installed(self, req_to_install): # type: (InstallRequirement) -> Optional[str] """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. ...
Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same.
def _get_abstract_dist_for(self, req): # type: (InstallRequirement) -> DistAbstraction """Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same. """ assert self.require_hashes is not None, ( "require_hashes should h...
Prepare a single requirements file.
def _resolve_one( self, requirement_set, # type: RequirementSet req_to_install, # type: InstallRequirement ignore_requires_python=False # type: bool ): # type: (...) -> List[InstallRequirement] """Prepare a single requirements file. :return: A list of addi...
Create the installation order.
def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no oth...
Escape & < > etc. in a string of data.
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split()) for from_,to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) return ...
Returns the line of text containing loc within a string counting newlines as line separators.
def line( loc, strg ): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:]
Decorator for debugging parse actions.
def traceParseAction(f): """Decorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. When the parse action completes, the decorator will print ``"<<"`` followed by...
Helper to define a delimited list of expressions - the delimiter defaults to. By default the list elements and delimiters can have intervening whitespace and comments but this can be overridden by passing combine = True in the constructor. If combine is set to True the matching tokens are returned as a single token str...
def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing ``combine=True`` in the constructor....
Helper to return the original untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself or to revert separate tokens with intervening whitespace back to the original matching input text. By default returns astring containing the original parsed text.
def originalTextFor(expr, asString=True): """Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. ...
Helper to decorate a returned token with its starting and ending locations in the input string.
def locatedExpr(expr): """Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the a...
r Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp [] string range definitions::
def srange(s): r"""Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" ...
Helper method for defining parse actions that require matching at a specific column in the input text.
def matchOnlyAtCol(n): """Helper method for defining parse actions that require matching at a specific column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol
Helper to define a parse action by mapping a function to all elements of a ParseResults list. If any additional args are passed they are forwarded to the given function as additional arguments after the token as in hex_integer = Word ( hexnums ). setParseAction ( tokenMap ( int 16 )) which will convert the parsed data ...
def tokenMap(func, *args): """Helper to define a parse action by mapping a function to all elements of a ParseResults list. If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in ``hex_integer = Word(hexnums).setParseAction(tokenMap...
Helper to create a validating parse action to be used with start tags created with: class: makeXMLTags or: class: makeHTMLTags. Use withAttribute to qualify a starting tag with a required attribute value to avoid false matches on common tags such as <TD > or <DIV >.
def withAttribute(*args,**attrDict): """Helper to create a validating parse action to be used with start tags created with :class:`makeXMLTags` or :class:`makeHTMLTags`. Use ``withAttribute`` to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as ``<...
Helper method for defining nested lists enclosed in opening and closing delimiters ( ( and ) are the default ).
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): """Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default= ``"("``); can also be a...
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
def _from_exception(cls, pe): """ internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses """ return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)