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 candida... | [
"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_inst... |
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(
... | [
"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 ... |
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):
... | [
"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 ... |
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(ire... | [
"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 ... | [
"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 ever... | [
"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 No... |
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.Req... | [
"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 :r... |
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}
]
_ensur... | [
"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:... |
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 = [
{"... | [
"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`... |
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:
... | [
"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:`~pi... |
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... |
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... |
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)), nam... | [
"\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'],... |
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_pinn... | [
"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... |
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)
... | [
"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 ... | [
"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 exposin... |
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... | [
"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
... | [
"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 ... | [
"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(ENCODIN... | [
"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()
... | [
"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',
... | [
"\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 mal... | [
"\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 = ... | [
"\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_disp... | [
"\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... | [
"\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(e... | [
"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 s... | [
"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... | [
"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.ends... | [
"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 fil... |
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[... | [
"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]
bre... | [
"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.isd... | [
"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.isfi... | [
"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
dis... | [
"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.in... | [
"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 u... | [
"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'kura@kura.io')\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'kura@kura.io')\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'],
mo... | [
"\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 \... |
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... |
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')
... | [
"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... | [] |
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... | [] |
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 sigwinc... | [] |
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.regist... | [] |
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.
#impo... | [
"\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', '... | [
"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 t... |
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... | [
"\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_t... | [
"\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... | [
"\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:
... | [
"\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,
s... | [
"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 ... |
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
... | [
"\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.repl... | [
"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_PY... | [] |
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("'cryptogr... | [
"\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):]
... | [
"\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 al... |
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 wo... | [
"\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_cha... | [
"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... | [
"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.PIP... | [
"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):
... | [
"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)... | [
"\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.Pi... |
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... | [
"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 ... |
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 .ve... | [
"\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... |
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)... | [
"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()
... | [
"\"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("=="):
... | [
"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 pa... | [
"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):
... | [
"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... | [
"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:
... | [
"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([cano... | [
"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):
... | [
"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) ==... | [
"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... |
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
... | [
"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 ... | [
"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 k... |
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(py... | [
"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 "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.