text
stringlengths
81
112k
Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. def ensure_object(self, object_type): """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv
Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. def lookup_default(self, name): """Looks up the default for a parameter name. This by default looks into the :attr:`default_map` if available. """ if self.default_map is not None: rv = self.default_map.get(name) if callable(rv): rv = rv() return rv
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) args = args[2:] with augment_usage_errors(self): with ctx: return callback(*args, **kwargs)
Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invoke another command which might or # might not have a callback. if not isinstance(cmd, Command): raise TypeError('Callback is not a command.') for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return self.invoke(cmd, **kwargs)
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point or reject further execution to avoid a # broken script. if not PY2: _verify_python3_env() else: _check_for_unicode_literals() if args is None: args = get_os_args() else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv # it's not safe to `ctx.exit(rv)` here! # note that `rv` may actually contain data like "1" which # has obvious effects # more subtle case: `rv=[None, None]` can come out of # chained commands which all returned `None` -- so it's not # even always obvious that `rv` indicates success/failure # by its truthiness/falsiness ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except IOError as e: if e.errno == errno.EPIPE: sys.stdout = PacifyFlushWrapper(sys.stdout) sys.stderr = PacifyFlushWrapper(sys.stderr) sys.exit(1) else: raise except Exit as e: if standalone_mode: sys.exit(e.exit_code) else: # in non-standalone mode, return the exit code # note that this is only reached if `self.invoke` above raises # an Exit explicitly -- thus bypassing the check there which # would return its result # the results of non-standalone execution may therefore be # somewhat ambiguous: if there are codepaths which lead to # `ctx.exit(1)` and to `return 1`, the caller won't be able to # tell the difference between the two return e.exit_code except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1)
Writes the usage line into the formatter. def format_usage(self, ctx, formatter): """Writes the usage line into the formatter.""" pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces))
Returns all the pieces that go into the usage line and returns it as a list of strings. def collect_usage_pieces(self, ctx): """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv
Returns the names for the help option. def get_help_option_names(self, ctx): """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return all_names
Returns the help option object. def get_help_option(self, ctx): """Returns the help option object.""" help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return def show_help(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Option(help_options, is_flag=True, is_eager=True, expose_value=False, callback=show_help, help='Show this message and exit.')
Creates the underlying option parser for this command. def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods: def get_help(self, ctx): """Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods: """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip('\n')
Gets short help for the command or makes it by shortening the long help string. def get_short_help_str(self, limit=45): """Gets short help for the command or makes it by shortening the long help string.""" return self.short_help or self.help and make_default_short_help(self.help, limit) or ''
Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter)
Writes the help text to the formatter if it exists. def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): help_text = self.help if self.deprecated: help_text += DEPRECATED_HELP_NOTICE formatter.write_text(help_text) elif self.deprecated: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(DEPRECATED_HELP_NOTICE)
Writes all the options into the formatter if they exist. def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section('Options'): formatter.write_dl(opts)
Writes the epilog into the formatter if it exists. def format_epilog(self, ctx, formatter): """Writes the epilog into the formatter if it exists.""" if self.epilog: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.epilog)
Given a context, this invokes the attached callback (if it exists) in the right way. def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ _maybe_show_deprecated_notice(self) if self.callback is not None: return ctx.invoke(self.callback, **ctx.params)
Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.resultcallback() def process_result(result, input): return result + input .. versionadded:: 3.0 :param replace: if set to `True` an already existing result callback will be removed. def resultcallback(self, replace=False): """Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.resultcallback() def process_result(result, input): return result + input .. versionadded:: 3.0 :param replace: if set to `True` an already existing result callback will be removed. """ def decorator(f): old_callback = self.result_callback if old_callback is None or replace: self.result_callback = f return f def function(__value, *args, **kwargs): return f(old_callback(__value, *args, **kwargs), *args, **kwargs) self.result_callback = rv = update_wrapper(function, f) return rv return decorator
Extra format methods for multi methods that adds all the commands after the options. def format_commands(self, ctx, formatter): """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) # allow for 3 times the default spacing if len(commands): limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) rows = [] for subcommand, cmd in commands: help = cmd.get_short_help_str(limit) rows.append((subcommand, help)) if rows: with formatter.section('Commands'): formatter.write_dl(rows)
Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') _check_multicommand(self, name, cmd, register=True) self.commands[name] = cmd
A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` but immediately registers the created command with this instance by calling into :meth:`add_command`. def command(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = command(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator
A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` but immediately registers the created command with this instance by calling into :meth:`add_command`. def group(self, *args, **kwargs): """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` but immediately registers the created command with this instance by calling into :meth:`add_command`. """ def decorator(f): cmd = group(*args, **kwargs)(f) self.add_command(cmd) return cmd return decorator
Given a context variable this calculates the default value. def get_default(self, ctx): """Given a context variable this calculates the default value.""" # Otherwise go with the regular default. if callable(self.default): rv = self.default() else: rv = self.default return self.type_cast_value(ctx, rv)
Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ if self.type.is_composite: if self.nargs <= 1: raise TypeError('Attempted to invoke composite type ' 'but nargs has been set to %s. This is ' 'not supported; nargs needs to be set to ' 'a fixed value > 1.' % self.nargs) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) return self.type(value or (), self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) return tuple(_convert(x, level - 1) for x in value or ()) return _convert(value, (self.nargs != 1) + bool(self.multiple))
Get a stringified version of the param for use in error messages to indicate which param caused the error. def get_error_hint(self, ctx): """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return ' / '.join('"%s"' % x for x in hint_list)
This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. def prompt_for_value(self, ctx): """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ # Calculate the default before prompting anything to be stable. default = self.get_default(ctx) # If this is a prompt for a flag we need to handle this # differently. if self.is_bool_flag: return confirm(self.prompt, default) return prompt(self.prompt, default=default, type=self.type, hide_input=self.hide_input, show_choices=self.show_choices, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x))
Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A list of matching candidates. :rtype: list[:class:`~pip._internal.index.InstallationCandidate`] def find_all_matches(finder, ireq, pre=False): # type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate] """Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A list of matching candidates. :rtype: list[:class:`~pip._internal.index.InstallationCandidate`] """ candidates = clean_requires_python(finder.find_all_candidates(ireq.name)) versions = {candidate.version for candidate in candidates} allowed_versions = _get_filtered_versions(ireq, versions, pre) if not pre and not allowed_versions: allowed_versions = _get_filtered_versions(ireq, versions, True) candidates = {c for c in candidates if c.version in allowed_versions} return candidates
Get all abstract dependencies for a given list of requirements. Given a set of requirements, convert each requirement to an Abstract Dependency. :param reqs: A list of Requirements :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`] :param sources: Pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional :return: A list of Abstract Dependencies :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`] def get_abstract_dependencies(reqs, sources=None, parent=None): """Get all abstract dependencies for a given list of requirements. Given a set of requirements, convert each requirement to an Abstract Dependency. :param reqs: A list of Requirements :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`] :param sources: Pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional :return: A list of Abstract Dependencies :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`] """ deps = [] from .requirements import Requirement for req in reqs: if isinstance(req, pip_shims.shims.InstallRequirement): requirement = Requirement.from_line( "{0}{1}".format(req.name, req.specifier) ) if req.link: requirement.req.link = req.link requirement.markers = req.markers requirement.req.markers = req.markers requirement.extras = req.extras requirement.req.extras = req.extras elif isinstance(req, Requirement): requirement = copy.deepcopy(req) else: requirement = Requirement.from_line(req) dep = AbstractDependency.from_requirement(requirement, parent=parent) deps.append(dep) return deps
Get all dependencies for a given install requirement. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :type parent: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) def get_dependencies(ireq, sources=None, parent=None): # type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...] """Get all dependencies for a given install requirement. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :type parent: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) """ if not isinstance(ireq, pip_shims.shims.InstallRequirement): name = getattr( ireq, "project_name", getattr(ireq, "project", ireq.name), ) version = getattr(ireq, "version", None) if not version: ireq = pip_shims.shims.InstallRequirement.from_line("{0}".format(name)) else: ireq = pip_shims.shims.InstallRequirement.from_line("{0}=={1}".format(name, version)) pip_options = get_pip_options(sources=sources) getters = [ get_dependencies_from_cache, get_dependencies_from_wheel_cache, get_dependencies_from_json, functools.partial(get_dependencies_from_index, pip_options=pip_options) ] for getter in getters: deps = getter(ireq) if deps is not None: return deps raise RuntimeError('failed to get dependencies for {}'.format(ireq))
Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None def get_dependencies_from_wheel_cache(ireq): """Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return matches = WHEEL_CACHE.get(ireq.link, name_from_req(ireq.req)) if matches: matches = set(matches) if not DEPENDENCY_CACHE.get(ireq): DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches] return matches return
Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None def get_dependencies_from_json(ireq): """Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return session = requests.session() atexit.register(session.close) version = str(ireq.req.specifier).lstrip("=") def gen(ireq): info = None try: info = session.get( "https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version) ).json()["info"] finally: session.close() requires_dist = info.get("requires_dist", info.get("requires")) if not requires_dist: # The API can return None for this. return for requires in requires_dist: i = pip_shims.shims.InstallRequirement.from_line(requires) # See above, we don't handle requirements with extras. if not _marker_contains_extra(i): yield format_requirement(i) if ireq not in DEPENDENCY_CACHE: try: reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq)) except JSONDecodeError: return req_iter = iter(reqs) else: req_iter = gen(ireq) return set(req_iter)
Retrieves dependencies for the given install requirement from the dependency cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None def get_dependencies_from_cache(ireq): """Retrieves dependencies for the given install requirement from the dependency cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return if ireq not in DEPENDENCY_CACHE: return cached = set(DEPENDENCY_CACHE[ireq]) # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: broken = False for line in cached: dep_ireq = pip_shims.shims.InstallRequirement.from_line(line) name = canonicalize_name(dep_ireq.name) if _marker_contains_extra(dep_ireq): broken = True # The "extra =" marker breaks everything. elif name == canonicalize_name(ireq.name): broken = True # A package cannot depend on itself. if broken: break except Exception: broken = True if broken: del DEPENDENCY_CACHE[ireq] return return cached
Retrieves dependencies for the given install requirement from the pip resolver. :param dep: A single InstallRequirement :type dep: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None): """Retrieves dependencies for the given install requirement from the pip resolver. :param dep: A single InstallRequirement :type dep: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ finder = get_finder(sources=sources, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE dep.is_direct = True reqset = pip_shims.shims.RequirementSet() reqset.add_requirement(dep) requirements = None setup_requires = {} with temp_environ(), start_resolver(finder=finder, wheel_cache=wheel_cache) as resolver: os.environ['PIP_EXISTS_ACTION'] = 'i' dist = None if dep.editable and not dep.prepared and not dep.req: with cd(dep.setup_py_dir): from setuptools.dist import distutils try: dist = distutils.core.run_setup(dep.setup_py) except (ImportError, TypeError, AttributeError): dist = None else: setup_requires[dist.get_name()] = dist.setup_requires if not dist: try: dist = dep.get_dist() except (TypeError, ValueError, AttributeError): pass else: setup_requires[dist.get_name()] = dist.setup_requires resolver.require_hashes = False try: results = resolver._resolve_one(reqset, dep) except Exception: # FIXME: Needs to bubble the exception somehow to the user. results = [] finally: try: wheel_cache.cleanup() except AttributeError: pass resolver_requires_python = getattr(resolver, "requires_python", None) requires_python = getattr(reqset, "requires_python", resolver_requires_python) if requires_python: add_marker = fix_requires_python_marker(requires_python) reqset.remove(dep) if dep.req.marker: dep.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: dep.req.marker = add_marker reqset.add(dep) requirements = set() for r in results: if requires_python: if r.req.marker: r.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: r.req.marker = add_marker requirements.add(format_requirement(r)) for section in setup_requires: python_version = section not_python = not is_python(section) # This is for cleaning up :extras: formatted markers # by adding them to the results of the resolver # since any such extra would have been returned as a result anyway for value in setup_requires[section]: # This is a marker. if is_python(section): python_version = value[1:-1] else: not_python = True if ':' not in value and not_python: try: requirement_str = "{0}{1}".format(value, python_version).replace(":", ";") requirements.add(format_requirement(make_install_requirement(requirement_str).ireq)) # Anything could go wrong here -- can't be too careful. except Exception: pass if not dep.editable and is_pinned_requirement(dep) and requirements is not None: DEPENDENCY_CACHE[dep] = list(requirements) return requirements
Build a pip command from a list of sources :param args: positional arguments passed through to the pip parser :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pre-built pip command instance :type pip_command: :class:`~pip._internal.cli.base_command.Command` :return: An instance of pip_options using the supplied arguments plus sane defaults :rtype: :class:`~pip._internal.cli.cmdoptions` def get_pip_options(args=[], sources=None, pip_command=None): """Build a pip command from a list of sources :param args: positional arguments passed through to the pip parser :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pre-built pip command instance :type pip_command: :class:`~pip._internal.cli.base_command.Command` :return: An instance of pip_options using the supplied arguments plus sane defaults :rtype: :class:`~pip._internal.cli.cmdoptions` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] _ensure_dir(CACHE_DIR) pip_args = args pip_args = prepare_pip_source_args(sources, pip_args) pip_options, _ = pip_command.parser.parse_args(pip_args) pip_options.cache_dir = CACHE_DIR return pip_options
Get a package finder for looking up candidates to install :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pip command instance, defaults to None :type pip_command: :class:`~pip._internal.cli.base_command.Command` :param pip_options: A pip options, defaults to None :type pip_options: :class:`~pip._internal.cli.cmdoptions` :return: A package finder :rtype: :class:`~pip._internal.index.PackageFinder` def get_finder(sources=None, pip_command=None, pip_options=None): # type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder """Get a package finder for looking up candidates to install :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pip command instance, defaults to None :type pip_command: :class:`~pip._internal.cli.base_command.Command` :param pip_options: A pip options, defaults to None :type pip_options: :class:`~pip._internal.cli.cmdoptions` :return: A package finder :rtype: :class:`~pip._internal.index.PackageFinder` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] if not pip_options: pip_options = get_pip_options(sources=sources, pip_command=pip_command) session = pip_command._build_session(pip_options) atexit.register(session.close) finder = pip_shims.shims.PackageFinder( find_links=[], index_urls=[s.get("url") for s in sources], trusted_hosts=[], allow_all_prereleases=pip_options.pre, session=session, ) return finder
Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`) def start_resolver(finder=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`) """ pip_command = get_pip_command() pip_options = get_pip_options(pip_command=pip_command) if not finder: finder = get_finder(pip_command=pip_command, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE _ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels"))) download_dir = PKGS_DOWNLOAD_DIR _ensure_dir(download_dir) _build_dir = create_tracked_tempdir(fs_str("build")) _source_dir = create_tracked_tempdir(fs_str("source")) preparer = partialclass( pip_shims.shims.RequirementPreparer, build_dir=_build_dir, src_dir=_source_dir, download_dir=download_dir, wheel_download_dir=WHEEL_DOWNLOAD_DIR, progress_bar="off", build_isolation=False, ) resolver = partialclass( pip_shims.shims.Resolver, finder=finder, session=finder.session, upgrade_strategy="to-satisfy-only", force_reinstall=True, ignore_dependencies=False, ignore_requires_python=True, ignore_installed=True, isolated=False, wheel_cache=wheel_cache, use_user_site=False, ) try: if packaging.version.parse(pip_shims.shims.pip_version) >= packaging.version.parse('18'): with pip_shims.shims.RequirementTracker() as req_tracker: preparer = preparer(req_tracker=req_tracker) yield resolver(preparer=preparer) else: preparer = preparer() yield resolver(preparer=preparer) finally: finder.session.close()
Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so: ("ipython", "2.1.0[nbconvert,notebook]") def as_cache_key(self, ireq): """ Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so: ("ipython", "2.1.0[nbconvert,notebook]") """ name, version, extras = as_tuple(ireq) if not extras: extras_string = "" else: extras_string = "[{}]".format(",".join(extras)) return name, "{}{}".format(version, extras_string)
Reads the cached contents into memory. def read_cache(self): """Reads the cached contents into memory.""" if os.path.exists(self._cache_file): self._cache = read_cache_file(self._cache_file) else: self._cache = {}
Writes the cache to disk as JSON. def write_cache(self): """Writes the cache to disk as JSON.""" doc = { '__format__': 1, 'dependencies': self._cache, } with open(self._cache_file, 'w') as f: json.dump(doc, f, sort_keys=True)
Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency tree is resolved. def reverse_dependencies(self, ireqs): """ Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency tree is resolved. """ ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs] return self._reverse_dependencies(ireqs_as_cache_values)
Returns a lookup table of reverse dependencies for all the given cache keys. Example input: [('pep8', '1.5.7'), ('flake8', '2.4.0'), ('mccabe', '0.3'), ('pyflakes', '0.8.1')] Example output: {'pep8': ['flake8'], 'flake8': [], 'mccabe': ['flake8'], 'pyflakes': ['flake8']} def _reverse_dependencies(self, cache_keys): """ Returns a lookup table of reverse dependencies for all the given cache keys. Example input: [('pep8', '1.5.7'), ('flake8', '2.4.0'), ('mccabe', '0.3'), ('pyflakes', '0.8.1')] Example output: {'pep8': ['flake8'], 'flake8': [], 'mccabe': ['flake8'], 'pyflakes': ['flake8']} """ # First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'), # ('flake8', 'mccabe'), ...] return lookup_table((key_from_req(Requirement(dep_name)), name) for name, version_and_extras in cache_keys for dep_name in self.cache[name][version_and_extras])
Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example:: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so:: ("ipython", "2.1.0[nbconvert,notebook]") def as_cache_key(self, ireq): """Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example:: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so:: ("ipython", "2.1.0[nbconvert,notebook]") """ extras = tuple(sorted(ireq.extras)) if not extras: extras_string = "" else: extras_string = "[{}]".format(",".join(extras)) name = key_from_req(ireq.req) version = get_pinned_version(ireq) return name, "{}{}".format(version, extras_string)
Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... def locked(path, timeout=None): """Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... """ def decor(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock = FileLock(path, timeout=timeout) lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper return decor
Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). * "lxml": Optimized walker for lxml.etree * "genshi": a Genshi stream :arg implementation: A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree (Currently applies to the "etree" tree type only). :arg kwargs: keyword arguments passed to the etree walker--for other walkers, this has no effect :returns: a TreeWalker class def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). * "lxml": Optimized walker for lxml.etree * "genshi": a Genshi stream :arg implementation: A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree (Currently applies to the "etree" tree type only). :arg kwargs: keyword arguments passed to the etree walker--for other walkers, this has no effect :returns: a TreeWalker class """ treeType = treeType.lower() if treeType not in treeWalkerCache: if treeType == "dom": from . import dom treeWalkerCache[treeType] = dom.TreeWalker elif treeType == "genshi": from . import genshi treeWalkerCache[treeType] = genshi.TreeWalker elif treeType == "lxml": from . import etree_lxml treeWalkerCache[treeType] = etree_lxml.TreeWalker elif treeType == "etree": from . import etree if implementation is None: implementation = default_etree # XXX: NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeWalker return treeWalkerCache.get(treeType)
Pretty printer for tree walkers Takes a TreeWalker instance and pretty prints the output of walking the tree. :arg walker: a TreeWalker instance def pprint(walker): """Pretty printer for tree walkers Takes a TreeWalker instance and pretty prints the output of walking the tree. :arg walker: a TreeWalker instance """ output = [] indent = 0 for token in concatenateCharacterTokens(walker): type = token["type"] if type in ("StartTag", "EmptyTag"): # tag name if token["namespace"] and token["namespace"] != constants.namespaces["html"]: if token["namespace"] in constants.prefixes: ns = constants.prefixes[token["namespace"]] else: ns = token["namespace"] name = "%s %s" % (ns, token["name"]) else: name = token["name"] output.append("%s<%s>" % (" " * indent, name)) indent += 2 # attributes (sorted for consistent ordering) attrs = token["data"] for (namespace, localname), value in sorted(attrs.items()): if namespace: if namespace in constants.prefixes: ns = constants.prefixes[namespace] else: ns = namespace name = "%s %s" % (ns, localname) else: name = localname output.append("%s%s=\"%s\"" % (" " * indent, name, value)) # self-closing if type == "EmptyTag": indent -= 2 elif type == "EndTag": indent -= 2 elif type == "Comment": output.append("%s<!-- %s -->" % (" " * indent, token["data"])) elif type == "Doctype": if token["name"]: if token["publicId"]: output.append("""%s<!DOCTYPE %s "%s" "%s">""" % (" " * indent, token["name"], token["publicId"], token["systemId"] if token["systemId"] else "")) elif token["systemId"]: output.append("""%s<!DOCTYPE %s "" "%s">""" % (" " * indent, token["name"], token["systemId"])) else: output.append("%s<!DOCTYPE %s>" % (" " * indent, token["name"])) else: output.append("%s<!DOCTYPE >" % (" " * indent,)) elif type == "Characters": output.append("%s\"%s\"" % (" " * indent, token["data"])) elif type == "SpaceCharacters": assert False, "concatenateCharacterTokens should have got rid of all Space tokens" else: raise ValueError("Unknown token type, %s" % type) return "\n".join(output)
Hide the spinner to allow for custom writing to the terminal. def hide(self): """Hide the spinner to allow for custom writing to the terminal.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and not self._hide_spin.is_set(): # set the hidden spinner flag self._hide_spin.set() # clear the current line sys.stdout.write("\r") self._clear_line() # flush the stdout buffer so the current line can be rewritten to sys.stdout.flush()
Show the hidden spinner. def show(self): """Show the hidden spinner.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and self._hide_spin.is_set(): # clear the hidden spinner flag self._hide_spin.clear() # clear the current line so the spinner is not appended to it sys.stdout.write("\r") self._clear_line()
Write text in the terminal without breaking the spinner. def write(self, text): """Write text in the terminal without breaking the spinner.""" # similar to tqdm.write() # https://pypi.python.org/pypi/tqdm#writing-messages sys.stdout.write("\r") self._clear_line() _text = to_unicode(text) if PY2: _text = _text.encode(ENCODING) # Ensure output is bytes for Py2 and Unicode for Py3 assert isinstance(_text, builtin_str) sys.stdout.write("{0}\n".format(_text))
Stop spinner, compose last frame and 'freeze' it. def _freeze(self, final_text): """Stop spinner, compose last frame and 'freeze' it.""" text = to_unicode(final_text) self._last_frame = self._compose_out(text, mode="last") # Should be stopped here, otherwise prints after # self._freeze call will mess up the spinner self.stop() sys.stdout.write(self._last_frame)
Return the VCS-specific command arguments. def to_args(self): # type: () -> List[str] """ Return the VCS-specific command arguments. """ args = [] # type: List[str] rev = self.arg_rev if rev is not None: args += self.vcs.get_base_rev_args(rev) args += self.extra_args return args
Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. def make_new(self, rev): # type: (str) -> RevOptions """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
Return the type of the version control backend if found at given location, e.g. vcs.get_backend_type('/path/to/vcs/checkout') def get_backend_type(self, location): # type: (str) -> Optional[Type[VersionControl]] """ Return the type of the version control backend if found at given location, e.g. vcs.get_backend_type('/path/to/vcs/checkout') """ for vc_type in self._registry.values(): if vc_type.controls_location(location): logger.debug('Determine that %s uses VCS: %s', location, vc_type.name) return vc_type return None
posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\\folder) def _is_local_repository(cls, repo): # type: (str) -> bool """ posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\\folder) """ drive, tail = os.path.splitdrive(repo) return repo.startswith(os.path.sep) or bool(drive)
Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). def get_url_rev_and_auth(self, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] """ Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). """ scheme, netloc, path, query, frag = urllib_parse.urlsplit(url) if '+' not in scheme: raise ValueError( "Sorry, {!r} is a malformed VCS url. " "The format is <vcs>+<protocol>://<url>, " "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url) ) # Remove the vcs prefix. scheme = scheme.split('+', 1)[1] netloc, user_pass = self.get_netloc_and_auth(netloc, scheme) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urllib_parse.urlunsplit((scheme, netloc, path, query, '')) return url, rev, user_pass
Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). def get_url_rev_options(self, url): # type: (str) -> Tuple[str, RevOptions] """ Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). """ url, rev, user_pass = self.get_url_rev_and_auth(url) username, password = user_pass extra_args = self.make_rev_args(username, password) rev_options = self.make_rev_options(rev, extra_args=extra_args) return url, rev_options
Compare two repo URLs for identity, ignoring incidental differences. def compare_urls(self, url1, url2): # type: (str, str) -> bool """ Compare two repo URLs for identity, ignoring incidental differences. """ return (self.normalize_url(url1) == self.normalize_url(url2))
Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update. def obtain(self, dest): # type: (str) -> None """ Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update. """ url, rev_options = self.get_url_rev_options(self.url) if not os.path.exists(dest): self.fetch_new(dest, url, rev_options) return rev_display = rev_options.to_display() if self.is_repository_directory(dest): existing_url = self.get_remote_url(dest) if self.compare_urls(existing_url, url): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.is_commit_id_equal(dest, rev_options.rev): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, url, rev_options) else: logger.info('Skipping because already up-to-date.') return logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) # https://github.com/python/mypy/issues/1174 prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore ('i', 'w', 'b')) logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 'a': sys.exit(-1) if response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) self.fetch_new(dest, url, rev_options) return if response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) self.fetch_new(dest, url, rev_options) return # Do nothing if the response is "i". if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options)
Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available def run_command( cls, 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[Mapping[str, Any]] spinner=None # type: Optional[SpinnerInterface] ): # type: (...) -> Optional[Text] """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available """ cmd = [cls.name] + cmd try: return call_subprocess(cmd, show_stdout, cwd, on_returncode=on_returncode, extra_ok_returncodes=extra_ok_returncodes, command_desc=command_desc, extra_environ=extra_environ, unset_environ=cls.unset_environ, spinner=spinner) except OSError as e: # errno.ENOENT = no such file or directory # In other words, the VCS executable isn't available if e.errno == errno.ENOENT: raise BadCommand( 'Cannot find command %r - do you have ' '%r installed and in your ' 'PATH?' % (cls.name, cls.name)) else: raise
Return whether a directory path is a repository directory. def is_repository_directory(cls, path): # type: (str) -> bool """ Return whether a directory path is a repository directory. """ logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.dirname))
Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names def _script_names(dist, script_name, is_gui): """Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names """ if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py exe_name = os.path.join(bin_dir, script_name) paths_to_remove = [exe_name] if WINDOWS: paths_to_remove.append(exe_name + '.exe') paths_to_remove.append(exe_name + '.exe.manifest') if is_gui: paths_to_remove.append(exe_name + '-script.pyw') else: paths_to_remove.append(exe_name + '-script.py') return paths_to_remove
Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path. def compact(paths): """Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path.""" sep = os.path.sep short_paths = set() for path in sorted(paths, key=len): should_skip = any( path.startswith(shortpath.rstrip("*")) and path[len(shortpath.rstrip("*").rstrip(sep))] == sep for shortpath in short_paths ) if not should_skip: short_paths.add(path) return short_paths
Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. def compress_for_rename(paths): """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() def norm_join(*a): return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() all_subdirs = set() for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards
Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. def compress_for_output_listing(paths): """Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. """ will_remove = list(paths) will_skip = set() # Determine folders and files folders = set() files = set() for path in will_remove: if path.endswith(".pyc"): continue if path.endswith("__init__.py") or ".dist-info" in path: folders.add(os.path.dirname(path)) files.add(path) _normcased_files = set(map(os.path.normcase, files)) folders = compact(folders) # This walks the tree using os.walk to not miss extra folders # that might get added. for folder in folders: for dirpath, _, dirfiles in os.walk(folder): for fname in dirfiles: if fname.endswith(".pyc"): continue file_ = os.path.join(dirpath, fname) if (os.path.isfile(file_) and os.path.normcase(file_) not in _normcased_files): # We are skipping this file. Add it to the set. will_skip.add(file_) will_remove = files | { os.path.join(folder, "*") for folder in folders } return will_remove, will_skip
Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir. def _get_directory_stash(self, path): """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) save_dir.create() except OSError: save_dir = TempDirectory(kind="uninstall") save_dir.create() self._save_dirs[os.path.normcase(path)] = save_dir return save_dir.path
Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory. def _get_file_stash(self, path): """Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.""" path = os.path.normcase(path) head, old_head = os.path.dirname(path), None save_dir = None while head != old_head: try: save_dir = self._save_dirs[head] break except KeyError: pass head, old_head = os.path.dirname(head), head else: # Did not find any suitable root head = os.path.dirname(path) save_dir = TempDirectory(kind='uninstall') save_dir.create() self._save_dirs[head] = save_dir relpath = os.path.relpath(path, head) if relpath and relpath != os.path.curdir: return os.path.join(save_dir.path, relpath) return save_dir.path
Stashes the directory or file and returns its new location. def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if os.path.isdir(path) and os.path.isdir(new_path): # If we're moving a directory, we need to # remove the destination first or else it will be # moved to inside the existing directory. # We just created new_path ourselves, so it will # be removable. os.rmdir(new_path) renames(path, new_path) return new_path
Commits the uninstall by removing stashed files. def commit(self): """Commits the uninstall by removing stashed files.""" for _, save_dir in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {}
Undoes the uninstall by moving stashed files back. def rollback(self): """Undoes the uninstall by moving stashed files back.""" for p in self._moves: logging.info("Moving to %s\n from %s", *p) for new_path, path in self._moves: try: logger.debug('Replacing %s from %s', new_path, path) if os.path.isfile(new_path): os.unlink(new_path) elif os.path.isdir(new_path): rmtree(new_path) renames(path, new_path) except OSError as ex: logger.error("Failed to restore %s", new_path) logger.debug("Exception: %s", ex) self.commit()
Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True). def remove(self, auto_confirm=False, verbose=False): """Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).""" if not self.paths: logger.info( "Can't uninstall '%s'. No files were found to uninstall.", self.dist.project_name, ) return dist_name_version = ( self.dist.project_name + "-" + self.dist.version ) logger.info('Uninstalling %s:', dist_name_version) with indent_log(): if auto_confirm or self._allowed_to_proceed(verbose): moved = self._moved_paths for_rename = compress_for_rename(self.paths) for path in sorted(compact(for_rename)): moved.stash(path) logger.debug('Removing file or directory %s', path) for pth in self.pth.values(): pth.remove() logger.info('Successfully uninstalled %s', dist_name_version)
Display which files would be deleted and prompt for confirmation def _allowed_to_proceed(self, verbose): """Display which files would be deleted and prompt for confirmation """ def _display(msg, paths): if not paths: return logger.info(msg) with indent_log(): for path in sorted(compact(paths)): logger.info(path) if not verbose: will_remove, will_skip = compress_for_output_listing(self.paths) else: # In verbose mode, display all the files that are going to be # deleted. will_remove = list(self.paths) will_skip = set() _display('Would remove:', will_remove) _display('Would not remove (might be manually added):', will_skip) _display('Would not remove (outside of prefix):', self._refuse) if verbose: _display('Will actually move:', compress_for_rename(self.paths)) return ask('Proceed (y/n)? ', ('y', 'n')) == 'y'
Rollback the changes previously made by remove(). def rollback(self): """Rollback the changes previously made by remove().""" if not self._moved_paths.can_rollback: logger.error( "Can't roll back %s; was not uninstalled", self.dist.project_name, ) return False logger.info('Rolling back uninstall of %s', self.dist.project_name) self._moved_paths.rollback() for pth in self.pth.values(): pth.rollback()
>>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io') def author(self): """ >>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io') """ author = namedtuple('Author', 'name email') return author(name=self._package['author'], email=self._package['author_email'])
>>> package = yarg.get('yarg') >>> package.maintainer Maintainer(name=u'Kura', email=u'kura@kura.io') def maintainer(self): """ >>> package = yarg.get('yarg') >>> package.maintainer Maintainer(name=u'Kura', email=u'kura@kura.io') """ maintainer = namedtuple('Maintainer', 'name email') return maintainer(name=self._package['maintainer'], email=self._package['maintainer_email'])
>>> package = yarg.get('yarg') >>> package.license_from_classifiers u'MIT License' def license_from_classifiers(self): """ >>> package = yarg.get('yarg') >>> package.license_from_classifiers u'MIT License' """ if len(self.classifiers) > 0: for c in self.classifiers: if c.startswith("License"): return c.split(" :: ")[-1]
>>> package = yarg.get('yarg') >>> package.downloads Downloads(day=50100, week=367941, month=1601938) # I wish def downloads(self): """ >>> package = yarg.get('yarg') >>> package.downloads Downloads(day=50100, week=367941, month=1601938) # I wish """ _downloads = self._package['downloads'] downloads = namedtuple('Downloads', 'day week month') return downloads(day=_downloads['last_day'], week=_downloads['last_week'], month=_downloads['last_month'])
Returns a list of Python version strings that the package has listed in :attr:`yarg.Release.classifiers`. >>> package = yarg.get('yarg') >>> package.python_versions [u'2.6', u'2.7', u'3.3', u'3.4'] def python_versions(self): """ Returns a list of Python version strings that the package has listed in :attr:`yarg.Release.classifiers`. >>> package = yarg.get('yarg') >>> package.python_versions [u'2.6', u'2.7', u'3.3', u'3.4'] """ version_re = re.compile(r"""Programming Language \:\: """ """Python \:\: \d\.\d""") return [c.split(' :: ')[-1] for c in self.classifiers if version_re.match(c)]
>>> package = yarg.get('yarg') >>> package.release_ids [u'0.0.1', u'0.0.5', u'0.1.0'] def release_ids(self): """ >>> package = yarg.get('yarg') >>> package.release_ids [u'0.0.1', u'0.0.5', u'0.1.0'] """ r = [(k, self._releases[k][0]['upload_time']) for k in self._releases.keys() if len(self._releases[k]) > 0] return [k[0] for k in sorted(r, key=lambda k: k[1])]
A list of :class:`yarg.release.Release` objects for each file in a release. :param release_id: A pypi release id. >>> package = yarg.get('yarg') >>> last_release = yarg.releases[-1] >>> package.release(last_release) [<Release 0.1.0>, <Release 0.1.0>] def release(self, release_id): """ A list of :class:`yarg.release.Release` objects for each file in a release. :param release_id: A pypi release id. >>> package = yarg.get('yarg') >>> last_release = yarg.releases[-1] >>> package.release(last_release) [<Release 0.1.0>, <Release 0.1.0>] """ if release_id not in self.release_ids: return None return [Release(release_id, r) for r in self._releases[release_id]]
Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. def is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. """ # follow symlinks, fpath = os.path.realpath(path) if not os.path.isfile(fpath): # non-files (directories, fifo, etc.) return False mode = os.stat(fpath).st_mode if (sys.platform.startswith('sunos') and os.getuid() == 0): # When root on Solaris, os.X_OK is True for *all* files, irregardless # of their executability -- instead, any permission bit of any user, # group, or other is fine enough. # # (This may be true for other "Unix98" OS's such as HP-UX and AIX) return bool(mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) return os.access(fpath, os.X_OK)
This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. def which(filename, env=None): '''This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.''' # Special case where filename contains an explicit path. if os.path.dirname(filename) != '' and is_executable_file(filename): return filename if env is None: env = os.environ p = env.get('PATH') if not p: p = os.defpath pathlist = p.split(os.pathsep) for path in pathlist: ff = os.path.join(path, filename) if is_executable_file(ff): return ff return None
This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. def split_command_line(command_line): '''This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. ''' arg_list = [] arg = '' # Constants to name the states we can be in. state_basic = 0 state_esc = 1 state_singlequote = 2 state_doublequote = 3 # The state when consuming whitespace between commands. state_whitespace = 4 state = state_basic for c in command_line: if state == state_basic or state == state_whitespace: if c == '\\': # Escape the next character state = state_esc elif c == r"'": # Handle single quote state = state_singlequote elif c == r'"': # Handle double quote state = state_doublequote elif c.isspace(): # Add arg to arg_list if we aren't in the middle of whitespace. if state == state_whitespace: # Do nothing. None else: arg_list.append(arg) arg = '' state = state_whitespace else: arg = arg + c state = state_basic elif state == state_esc: arg = arg + c state = state_basic elif state == state_singlequote: if c == r"'": state = state_basic else: arg = arg + c elif state == state_doublequote: if c == r'"': state = state_basic else: arg = arg + c if arg != '': arg_list.append(arg) return arg_list
This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None): '''This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). ''' # if select() is interrupted by a signal (errno==EINTR) then # we loop back and enter the select() again. if timeout is not None: end_time = time.time() + timeout while True: try: return select.select(iwtd, owtd, ewtd, timeout) except InterruptedError: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: # if we loop back we have to subtract the # amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return([], [], []) else: # something else caused the select.error, so # this actually is an exception. raise
Simple wrapper around poll to register file descriptors and ignore signals. def poll_ignore_interrupts(fds, timeout=None): '''Simple wrapper around poll to register file descriptors and ignore signals.''' if timeout is not None: end_time = time.time() + timeout poller = select.poll() for fd in fds: poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) while True: try: timeout_ms = None if timeout is None else timeout * 1000 results = poller.poll(timeout_ms) return [afd for afd, _ in results] except InterruptedError: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: # if we loop back we have to subtract the # amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return [] else: # something else caused the select.error, so # this actually is an exception. raise
Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything. def _suggest_semantic_version(s): """ Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything. """ result = s.strip().lower() for pat, repl in _REPLACEMENTS: result = pat.sub(repl, result) if not result: result = '0.0.0' # Now look for numeric prefix, and separate it out from # the rest. #import pdb; pdb.set_trace() m = _NUMERIC_PREFIX.match(result) if not m: prefix = '0.0.0' suffix = result else: prefix = m.groups()[0].split('.') prefix = [int(i) for i in prefix] while len(prefix) < 3: prefix.append(0) if len(prefix) == 3: suffix = result[m.end():] else: suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():] prefix = prefix[:3] prefix = '.'.join([str(i) for i in prefix]) suffix = suffix.strip() if suffix: #import pdb; pdb.set_trace() # massage the suffix. for pat, repl in _SUFFIX_REPLACEMENTS: suffix = pat.sub(repl, suffix) if not suffix: result = prefix else: sep = '-' if 'dev' in suffix else '+' result = prefix + sep + suffix if not is_semver(result): result = None return result
Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. def _suggest_normalized_version(s): """Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. """ try: _normalized_key(s) return s # already rational except UnsupportedVersionError: pass rs = s.lower() # part of this could use maketrans for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), ('beta', 'b'), ('rc', 'c'), ('-final', ''), ('-pre', 'c'), ('-release', ''), ('.release', ''), ('-stable', ''), ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), ('final', '')): rs = rs.replace(orig, repl) # if something ends with dev or pre, we add a 0 rs = re.sub(r"pre$", r"pre0", rs) rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the # version, that is probably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) # 1.0-dev-r371 -> 1.0.dev371 # 0.1-dev-r79 -> 0.1.dev79 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) # Clean: v0.3, v1.0 if rs.startswith('v'): rs = rs[1:] # Clean leading '0's on numbers. #TODO: unintended side-effect on, e.g., "2003.05.09" # PyPI stats: 77 (~2%) better rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers # zero. # PyPI stats: 245 (7.56%) better rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) # the 'dev-rNNN' tag is a dev tag rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) # clean the - when used as a pre delimiter rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) # a terminal "dev" or "devel" can be changed into ".dev0" rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) # a terminal "dev" can be changed into ".dev0" rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) # a terminal "final" or "stable" can be removed rs = re.sub(r"(final|stable)$", "", rs) # The 'r' and the '-' tags are post release tags # 0.4a1.r10 -> 0.4a1.post10 # 0.9.33-17222 -> 0.9.33.post17222 # 0.9.33-r17222 -> 0.9.33.post17222 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) # Clean 'r' instead of 'dev' usage: # 0.9.33+r17222 -> 0.9.33.dev17222 # 1.0dev123 -> 1.0.dev123 # 1.0.git123 -> 1.0.dev123 # 1.0.bzr123 -> 1.0.dev123 # 0.1a0dev.123 -> 0.1a0.dev123 # PyPI stats: ~150 (~4%) better rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: # 0.2.pre1 -> 0.2c1 # 0.2-c1 -> 0.2c1 # 1.0preview123 -> 1.0c123 # PyPI stats: ~21 (0.62%) better rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) # Tcl/Tk uses "px" for their post release markers rs = re.sub(r"p(\d+)$", r".post\1", rs) try: _normalized_key(rs) except UnsupportedVersionError: rs = None return rs
Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance. def match(self, version): """ Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) for operator, constraint, prefix in self._parts: f = self._operators.get(operator) if isinstance(f, string_types): f = getattr(self, f) if not f: msg = ('%r not implemented ' 'for %s' % (operator, self.__class__.__name__)) raise NotImplementedError(msg) if not f(version, constraint, prefix): return False return True
Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the filesystem def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"): """ Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the filesystem """ value_to_set = value_to_set.strip("'").strip('"') if not os.path.exists(dotenv_path): warnings.warn("can't write to %s - it doesn't exist." % dotenv_path) return None, key_to_set, value_to_set if " " in value_to_set: quote_mode = "always" line_template = '{}="{}"\n' if quote_mode == "always" else '{}={}\n' line_out = line_template.format(key_to_set, value_to_set) with rewrite(dotenv_path) as (source, dest): replaced = False for mapping in parse_stream(source): if mapping.key == key_to_set: dest.write(line_out) replaced = True else: dest.write(mapping.original) if not replaced: dest.write(line_out) return True, key_to_set, value_to_set
Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails def unset_key(dotenv_path, key_to_unset, quote_mode="always"): """ Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails """ if not os.path.exists(dotenv_path): warnings.warn("can't delete from %s - it doesn't exist." % dotenv_path) return None, key_to_unset removed = False with rewrite(dotenv_path) as (source, dest): for mapping in parse_stream(source): if mapping.key == key_to_unset: removed = True else: dest.write(mapping.original) if not removed: warnings.warn("key %s not removed from %s - key doesn't exist." % (key_to_unset, dotenv_path)) return None, key_to_unset return removed, key_to_unset
Yield directories starting from the given directory up to the root def _walk_to_root(path): """ Yield directories starting from the given directory up to the root """ if not os.path.exists(path): raise IOError('Starting path not found') if os.path.isfile(path): path = os.path.dirname(path) last_dir = None current_dir = os.path.abspath(path) while last_dir != current_dir: yield current_dir parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) last_dir, current_dir = current_dir, parent_dir
Run command in sub process. Runs the command in a sub process with the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additional environment variables Returns ------- int The return code of the command def run_command(command, env): """Run command in sub process. Runs the command in a sub process with the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additional environment variables Returns ------- int The return code of the command """ # copy the current environment variables and add the vales from # `env` cmd_env = os.environ.copy() cmd_env.update(env) p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env) _, _ = p.communicate() return p.returncode
Return dotenv as dict def dict(self): """Return dotenv as dict""" if self._dict: return self._dict values = OrderedDict(self.parse()) self._dict = resolve_nested_variables(values) return self._dict
Load the current dotenv as system environemt variable. def set_as_environment_variables(self, override=False): """ Load the current dotenv as system environemt variable. """ for k, v in self.dict().items(): if k in os.environ and not override: continue # With Python2 on Windows, force environment variables to str to avoid # "TypeError: environment can only contain strings" in Python's subprocess.py. if PY2 and WIN: if isinstance(k, text_type) or isinstance(v, text_type): k = k.encode('ascii') v = v.encode('ascii') os.environ[k] = v return True
Get an all-lowercase version of the requirement's name. def _key_from_req(req): """Get an all-lowercase version of the requirement's name.""" if hasattr(req, 'key'): # from pkg_resources, such as installed dists for pip-sync key = req.key else: # from packaging, such as install requirements from requirements.txt key = req.name key = key.replace('_', '-').lower() return key
Reads the cached contents into memory. def read_cache(self): """Reads the cached contents into memory. """ if os.path.exists(self._cache_file): self._cache = _read_cache_file(self._cache_file) else: self._cache = {}
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError("'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer.") # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError("'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer.")
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. """ def idna_encode(name): """ Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. """ from pipenv.patched.notpip._vendor import idna try: for prefix in [u'*.', u'.']: if name.startswith(prefix): name = name[len(prefix):] return prefix.encode('ascii') + idna.encode(name) return idna.encode(name) except idna.core.IDNAError: return None name = idna_encode(name) if name is None: return None elif sys.version_info >= (3, 0): name = name.decode('utf-8') return name
Given an PyOpenSSL certificate, provides all the subject alternative names. def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
feed a character with known length def feed(self, char, char_len): """feed a character with known length""" if char_len == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(char) else: order = -1 if order >= 0: self._total_chars += 1 # order is valid if order < self._table_size: if 512 > self._char_to_freq_order[order]: self._freq_chars += 1
return confidence based on existing data def get_confidence(self): """return confidence based on existing data""" # if we didn't receive any character in our consideration range, # return negative answer if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD: return self.SURE_NO if self._total_chars != self._freq_chars: r = (self._freq_chars / ((self._total_chars - self._freq_chars) * self.typical_distribution_ratio)) if r < self.SURE_YES: return r # normalize confidence (we don't want to be 100% sure) return self.SURE_YES