text
stringlengths
81
112k
Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned. def iter_child_nodes(self, exclude=None, only=None): """Iterates over all direct child nodes of t...
Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items. def find_all(self, node_type): """Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items. """ for child in self...
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context. def set_ctx(self, ctx): """Reset the ...
Set the line numbers of the node and children. def set_lineno(self, lineno, override=False): """Set the line numbers of the node and children.""" todo = deque([self]) while todo: node = todo.popleft() if 'lineno' in node.attributes: if node.lineno is None...
Set the environment for all nodes. def set_environment(self, environment): """Set the environment for all nodes.""" todo = deque([self]) while todo: node = todo.popleft() node.environment = environment todo.extend(node.iter_child_nodes()) return self
Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception. def from_untrusted(cls, value, lineno=None, environment=None): """Return a const object if the value is representable as constant value in the ...
Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subpr...
Build an sdist from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str sdist_dir: Target directory to place sdist in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subpr...
Install dependencies into this env by calling pip in a subprocess def pip_install(self, reqs): """Install dependencies into this env by calling pip in a subprocess""" if not reqs: return log.info('Calling pip to install %s', reqs) check_call([ sys.executable, '-m...
Move all the children of the current node to newParent. This is needed so that trees that don't store text as nodes move the text in the correct way :arg newParent: the node to move all this node's children to def reparentChildren(self, newParent): """Move all the children of the curre...
Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false def elementInActiveFormattingElements(self, name): """Check if an element exists between the end of the active formatting elements and the last mark...
Create an element but don't insert it anywhere def createElement(self, token): """Create an element but don't insert it anywhere""" name = token["name"] namespace = token.get("namespace", self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = to...
Switch the function used to insert an element from the normal one to the misnested table one and back again def _setInsertFromTable(self, value): """Switch the function used to insert an element from the normal one to the misnested table one and back again""" self._insertFromTable = val...
Create an element and insert it into the tree def insertElementTable(self, token): """Create an element and insert it into the tree""" element = self.createElement(token) if self.openElements[-1].name not in tableInsertModeElements: return self.insertElementNormal(token) els...
Insert text data. def insertText(self, data, parent=None): """Insert text data.""" if parent is None: parent = self.openElements[-1] if (not self.insertFromTable or (self.insertFromTable and self.openElements[-1].name ...
Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node def getTableMisnestedNodePosition(self): """Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node""" # The foster parent elem...
Return the final fragment def getFragment(self): """Return the final fragment""" # assert self.innerHTML fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process. def evaluate(self, environment=None...
Monkey patch pip.Wheel to allow all wheels The usual checks against platforms and Python versions are ignored to allow fetching all available entries in PyPI. This also saves the candidate cache and set a new one, or else the results from the previous non-patched calls will interfere. def _allow_all_w...
Create a temporary directory and store its path in self.path def create(self): """Create a temporary directory and store its path in self.path """ if self.path is not None: logger.debug( "Skipped creation of temporary directory: {}".format(self.path) ) ...
Remove the temporary directory created and reset state def cleanup(self): """Remove the temporary directory created and reset state """ if getattr(self._finalizer, "detach", None) and self._finalizer.detach(): if os.path.exists(self.path): try: rm...
Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). def _generate_names(cls, name): """Generates a seri...
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``by...
Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent. >>> Markup('Main &raquo; <em>About</em>').unescape() 'Main » <em>About</em>' def unescape(self): """Convert escaped markup back into a text string. This replaces HTML...
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: ...
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 require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes ...
Return whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. 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. """ ...
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 from flags. They satisfy --require-hashes (whether it was implicitly or ...
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 temporary directory and store the _ideal_build_dir. This is only call...
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.pat...
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 t...
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 should follow the PEP 517 or legacy (setup.py) code path. def lo...
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. def prepare_metadata(self): # type: () -> None """Ensure that project metadata is available. Under PEP 517, call the backen...
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_r...
Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virt...
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: PackageFi...
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]] ...
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. def intranges_from_list(list_): """R...
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) # w...
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. For details, see :func:`distro.linux_distribution`. def linux_distribution(self, full_distribution_name=True): """ Return in...
Return the distro ID of the OS distribution, as a string. For details, see :func:`distro.id`. 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.l...
Return the name of the OS distribution, as a string. For details, see :func:`distro.name`. 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') \ ...
Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ ...
Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. def version_parts(self, best=False): """ Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.ve...
Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`. def info(self, pretty=False, best=False): """ Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`. ...
Get the information items from the specified os-release file. Returns: A dictionary containing all information items. def _os_release_info(self): """ Get the information items from the specified os-release file. Returns: A dictionary containing all information ...
Get the information items from the lsb_release command output. Returns: A dictionary containing all information items. def _lsb_release_info(self): """ Get the information items from the lsb_release command output. Returns: A dictionary containing all informati...
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: A dictionary containing all information items. def...
Get the information items from the specified distro release file. Returns: A dictionary containing all information items. def _distro_release_info(self): """ Get the information items from the specified distro release file. Returns: A dictionary containing all ...
Parse a distro release file. Parameters: * filepath: Path name of the distro release file. Returns: A dictionary containing all information items. def _parse_distro_release_file(self, filepath): """ Parse a distro release file. Parameters: * file...
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 items. def _parse_distro_release_content(line): """ ...
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')} `root_key` should be the key to return the dependency tree fo...
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, clic...
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...
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 = [] i...
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 environmen...
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_...
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 linke...
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. ...
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 the filter supports async execution. It's your responsibility to await this if needed. .. vers...
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. If you are :ref:`developing Jinja2 extensions <writi...
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. This does not perform preprocessing. If you want the preprocessing...
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...
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 tem...
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 same rules as Jinja in template "configuration files" or similar si...
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. The `globals` parameter can be use...
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:: 2.4 If `names` contains a :class:`Template` object it is re...
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 def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a ty...
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. """ glob...
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. .. versionadded:: 2.4 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 templa...
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. `locals` can be a dict of local variable...
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...
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 ...
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` 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, bypassing validation. :return: The new, parsed URL object ...
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 def remove_password_from_url(url): # type: (S) -> S """ Given a url, remove the password and insert 4 dashes :pa...
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_...
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 rm...
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]...
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(set...
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) ...
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.realpa...
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): ...
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." 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 p...
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...
Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, d...
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_packages 3) in a yes-global virtualenv try to find in site_packages, ...
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 tha...
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] ...
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 worst case, the returned string will contain some garbage...
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. def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporar...
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_n...
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. def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): """ Return the URL for a VCS requirement. Args: rep...
Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). 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, N...