Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def find_all_matches(finder, ireq, pre=False): # type: (PackageFinder, InstallRequirement, bool) -> List[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
[ "Find all matching dependencies using the supplied finder and the\n given ireq.\n\n :param finder: A package finder for discovering matching candidates.\n :type finder: :class:`~pip._internal.index.PackageFinder`\n :param ireq: An install requirement.\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A list of matching candidates.\n :rtype: list[:class:`~pip._internal.index.InstallationCandidate`]\n " ]
Please provide a description of the function:def get_abstract_dependencies(reqs, sources=None, parent=None): 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 abstract dependencies for a given list of requirements.\n\n Given a set of requirements, convert each requirement to an Abstract Dependency.\n\n :param reqs: A list of Requirements\n :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]\n :param sources: Pipfile-formatted sources, defaults to None\n :param sources: list[dict], optional\n :param parent: The parent of this list of dependencies, defaults to None\n :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional\n :return: A list of Abstract Dependencies\n :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]\n " ]
Please provide a description of the function:def get_dependencies(ireq, sources=None, parent=None): # type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...] 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))
[ "Get all dependencies for a given install requirement.\n\n :param ireq: A single InstallRequirement\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :param sources: Pipfile-formatted sources, defaults to None\n :type sources: list[dict], optional\n :param parent: The parent of this list of dependencies, defaults to None\n :type parent: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str)\n " ]
Please provide a description of the function:def get_dependencies_from_wheel_cache(ireq): 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 wheel cache.\n\n :param ireq: A single InstallRequirement\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str) or None\n " ]
Please provide a description of the function:def get_dependencies_from_json(ireq): 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 json api.\n\n :param ireq: A single InstallRequirement\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str) or None\n " ]
Please provide a description of the function:def get_dependencies_from_cache(ireq): 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 dependency cache.\n\n :param ireq: A single InstallRequirement\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str) or None\n " ]
Please provide a description of the function:def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=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
[ "Retrieves dependencies for the given install requirement from the pip resolver.\n\n :param dep: A single InstallRequirement\n :type dep: :class:`~pip._internal.req.req_install.InstallRequirement`\n :param sources: Pipfile-formatted sources, defaults to None\n :type sources: list[dict], optional\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str) or None\n " ]
Please provide a description of the function:def get_pip_options(args=[], sources=None, pip_command=None): 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
[ "Build a pip command from a list of sources\n\n :param args: positional arguments passed through to the pip parser\n :param sources: A list of pipfile-formatted sources, defaults to None\n :param sources: list[dict], optional\n :param pip_command: A pre-built pip command instance\n :type pip_command: :class:`~pip._internal.cli.base_command.Command`\n :return: An instance of pip_options using the supplied arguments plus sane defaults\n :rtype: :class:`~pip._internal.cli.cmdoptions`\n " ]
Please provide a description of the function:def get_finder(sources=None, pip_command=None, pip_options=None): # type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> 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
[ "Get a package finder for looking up candidates to install\n\n :param sources: A list of pipfile-formatted sources, defaults to None\n :param sources: list[dict], optional\n :param pip_command: A pip command instance, defaults to None\n :type pip_command: :class:`~pip._internal.cli.base_command.Command`\n :param pip_options: A pip options, defaults to None\n :type pip_options: :class:`~pip._internal.cli.cmdoptions`\n :return: A package finder\n :rtype: :class:`~pip._internal.index.PackageFinder`\n " ]
Please provide a description of the function:def start_resolver(finder=None, wheel_cache=None): 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()
[ "Context manager to produce a resolver.\n\n :param finder: A package finder to use for searching the index\n :type finder: :class:`~pip._internal.index.PackageFinder`\n :return: A 3-tuple of finder, preparer, resolver\n :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`)\n " ]
Please provide a description of the function:def as_cache_key(self, ireq): name, version, extras = as_tuple(ireq) if not extras: extras_string = "" else: extras_string = "[{}]".format(",".join(extras)) return name, "{}{}".format(version, extras_string)
[ "\n Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards\n compatibility with cache files. For a requirement without extras, this will return, for example:\n\n (\"ipython\", \"2.1.0\")\n\n For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets,\n like so:\n\n (\"ipython\", \"2.1.0[nbconvert,notebook]\")\n " ]
Please provide a description of the function:def read_cache(self): if os.path.exists(self._cache_file): self._cache = read_cache_file(self._cache_file) else: self._cache = {}
[ "Reads the cached contents into memory." ]
Please provide a description of the function:def write_cache(self): doc = { '__format__': 1, 'dependencies': self._cache, } with open(self._cache_file, 'w') as f: json.dump(doc, f, sort_keys=True)
[ "Writes the cache to disk as JSON." ]
Please provide a description of the function:def reverse_dependencies(self, ireqs): ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs] return self._reverse_dependencies(ireqs_as_cache_values)
[ "\n Returns a lookup table of reverse dependencies for all the given ireqs.\n\n Since this is all static, it only works if the dependency cache\n contains the complete data, otherwise you end up with a partial view.\n This is typically no problem if you use this function after the entire\n dependency tree is resolved.\n " ]
Please provide a description of the function:def _reverse_dependencies(self, cache_keys): # 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])
[ "\n Returns a lookup table of reverse dependencies for all the given cache keys.\n\n Example input:\n\n [('pep8', '1.5.7'),\n ('flake8', '2.4.0'),\n ('mccabe', '0.3'),\n ('pyflakes', '0.8.1')]\n\n Example output:\n\n {'pep8': ['flake8'],\n 'flake8': [],\n 'mccabe': ['flake8'],\n 'pyflakes': ['flake8']}\n\n " ]
Please provide a description of the function:def as_cache_key(self, ireq): 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)
[ "Given a requirement, return its cache key.\n\n This behavior is a little weird in order to allow backwards\n compatibility with cache files. For a requirement without extras, this\n will return, for example::\n\n (\"ipython\", \"2.1.0\")\n\n For a requirement with extras, the extras will be comma-separated and\n appended to the version, inside brackets, like so::\n\n (\"ipython\", \"2.1.0[nbconvert,notebook]\")\n " ]
Please provide a description of the function:def locked(path, timeout=None): 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
[ "Decorator which enables locks for decorated function.\n\n Arguments:\n - path: path for lockfile.\n - timeout (optional): Timeout for acquiring lock.\n\n Usage:\n @locked('/var/run/myname', timeout=0)\n def myname(...):\n ...\n " ]
Please provide a description of the function:def getTreeWalker(treeType, implementation=None, **kwargs): 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)
[ "Get a TreeWalker class for various types of tree with built-in support\n\n :arg str treeType: the name of the tree type required (case-insensitive).\n Supported values are:\n\n * \"dom\": The xml.dom.minidom DOM implementation\n * \"etree\": A generic walker for tree implementations exposing an\n elementtree-like interface (known to work with ElementTree,\n cElementTree and lxml.etree).\n * \"lxml\": Optimized walker for lxml.etree\n * \"genshi\": a Genshi stream\n\n :arg implementation: A module implementing the tree type e.g.\n xml.etree.ElementTree or cElementTree (Currently applies to the \"etree\"\n tree type only).\n\n :arg kwargs: keyword arguments passed to the etree walker--for other\n walkers, this has no effect\n\n :returns: a TreeWalker class\n\n " ]
Please provide a description of the function:def pprint(walker): 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( % (" " * indent, token["name"], token["publicId"], token["systemId"] if token["systemId"] else "")) elif token["systemId"]: output.append( % (" " * 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)
[ "Pretty printer for tree walkers\n\n Takes a TreeWalker instance and pretty prints the output of walking the tree.\n\n :arg walker: a TreeWalker instance\n\n ", "%s<!DOCTYPE %s \"%s\" \"%s\">", "%s<!DOCTYPE %s \"\" \"%s\">" ]
Please provide a description of the function:def hide(self): 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()
[ "Hide the spinner to allow for custom writing to the terminal." ]
Please provide a description of the function:def show(self): 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()
[ "Show the hidden spinner." ]
Please provide a description of the function:def write(self, text): # 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))
[ "Write text in the terminal without breaking the spinner." ]
Please provide a description of the function:def _freeze(self, final_text): 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)
[ "Stop spinner, compose last frame and 'freeze' it." ]
Please provide a description of the function:def to_args(self): # type: () -> List[str] 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
[ "\n Return the VCS-specific command arguments.\n " ]
Please provide a description of the function:def make_new(self, rev): # type: (str) -> RevOptions return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
[ "\n Make a copy of the current instance, but with a new rev.\n\n Args:\n rev: the name of the revision for the new object.\n " ]
Please provide a description of the function:def get_backend_type(self, location): # type: (str) -> Optional[Type[VersionControl]] 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
[ "\n Return the type of the version control backend if found at given\n location, e.g. vcs.get_backend_type('/path/to/vcs/checkout')\n " ]
Please provide a description of the function:def _is_local_repository(cls, repo): # type: (str) -> bool drive, tail = os.path.splitdrive(repo) return repo.startswith(os.path.sep) or bool(drive)
[ "\n posix absolute paths start with os.path.sep,\n win32 ones start with drive (like c:\\\\folder)\n " ]
Please provide a description of the function:def get_url_rev_and_auth(self, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] 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
[ "\n Parse the repository URL to use, and return the URL, revision,\n and auth info to use.\n\n Returns: (url, rev, (username, password)).\n " ]
Please provide a description of the function:def get_url_rev_options(self, url): # type: (str) -> Tuple[str, RevOptions] 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
[ "\n Return the URL and RevOptions object to use in obtain() and in\n some cases export(), as a tuple (url, rev_options).\n " ]
Please provide a description of the function:def compare_urls(self, url1, url2): # type: (str, str) -> bool return (self.normalize_url(url1) == self.normalize_url(url2))
[ "\n Compare two repo URLs for identity, ignoring incidental differences.\n " ]
Please provide a description of the function:def obtain(self, dest): # type: (str) -> None 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)
[ "\n Install or update in editable mode the package represented by this\n VersionControl object.\n\n Args:\n dest: the repository directory in which to install or update.\n " ]
Please provide a description of the function: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] 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
[ "\n Run a VCS subcommand\n This is simply a wrapper around call_subprocess that adds the VCS\n command name, and checks that the VCS is available\n " ]
Please provide a description of the function:def is_repository_directory(cls, path): # type: (str) -> bool logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.dirname))
[ "\n Return whether a directory path is a repository directory.\n " ]
Please provide a description of the function:def _script_names(dist, script_name, is_gui): 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
[ "Create the fully qualified name of the files created by\n {console,gui}_scripts for the given ``dist``.\n Returns the list of file names\n " ]
Please provide a description of the function:def compact(paths): 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
[ "Compact a path set to contain the minimal number of paths\n necessary to contain all paths in the set. If /a/path/ and\n /a/path/to/a/file.txt are both in the set, leave only the\n shorter path." ]
Please provide a description of the function:def compress_for_rename(paths): 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 set containing the paths that need to be renamed.\n\n This set may include directories when the original sequence of paths\n included every file on disk.\n " ]
Please provide a description of the function:def compress_for_output_listing(paths): 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
[ "Returns a tuple of 2 sets of which paths to display to user\n\n The first set contains paths that would be deleted. Files of a package\n are not added and the top-level directory of the package has a '*' added\n at the end - to signify that all it's contents are removed.\n\n The second set contains files that would have been skipped in the above\n folders.\n " ]
Please provide a description of the function:def _get_directory_stash(self, path): 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 directory.\n\n Directories are stashed adjacent to their original location if\n possible, or else moved/copied into the user's temp dir." ]
Please provide a description of the function:def _get_file_stash(self, path): 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 a file.\n\n If no root has been provided, one will be created for the directory\n in the user's temp directory." ]
Please provide a description of the function:def stash(self, path): 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
[ "Stashes the directory or file and returns its new location.\n " ]
Please provide a description of the function:def commit(self): for _, save_dir in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {}
[ "Commits the uninstall by removing stashed files." ]
Please provide a description of the function:def rollback(self): 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()
[ "Undoes the uninstall by moving stashed files back." ]
Please provide a description of the function:def remove(self, auto_confirm=False, verbose=False): 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)
[ "Remove paths in ``self.paths`` with confirmation (unless\n ``auto_confirm`` is True)." ]
Please provide a description of the function:def _allowed_to_proceed(self, verbose): 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'
[ "Display which files would be deleted and prompt for confirmation\n " ]
Please provide a description of the function:def rollback(self): 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()
[ "Rollback the changes previously made by remove()." ]
Please provide a description of the function:def author(self): author = namedtuple('Author', 'name email') return author(name=self._package['author'], email=self._package['author_email'])
[ "\n >>> package = yarg.get('yarg')\n >>> package.author\n Author(name=u'Kura', email=u'[email protected]')\n " ]
Please provide a description of the function:def maintainer(self): maintainer = namedtuple('Maintainer', 'name email') return maintainer(name=self._package['maintainer'], email=self._package['maintainer_email'])
[ "\n >>> package = yarg.get('yarg')\n >>> package.maintainer\n Maintainer(name=u'Kura', email=u'[email protected]')\n " ]
Please provide a description of the function:def license_from_classifiers(self): if len(self.classifiers) > 0: for c in self.classifiers: if c.startswith("License"): return c.split(" :: ")[-1]
[ "\n >>> package = yarg.get('yarg')\n >>> package.license_from_classifiers\n u'MIT License'\n " ]
Please provide a description of the function:def downloads(self): _downloads = self._package['downloads'] downloads = namedtuple('Downloads', 'day week month') return downloads(day=_downloads['last_day'], week=_downloads['last_week'], month=_downloads['last_month'])
[ "\n >>> package = yarg.get('yarg')\n >>> package.downloads\n Downloads(day=50100, week=367941, month=1601938) # I wish\n " ]
Please provide a description of the function:def python_versions(self): version_re = re.compile(r ) return [c.split(' :: ')[-1] for c in self.classifiers if version_re.match(c)]
[ "\n Returns a list of Python version strings that\n the package has listed in :attr:`yarg.Release.classifiers`.\n\n >>> package = yarg.get('yarg')\n >>> package.python_versions\n [u'2.6', u'2.7', u'3.3', u'3.4']\n ", "Programming Language \\:\\: ", "Python \\:\\: \\d\\.\\d" ]
Please provide a description of the function:def release_ids(self): 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])]
[ "\n >>> package = yarg.get('yarg')\n >>> package.release_ids\n [u'0.0.1', u'0.0.5', u'0.1.0']\n " ]
Please provide a description of the function:def release(self, release_id): if release_id not in self.release_ids: return None return [Release(release_id, r) for r in self._releases[release_id]]
[ "\n A list of :class:`yarg.release.Release` objects for each file in a\n release.\n\n :param release_id: A pypi release id.\n\n >>> package = yarg.get('yarg')\n >>> last_release = yarg.releases[-1]\n >>> package.release(last_release)\n [<Release 0.1.0>, <Release 0.1.0>]\n " ]
Please provide a description of the function:def is_executable_file(path): # 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)
[ "Checks that path is an executable regular file, or a symlink towards one.\n\n This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.\n " ]
Please provide a description of the function: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
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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
[]
Please provide a description of the function:def _suggest_semantic_version(s): 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
[ "\n Try to suggest a semantic form for a version for which\n _suggest_normalized_version couldn't come up with anything.\n " ]
Please provide a description of the function:def _suggest_normalized_version(s): 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
[ "Suggest a normalized version close to the given version string.\n\n If you have a version string that isn't rational (i.e. NormalizedVersion\n doesn't like it) then you might be able to get an equivalent (or close)\n rational version from this function.\n\n This does a number of simple normalizations to the given string, based\n on observation of versions currently in use on PyPI. Given a dump of\n those version during PyCon 2009, 4287 of them:\n - 2312 (53.93%) match NormalizedVersion without change\n with the automatic suggestion\n - 3474 (81.04%) match when using this suggestion method\n\n @param s {str} An irrational version string.\n @returns A rational version string, or None, if couldn't determine one.\n " ]
Please provide a description of the function:def match(self, version): 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
[ "\n Check if the provided version matches the constraints.\n\n :param version: The version to match against this instance.\n :type version: String or :class:`Version` instance.\n " ]
Please provide a description of the function:def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"): 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
[ "\n Adds or Updates a key/value to the given .env\n\n If the .env path given doesn't exist, fails instead of risking creating\n an orphan .env somewhere in the filesystem\n " ]
Please provide a description of the function:def unset_key(dotenv_path, key_to_unset, quote_mode="always"): 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
[ "\n Removes a given key from the given .env\n\n If the .env path given doesn't exist, fails\n If the given key doesn't exist in the .env, fails\n " ]
Please provide a description of the function:def _walk_to_root(path): 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
[ "\n Yield directories starting from the given directory up to the root\n " ]
Please provide a description of the function:def run_command(command, env): # 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
[ "Run command in sub process.\n\n Runs the command in a sub process with the variables from `env`\n added in the current environment variables.\n\n Parameters\n ----------\n command: List[str]\n The command and it's parameters\n env: Dict\n The additional environment variables\n\n Returns\n -------\n int\n The return code of the command\n\n " ]
Please provide a description of the function:def dict(self): if self._dict: return self._dict values = OrderedDict(self.parse()) self._dict = resolve_nested_variables(values) return self._dict
[ "Return dotenv as dict" ]
Please provide a description of the function:def set_as_environment_variables(self, override=False): 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
[ "\n Load the current dotenv as system environemt variable.\n " ]
Please provide a description of the function:def _key_from_req(req): 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
[ "Get an all-lowercase version of the requirement's name." ]
Please provide a description of the function:def read_cache(self): if os.path.exists(self._cache_file): self._cache = _read_cache_file(self._cache_file) else: self._cache = {}
[ "Reads the cached contents into memory.\n " ]
Please provide a description of the function: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
[]
Please provide a description of the function:def _validate_dependencies_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.")
[ "\n Verifies that PyOpenSSL's package-level dependencies have been met.\n Throws `ImportError` if they are not met.\n " ]
Please provide a description of the function:def _dnsname_to_stdlib(name): def idna_encode(name): 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
[ "\n Converts a dNSName SubjectAlternativeName field to the form used by the\n standard library on the given Python version.\n\n Cryptography produces a dNSName as a unicode string that was idna-decoded\n from ASCII bytes. We need to idna-encode that string to get it back, and\n then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n If the name cannot be idna-encoded then we return None signalling that\n the name given should be skipped.\n ", "\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoids that problem.\n " ]
Please provide a description of the function:def get_subj_alt_name(peer_cert): # 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
[ "\n Given an PyOpenSSL certificate, provides all the subject alternative names.\n " ]
Please provide a description of the function:def feed(self, char, char_len): 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
[ "feed a character with known length" ]
Please provide a description of the function:def get_confidence(self): # 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
[ "return confidence based on existing data" ]
Please provide a description of the function:def _get_requests_session(): global requests_session if requests_session is not None: return requests_session import requests requests_session = requests.Session() adapter = requests.adapters.HTTPAdapter( max_retries=environments.PIPENV_MAX_RETRIES ) requests_session.mount("https://pypi.org/pypi", adapter) return requests_session
[ "Load requests lazily." ]
Please provide a description of the function:def convert_toml_outline_tables(parsed): def convert_tomlkit_table(section): for key, value in section._body: if not key: continue if hasattr(value, "keys") and not isinstance(value, tomlkit.items.InlineTable): table = tomlkit.inline_table() table.update(value.value) section[key.key] = table def convert_toml_table(section): for package, value in section.items(): if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict): table = toml.TomlDecoder().get_empty_inline_table() table.update(value) section[package] = table is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container) for section in ("packages", "dev-packages"): table_data = parsed.get(section, {}) if not table_data: continue if is_tomlkit_parsed: convert_tomlkit_table(table_data) else: convert_toml_table(table_data) return parsed
[ "Converts all outline tables to inline tables." ]
Please provide a description of the function:def run_command(cmd, *args, **kwargs): from pipenv.vendor import delegator from ._compat import decode_for_output from .cmdparse import Script catch_exceptions = kwargs.pop("catch_exceptions", True) if isinstance(cmd, (six.string_types, list, tuple)): cmd = Script.parse(cmd) if not isinstance(cmd, Script): raise TypeError("Command input must be a string, list or tuple") if "env" not in kwargs: kwargs["env"] = os.environ.copy() kwargs["env"]["PYTHONIOENCODING"] = "UTF-8" try: cmd_string = cmd.cmdify() except TypeError: click_echo("Error turning command into string: {0}".format(cmd), err=True) sys.exit(1) if environments.is_verbose(): click_echo("Running command: $ {0}".format(cmd_string, err=True)) c = delegator.run(cmd_string, *args, **kwargs) return_code = c.return_code if environments.is_verbose(): click_echo("Command output: {0}".format( crayons.blue(decode_for_output(c.out)) ), err=True) if not c.ok and catch_exceptions: raise PipenvCmdError(cmd_string, c.out, c.err, return_code) return c
[ "\n Take an input command and run it, handling exceptions and error codes and returning\n its stdout and stderr.\n\n :param cmd: The list of command and arguments.\n :type cmd: list\n :returns: A 2-tuple of the output and error from the command\n :rtype: Tuple[str, str]\n :raises: exceptions.PipenvCmdError\n " ]
Please provide a description of the function:def parse_python_version(output): version_line = output.split("\n", 1)[0] version_pattern = re.compile( r, re.VERBOSE, ) match = version_pattern.match(version_line) if not match: return None return match.groupdict(default="0")
[ "Parse a Python version output returned by `python --version`.\n\n Return a dict with three keys: major, minor, and micro. Each value is a\n string containing a version part.\n\n Note: The micro part would be `'0'` if it's missing from the input string.\n ", "\n ^ # Beginning of line.\n Python # Literally \"Python\".\n \\s # Space.\n (?P<major>\\d+) # Major = one or more digits.\n \\. # Dot.\n (?P<minor>\\d+) # Minor = one or more digits.\n (?: # Unnamed group for dot-micro.\n \\. # Dot.\n (?P<micro>\\d+) # Micro = one or more digit.\n )? # Micro is optional because pypa/pipenv#1893.\n .* # Trailing garbage.\n $ # End of line.\n " ]
Please provide a description of the function:def escape_grouped_arguments(s): if s is None: return None # Additional escaping for windows paths if os.name == "nt": s = "{}".format(s.replace("\\", "\\\\")) return '"' + s.replace("'", "'\\''") + '"'
[ "Prepares a string for the shell (on Windows too!)\n\n Only for use on grouped arguments (passed as a string to Popen)\n " ]
Please provide a description of the function:def venv_resolve_deps( deps, which, project, pre=False, clear=False, allow_global=False, pypi_mirror=None, dev=False, pipfile=None, lockfile=None, keep_outdated=False ): from .vendor.vistir.misc import fs_str from .vendor.vistir.compat import Path, JSONDecodeError, NamedTemporaryFile from .vendor.vistir.path import create_tracked_tempdir from . import resolver from ._compat import decode_for_output import json results = [] pipfile_section = "dev-packages" if dev else "packages" lockfile_section = "develop" if dev else "default" if not deps: if not project.pipfile_exists: return None deps = project.parsed_pipfile.get(pipfile_section, {}) if not deps: return None if not pipfile: pipfile = getattr(project, pipfile_section, {}) if not lockfile: lockfile = project._lockfile req_dir = create_tracked_tempdir(prefix="pipenv", suffix="requirements") cmd = [ which("python", allow_global=allow_global), Path(resolver.__file__.rstrip("co")).as_posix() ] if pre: cmd.append("--pre") if clear: cmd.append("--clear") if allow_global: cmd.append("--system") if dev: cmd.append("--dev") target_file = NamedTemporaryFile(prefix="resolver", suffix=".json", delete=False) target_file.close() cmd.extend(["--write", make_posix(target_file.name)]) with temp_environ(): os.environ.update({fs_str(k): fs_str(val) for k, val in os.environ.items()}) if pypi_mirror: os.environ["PIPENV_PYPI_MIRROR"] = str(pypi_mirror) os.environ["PIPENV_VERBOSITY"] = str(environments.PIPENV_VERBOSITY) os.environ["PIPENV_REQ_DIR"] = fs_str(req_dir) os.environ["PIP_NO_INPUT"] = fs_str("1") os.environ["PIPENV_SITE_DIR"] = get_pipenv_sitedir() if keep_outdated: os.environ["PIPENV_KEEP_OUTDATED"] = fs_str("1") with create_spinner(text=decode_for_output("Locking...")) as sp: # This conversion is somewhat slow on local and file-type requirements since # we now download those requirements / make temporary folders to perform # dependency resolution on them, so we are including this step inside the # spinner context manager for the UX improvement sp.write(decode_for_output("Building requirements...")) deps = convert_deps_to_pip( deps, project, r=False, include_index=True ) constraints = set(deps) os.environ["PIPENV_PACKAGES"] = str("\n".join(constraints)) sp.write(decode_for_output("Resolving dependencies...")) c = resolve(cmd, sp) results = c.out.strip() sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!")) try: with open(target_file.name, "r") as fh: results = json.load(fh) except (IndexError, JSONDecodeError): click_echo(c.out.strip(), err=True) click_echo(c.err.strip(), err=True) if os.path.exists(target_file.name): os.unlink(target_file.name) raise RuntimeError("There was a problem with locking.") if os.path.exists(target_file.name): os.unlink(target_file.name) if environments.is_verbose(): click_echo(results, err=True) if lockfile_section not in lockfile: lockfile[lockfile_section] = {} prepare_lockfile(results, pipfile, lockfile[lockfile_section])
[ "\n Resolve dependencies for a pipenv project, acts as a portal to the target environment.\n\n Regardless of whether a virtual environment is present or not, this will spawn\n a subproces which is isolated to the target environment and which will perform\n dependency resolution. This function reads the output of that call and mutates\n the provided lockfile accordingly, returning nothing.\n\n :param List[:class:`~requirementslib.Requirement`] deps: A list of dependencies to resolve.\n :param Callable which: [description]\n :param project: The pipenv Project instance to use during resolution\n :param Optional[bool] pre: Whether to resolve pre-release candidates, defaults to False\n :param Optional[bool] clear: Whether to clear the cache during resolution, defaults to False\n :param Optional[bool] allow_global: Whether to use *sys.executable* as the python binary, defaults to False\n :param Optional[str] pypi_mirror: A URL to substitute any time *pypi.org* is encountered, defaults to None\n :param Optional[bool] dev: Whether to target *dev-packages* or not, defaults to False\n :param pipfile: A Pipfile section to operate on, defaults to None\n :type pipfile: Optional[Dict[str, Union[str, Dict[str, bool, List[str]]]]]\n :param Dict[str, Any] lockfile: A project lockfile to mutate, defaults to None\n :param bool keep_outdated: Whether to retain outdated dependencies and resolve with them in mind, defaults to False\n :raises RuntimeError: Raised on resolution failure\n :return: Nothing\n :rtype: None\n " ]
Please provide a description of the function:def resolve_deps( deps, which, project, sources=None, python=False, clear=False, pre=False, allow_global=False, req_dir=None ): index_lookup = {} markers_lookup = {} python_path = which("python", allow_global=allow_global) if not os.environ.get("PIP_SRC"): os.environ["PIP_SRC"] = project.virtualenv_src_location backup_python_path = sys.executable results = [] resolver = None if not deps: return results, resolver # First (proper) attempt: req_dir = req_dir if req_dir else os.environ.get("req_dir", None) if not req_dir: from .vendor.vistir.path import create_tracked_tempdir req_dir = create_tracked_tempdir(prefix="pipenv-", suffix="-requirements") with HackedPythonVersion(python_version=python, python_path=python_path): try: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( deps, index_lookup, markers_lookup, project, sources, clear, pre, req_dir=req_dir, ) except RuntimeError: # Don't exit here, like usual. results = None # Second (last-resort) attempt: if results is None: with HackedPythonVersion( python_version=".".join([str(s) for s in sys.version_info[:3]]), python_path=backup_python_path, ): try: # Attempt to resolve again, with different Python version information, # particularly for particularly particular packages. results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( deps, index_lookup, markers_lookup, project, sources, clear, pre, req_dir=req_dir, ) except RuntimeError: sys.exit(1) return results, resolver
[ "Given a list of dependencies, return a resolved list of dependencies,\n using pip-tools -- and their hashes, using the warehouse API / pip.\n " ]
Please provide a description of the function:def convert_deps_to_pip(deps, project=None, r=True, include_index=True): from .vendor.requirementslib.models.requirements import Requirement dependencies = [] for dep_name, dep in deps.items(): if project: project.clear_pipfile_cache() indexes = getattr(project, "pipfile_sources", []) if project is not None else [] new_dep = Requirement.from_pipfile(dep_name, dep) if new_dep.index: include_index = True req = new_dep.as_line(sources=indexes if include_index else None).strip() dependencies.append(req) if not r: return dependencies # Write requirements.txt to tmp directory. from .vendor.vistir.path import create_tracked_tempfile f = create_tracked_tempfile(suffix="-requirements.txt", delete=False) f.write("\n".join(dependencies).encode("utf-8")) f.close() return f.name
[ "\"Converts a Pipfile-formatted dependency to a pip-formatted one." ]
Please provide a description of the function:def is_required_version(version, specified_version): # Certain packages may be defined with multiple values. if isinstance(specified_version, dict): specified_version = specified_version.get("version", "") if specified_version.startswith("=="): return version.strip() == specified_version.split("==")[1].strip() return True
[ "Check to see if there's a hard requirement for version\n number provided in the Pipfile.\n " ]
Please provide a description of the function:def is_installable_file(path): from .vendor.pip_shims.shims import is_installable_dir, is_archive_file from .patched.notpip._internal.utils.packaging import specifiers from ._compat import Path if hasattr(path, "keys") and any( key for key in path.keys() if key in ["file", "path"] ): path = urlparse(path["file"]).path if "file" in path else path["path"] if not isinstance(path, six.string_types) or path == "*": return False # If the string starts with a valid specifier operator, test if it is a valid # specifier set before making a path object (to avoid breaking windows) if any(path.startswith(spec) for spec in "!=<>~"): try: specifiers.SpecifierSet(path) # If this is not a valid specifier, just move on and try it as a path except specifiers.InvalidSpecifier: pass else: return False if not os.path.exists(os.path.abspath(path)): return False lookup_path = Path(path) absolute_path = "{0}".format(lookup_path.absolute()) if lookup_path.is_dir() and is_installable_dir(absolute_path): return True elif lookup_path.is_file() and is_archive_file(absolute_path): return True return False
[ "Determine if a path can potentially be installed" ]
Please provide a description of the function:def is_file(package): if hasattr(package, "keys"): return any(key for key in package.keys() if key in ["file", "path"]) if os.path.exists(str(package)): return True for start in SCHEME_LIST: if str(package).startswith(start): return True return False
[ "Determine if a package name is for a File dependency." ]
Please provide a description of the function:def pep423_name(name): name = name.lower() if any(i not in name for i in (VCS_LIST + SCHEME_LIST)): return name.replace("_", "-") else: return name
[ "Normalize package name to PEP 423 style standard." ]
Please provide a description of the function:def proper_case(package_name): # Hit the simple API. r = _get_requests_session().get( "https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True ) if not r.ok: raise IOError( "Unable to find package {0} in PyPI repository.".format(package_name) ) r = parse.parse("https://pypi.org/pypi/{name}/json", r.url) good_name = r["name"] return good_name
[ "Properly case project name from pypi.org." ]
Please provide a description of the function:def find_windows_executable(bin_path, exe_name): requested_path = get_windows_path(bin_path, exe_name) if os.path.isfile(requested_path): return requested_path try: pathext = os.environ["PATHEXT"] except KeyError: pass else: for ext in pathext.split(os.pathsep): path = get_windows_path(bin_path, exe_name + ext.strip().lower()) if os.path.isfile(path): return path return find_executable(exe_name)
[ "Given an executable name, search the given location for an executable" ]
Please provide a description of the function:def get_canonical_names(packages): from .vendor.packaging.utils import canonicalize_name if not isinstance(packages, Sequence): if not isinstance(packages, six.string_types): return packages packages = [packages] return set([canonicalize_name(pkg) for pkg in packages if pkg])
[ "Canonicalize a list of packages and return a set of canonical names" ]
Please provide a description of the function:def find_requirements(max_depth=3): i = 0 for c, d, f in walk_up(os.getcwd()): i += 1 if i < max_depth: if "requirements.txt": r = os.path.join(c, "requirements.txt") if os.path.isfile(r): return r raise RuntimeError("No requirements.txt found!")
[ "Returns the path of a Pipfile in parent directories." ]
Please provide a description of the function:def temp_environ(): environ = dict(os.environ) try: yield finally: os.environ.clear() os.environ.update(environ)
[ "Allow the ability to set os.environ temporarily" ]
Please provide a description of the function:def temp_path(): path = [p for p in sys.path] try: yield finally: sys.path = [p for p in path]
[ "Allow the ability to set os.environ temporarily" ]
Please provide a description of the function:def is_valid_url(url): pieces = urlparse(url) return all([pieces.scheme, pieces.netloc])
[ "Checks if a given string is an url" ]
Please provide a description of the function:def download_file(url, filename): r = _get_requests_session().get(url, stream=True) if not r.ok: raise IOError("Unable to download file") with open(filename, "wb") as f: f.write(r.content)
[ "Downloads file from url to a path with filename" ]
Please provide a description of the function:def normalize_drive(path): if os.name != "nt" or not isinstance(path, six.string_types): return path drive, tail = os.path.splitdrive(path) # Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts. if drive.islower() and len(drive) == 2 and drive[1] == ":": return "{}{}".format(drive.upper(), tail) return path
[ "Normalize drive in path so they stay consistent.\n\n This currently only affects local drives on Windows, which can be\n identified with either upper or lower cased drive names. The case is\n always converted to uppercase because it seems to be preferred.\n\n See: <https://github.com/pypa/pipenv/issues/1218>\n " ]
Please provide a description of the function:def is_readonly_path(fn): if os.path.exists(fn): return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access(fn, os.W_OK) return False
[ "Check if a provided path exists and is readonly.\n\n Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`\n " ]
Please provide a description of the function:def handle_remove_readonly(func, path, exc): # Check for read-only attribute default_warning_message = ( "Unable to remove file due to permissions restriction: {!r}" ) # split the initial exception out into its type, exception, and traceback exc_type, exc_exception, exc_tb = exc if is_readonly_path(path): # Apply write permission and call original function set_write_bit(path) try: func(path) except (OSError, IOError) as e: if e.errno in [errno.EACCES, errno.EPERM]: warnings.warn(default_warning_message.format(path), ResourceWarning) return if exc_exception.errno in [errno.EACCES, errno.EPERM]: warnings.warn(default_warning_message.format(path), ResourceWarning) return raise exc
[ "Error handler for shutil.rmtree.\n\n Windows source repo folders are read-only by default, so this error handler\n attempts to set them as writeable and then proceed with deletion." ]
Please provide a description of the function:def safe_expandvars(value): if isinstance(value, six.string_types): return os.path.expandvars(value) return value
[ "Call os.path.expandvars if value is a string, otherwise do nothing.\n " ]
Please provide a description of the function:def translate_markers(pipfile_entry): if not isinstance(pipfile_entry, Mapping): raise TypeError("Entry is not a pipfile formatted mapping.") from .vendor.distlib.markers import DEFAULT_CONTEXT as marker_context from .vendor.packaging.markers import Marker from .vendor.vistir.misc import dedup allowed_marker_keys = ["markers"] + [k for k in marker_context.keys()] provided_keys = list(pipfile_entry.keys()) if hasattr(pipfile_entry, "keys") else [] pipfile_markers = [k for k in provided_keys if k in allowed_marker_keys] new_pipfile = dict(pipfile_entry).copy() marker_set = set() if "markers" in new_pipfile: marker = str(Marker(new_pipfile.pop("markers"))) if 'extra' not in marker: marker_set.add(marker) for m in pipfile_markers: entry = "{0}".format(pipfile_entry[m]) if m != "markers": marker_set.add(str(Marker("{0}{1}".format(m, entry)))) new_pipfile.pop(m) if marker_set: new_pipfile["markers"] = str(Marker(" or ".join( "{0}".format(s) if " and " in s else s for s in sorted(dedup(marker_set)) ))).replace('"', "'") return new_pipfile
[ "Take a pipfile entry and normalize its markers\n\n Provide a pipfile entry which may have 'markers' as a key or it may have\n any valid key from `packaging.markers.marker_context.keys()` and standardize\n the format into {'markers': 'key == \"some_value\"'}.\n\n :param pipfile_entry: A dictionariy of keys and values representing a pipfile entry\n :type pipfile_entry: dict\n :returns: A normalized dictionary with cleaned marker entries\n " ]
Please provide a description of the function:def is_virtual_environment(path): if not path.is_dir(): return False for bindir_name in ('bin', 'Scripts'): for python in path.joinpath(bindir_name).glob('python*'): try: exeness = python.is_file() and os.access(str(python), os.X_OK) except OSError: exeness = False if exeness: return True return False
[ "Check if a given path is a virtual environment's root.\n\n This is done by checking if the directory contains a Python executable in\n its bin/Scripts directory. Not technically correct, but good enough for\n general usage.\n " ]