text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Generates an EmptyTag token
<END_TASK>
<USER_TASK:>
Description:
def emptyTag(self, namespace, name, attrs, hasChildren=False):
"""Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to yield a SerializationError because
this tag shouldn't have children
:returns: EmptyTag token
""" |
yield {"type": "EmptyTag", "name": name,
"namespace": namespace,
"data": attrs}
if hasChildren:
yield self.error("Void element has children") |
<SYSTEM_TASK:>
Generates SpaceCharacters and Characters tokens
<END_TASK>
<USER_TASK:>
Description:
def text(self, data):
"""Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantiates
>>> walker = TreeWalker([])
>>> list(walker.text(''))
[]
>>> list(walker.text(' '))
[{u'data': ' ', u'type': u'SpaceCharacters'}]
>>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE
[{u'data': ' ', u'type': u'SpaceCharacters'},
{u'data': u'abc', u'type': u'Characters'},
{u'data': u' ', u'type': u'SpaceCharacters'}]
:arg data: the text data
:returns: one or more ``SpaceCharacters`` and ``Characters`` tokens
""" |
data = data
middle = data.lstrip(spaceCharacters)
left = data[:len(data) - len(middle)]
if left:
yield {"type": "SpaceCharacters", "data": left}
data = middle
middle = data.rstrip(spaceCharacters)
right = data[len(middle):]
if middle:
yield {"type": "Characters", "data": middle}
if right:
yield {"type": "SpaceCharacters", "data": right} |
<SYSTEM_TASK:>
Returns the string to activate a virtualenv.
<END_TASK>
<USER_TASK:>
Description:
def _get_activate_script(cmd, venv):
"""Returns the string to activate a virtualenv.
This is POSIX-only at the moment since the compat (pexpect-based) shell
does not work elsewhere anyway.
""" |
# Suffix and source command for other shells.
# Support for fish shell.
if "fish" in cmd:
suffix = ".fish"
command = "source"
# Support for csh shell.
elif "csh" in cmd:
suffix = ".csh"
command = "source"
else:
suffix = ""
command = "."
# Escape any spaces located within the virtualenv path to allow
# for proper activation.
venv_location = str(venv).replace(" ", r"\ ")
# The leading space can make history cleaner in some shells.
return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command) |
<SYSTEM_TASK:>
Build and return a filename from the various components.
<END_TASK>
<USER_TASK:>
Description:
def filename(self):
"""
Build and return a filename from the various components.
""" |
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arch)
# replace - with _ as a local version separator
version = self.version.replace('-', '_')
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
pyver, abi, arch) |
<SYSTEM_TASK:>
Adds a given path to the PATH.
<END_TASK>
<USER_TASK:>
Description:
def add_to_path(p):
"""Adds a given path to the PATH.""" |
if p not in os.environ["PATH"]:
os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"]) |
<SYSTEM_TASK:>
Removes the virtualenv directory from the system.
<END_TASK>
<USER_TASK:>
Description:
def cleanup_virtualenv(bare=True):
"""Removes the virtualenv directory from the system.""" |
if not bare:
click.echo(crayons.red("Environment creation aborted."))
try:
# Delete the virtualenv.
vistir.path.rmtree(project.virtualenv_location)
except OSError as e:
click.echo(
"{0} An error occurred while removing {1}!".format(
crayons.red("Error: ", bold=True),
crayons.green(project.virtualenv_location),
),
err=True,
)
click.echo(crayons.blue(e), err=True) |
<SYSTEM_TASK:>
Find a Python installation from a given line.
<END_TASK>
<USER_TASK:>
Description:
def find_a_system_python(line):
"""Find a Python installation from a given line.
This tries to parse the line in various of ways:
* Looks like an absolute path? Use it directly.
* Looks like a py.exe call? Use py.exe to get the executable.
* Starts with "py" something? Looks like a python command. Try to find it
in PATH, and use it directly.
* Search for "python" and "pythonX.Y" executables in PATH to find a match.
* Nothing fits, return None.
""" |
from .vendor.pythonfinder import Finder
finder = Finder(system=False, global_search=True)
if not line:
return next(iter(finder.find_all_python_versions()), None)
# Use the windows finder executable
if (line.startswith("py ") or line.startswith("py.exe ")) and os.name == "nt":
line = line.split(" ", 1)[1].lstrip("-")
python_entry = find_python(finder, line)
return python_entry |
<SYSTEM_TASK:>
Creates a virtualenv, if one doesn't exist.
<END_TASK>
<USER_TASK:>
Description:
def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror=None):
"""Creates a virtualenv, if one doesn't exist.""" |
from .environments import PIPENV_USE_SYSTEM
def abort():
sys.exit(1)
global USING_DEFAULT_PYTHON
if not project.virtualenv_exists:
try:
# Ensure environment variables are set properly.
ensure_environment()
# Ensure Python is available.
python = ensure_python(three=three, python=python)
if python is not None and not isinstance(python, six.string_types):
python = python.path.as_posix()
# Create the virtualenv.
# Abort if --system (or running in a virtualenv).
if PIPENV_USE_SYSTEM:
click.echo(
crayons.red(
"You are attempting to re–create a virtualenv that "
"Pipenv did not create. Aborting."
)
)
sys.exit(1)
do_create_virtualenv(
python=python, site_packages=site_packages, pypi_mirror=pypi_mirror
)
except KeyboardInterrupt:
# If interrupted, cleanup the virtualenv.
cleanup_virtualenv(bare=False)
sys.exit(1)
# If --three, --two, or --python were passed…
elif (python) or (three is not None) or (site_packages is not False):
USING_DEFAULT_PYTHON = False
# Ensure python is installed before deleting existing virtual env
python = ensure_python(three=three, python=python)
if python is not None and not isinstance(python, six.string_types):
python = python.path.as_posix()
click.echo(crayons.red("Virtualenv already exists!"), err=True)
# If VIRTUAL_ENV is set, there is a possibility that we are
# going to remove the active virtualenv that the user cares
# about, so confirm first.
if "VIRTUAL_ENV" in os.environ:
if not (
PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True)
):
abort()
click.echo(
crayons.normal(fix_utf8("Removing existing virtualenv…"), bold=True), err=True
)
# Remove the virtualenv.
cleanup_virtualenv(bare=True)
# Call this function again.
ensure_virtualenv(
three=three,
python=python,
site_packages=site_packages,
pypi_mirror=pypi_mirror,
) |
<SYSTEM_TASK:>
Ensures both Pipfile and virtualenv exist for the project.
<END_TASK>
<USER_TASK:>
Description:
def ensure_project(
three=None,
python=None,
validate=True,
system=False,
warn=True,
site_packages=False,
deploy=False,
skip_requirements=False,
pypi_mirror=None,
clear=False,
):
"""Ensures both Pipfile and virtualenv exist for the project.""" |
from .environments import PIPENV_USE_SYSTEM
# Clear the caches, if appropriate.
if clear:
print("clearing")
sys.exit(1)
# Automatically use an activated virtualenv.
if PIPENV_USE_SYSTEM:
system = True
if not project.pipfile_exists and deploy:
raise exceptions.PipfileNotFound
# Fail if working under /
if not project.name:
click.echo(
"{0}: Pipenv is not intended to work under the root directory, "
"please choose another path.".format(crayons.red("ERROR")),
err=True
)
sys.exit(1)
# Skip virtualenv creation when --system was used.
if not system:
ensure_virtualenv(
three=three,
python=python,
site_packages=site_packages,
pypi_mirror=pypi_mirror,
)
if warn:
# Warn users if they are using the wrong version of Python.
if project.required_python_version:
path_to_python = which("python") or which("py")
if path_to_python and project.required_python_version not in (
python_version(path_to_python) or ""
):
click.echo(
"{0}: Your Pipfile requires {1} {2}, "
"but you are using {3} ({4}).".format(
crayons.red("Warning", bold=True),
crayons.normal("python_version", bold=True),
crayons.blue(project.required_python_version),
crayons.blue(python_version(path_to_python)),
crayons.green(shorten_path(path_to_python)),
),
err=True,
)
click.echo(
" {0} and rebuilding the virtual environment "
"may resolve the issue.".format(crayons.green("$ pipenv --rm")),
err=True,
)
if not deploy:
click.echo(
" {0} will surely fail."
"".format(crayons.red("$ pipenv check")),
err=True,
)
else:
raise exceptions.DeployException
# Ensure the Pipfile exists.
ensure_pipfile(
validate=validate, skip_requirements=skip_requirements, system=system
) |
<SYSTEM_TASK:>
Returns a visually shorter representation of a given system path.
<END_TASK>
<USER_TASK:>
Description:
def shorten_path(location, bold=False):
"""Returns a visually shorter representation of a given system path.""" |
original = location
short = os.sep.join(
[s[0] if len(s) > (len("2long4")) else s for s in location.split(os.sep)]
)
short = short.split(os.sep)
short[-1] = original.split(os.sep)[-1]
if bold:
short[-1] = str(crayons.normal(short[-1], bold=True))
return os.sep.join(short) |
<SYSTEM_TASK:>
Executes the where functionality.
<END_TASK>
<USER_TASK:>
Description:
def do_where(virtualenv=False, bare=True):
"""Executes the where functionality.""" |
if not virtualenv:
if not project.pipfile_exists:
click.echo(
"No Pipfile present at project home. Consider running "
"{0} first to automatically generate a Pipfile for you."
"".format(crayons.green("`pipenv install`")),
err=True,
)
return
location = project.pipfile_location
# Shorten the virtual display of the path to the virtualenv.
if not bare:
location = shorten_path(location)
click.echo(
"Pipfile found at {0}.\n Considering this to be the project home."
"".format(crayons.green(location)),
err=True,
)
else:
click.echo(project.project_directory)
else:
location = project.virtualenv_location
if not bare:
click.echo(
"Virtualenv location: {0}".format(crayons.green(location)), err=True
)
else:
click.echo(location) |
<SYSTEM_TASK:>
A fallback implementation of the `which` utility command that relies exclusively on
<END_TASK>
<USER_TASK:>
Description:
def fallback_which(command, location=None, allow_global=False, system=False):
"""
A fallback implementation of the `which` utility command that relies exclusively on
searching the path for commands.
:param str command: The command to search for, optional
:param str location: The search location to prioritize (prepend to path), defaults to None
:param bool allow_global: Whether to search the global path, defaults to False
:param bool system: Whether to use the system python instead of pipenv's python, defaults to False
:raises ValueError: Raised if no command is provided
:raises TypeError: Raised if the command provided is not a string
:return: A path to the discovered command location
:rtype: str
""" |
from .vendor.pythonfinder import Finder
if not command:
raise ValueError("fallback_which: Must provide a command to search for...")
if not isinstance(command, six.string_types):
raise TypeError("Provided command must be a string, received {0!r}".format(command))
global_search = system or allow_global
if location is None:
global_search = True
finder = Finder(system=False, global_search=global_search, path=location)
if is_python_command(command):
result = find_python(finder, command)
if result:
return result
result = finder.which(command)
if result:
return result.path.as_posix()
return "" |
<SYSTEM_TASK:>
Returns the location of virtualenv-installed pip.
<END_TASK>
<USER_TASK:>
Description:
def which_pip(allow_global=False):
"""Returns the location of virtualenv-installed pip.""" |
location = None
if "VIRTUAL_ENV" in os.environ:
location = os.environ["VIRTUAL_ENV"]
if allow_global:
if location:
pip = which("pip", location=location)
if pip:
return pip
for p in ("pip", "pip3", "pip2"):
where = system_which(p)
if where:
return where
pip = which("pip")
if not pip:
pip = fallback_which("pip", allow_global=allow_global, location=location)
return pip |
<SYSTEM_TASK:>
Emulates the system's which. Returns None if not found.
<END_TASK>
<USER_TASK:>
Description:
def system_which(command, mult=False):
"""Emulates the system's which. Returns None if not found.""" |
_which = "which -a" if not os.name == "nt" else "where"
os.environ = {
vistir.compat.fs_str(k): vistir.compat.fs_str(val)
for k, val in os.environ.items()
}
result = None
try:
c = delegator.run("{0} {1}".format(_which, command))
try:
# Which Not found…
if c.return_code == 127:
click.echo(
"{}: the {} system utility is required for Pipenv to find Python installations properly."
"\n Please install it.".format(
crayons.red("Warning", bold=True), crayons.red(_which)
),
err=True,
)
assert c.return_code == 0
except AssertionError:
result = fallback_which(command, allow_global=True)
except TypeError:
if not result:
result = fallback_which(command, allow_global=True)
else:
if not result:
result = next(iter([c.out, c.err]), "").split("\n")
result = next(iter(result)) if not mult else result
return result
if not result:
result = fallback_which(command, allow_global=True)
result = [result] if mult else result
return result |
<SYSTEM_TASK:>
Built-in venv doesn't have activate_this.py, but doesn't need it anyway.
<END_TASK>
<USER_TASK:>
Description:
def _inline_activate_venv():
"""Built-in venv doesn't have activate_this.py, but doesn't need it anyway.
As long as we find the correct executable, built-in venv sets up the
environment automatically.
See: https://bugs.python.org/issue21496#msg218455
""" |
components = []
for name in ("bin", "Scripts"):
bindir = os.path.join(project.virtualenv_location, name)
if os.path.exists(bindir):
components.append(bindir)
if "PATH" in os.environ:
components.append(os.environ["PATH"])
os.environ["PATH"] = os.pathsep.join(components) |
<SYSTEM_TASK:>
Attempt to run command either pulling from project or interpreting as executable.
<END_TASK>
<USER_TASK:>
Description:
def do_run(command, args, three=None, python=False, pypi_mirror=None):
"""Attempt to run command either pulling from project or interpreting as executable.
Args are appended to the command in [scripts] section of project if found.
""" |
from .cmdparse import ScriptEmptyError
# Ensure that virtualenv is available.
ensure_project(
three=three, python=python, validate=False, pypi_mirror=pypi_mirror,
)
load_dot_env()
previous_pip_shims_module = os.environ.pop("PIP_SHIMS_BASE_MODULE", None)
# Activate virtualenv under the current interpreter's environment
inline_activate_virtual_environment()
# Set an environment variable, so we know we're in the environment.
# Only set PIPENV_ACTIVE after finishing reading virtualenv_location
# such as in inline_activate_virtual_environment
# otherwise its value will be changed
previous_pipenv_active_value = os.environ.get("PIPENV_ACTIVE")
os.environ["PIPENV_ACTIVE"] = vistir.misc.fs_str("1")
try:
script = project.build_script(command, args)
cmd_string = ' '.join([script.command] + script.args)
if environments.is_verbose():
click.echo(crayons.normal("$ {0}".format(cmd_string)), err=True)
except ScriptEmptyError:
click.echo("Can't run script {0!r}-it's empty?", err=True)
run_args = [script]
run_kwargs = {}
if os.name == "nt":
run_fn = do_run_nt
else:
run_fn = do_run_posix
run_kwargs = {"command": command}
try:
run_fn(*run_args, **run_kwargs)
finally:
os.environ.pop("PIPENV_ACTIVE", None)
if previous_pipenv_active_value is not None:
os.environ["PIPENV_ACTIVE"] = previous_pipenv_active_value
if previous_pip_shims_module is not None:
os.environ["PIP_SHIMS_BASE_MODULE"] = previous_pip_shims_module |
<SYSTEM_TASK:>
Iterate through processes, yielding process ID and properties of each.
<END_TASK>
<USER_TASK:>
Description:
def _iter_process():
"""Iterate through processes, yielding process ID and properties of each.
Example usage::
>>> for pid, info in _iter_process():
... print(pid, '->', info)
1509 -> {'parent_pid': 1201, 'executable': 'python.exe'}
""" |
# TODO: Process32{First,Next} does not return full executable path, only
# the name. To get the full path, Module32{First,Next} is needed, but that
# does not contain parent process information. We probably need to call
# BOTH to build the correct process tree.
h_process = windll.kernel32.CreateToolhelp32Snapshot(
2, # dwFlags=TH32CS_SNAPPROCESS (include all processes).
0, # th32ProcessID=0 (the current process).
)
if h_process == INVALID_HANDLE_VALUE:
raise WinError()
pe = PROCESSENTRY32()
pe.dwSize = sizeof(PROCESSENTRY32)
success = windll.kernel32.Process32First(h_process, byref(pe))
while True:
if not success:
errcode = windll.kernel32.GetLastError()
if errcode == ERROR_NO_MORE_FILES:
# No more processes to iterate through, we're done here.
return
elif errcode == ERROR_INSUFFICIENT_BUFFER:
# This is likely because the file path is longer than the
# Windows limit. Just ignore it, it's likely not what we're
# looking for. We can fix this when it actually matters. (#8)
continue
raise WinError()
# The executable name would be encoded with the current code page if
# we're in ANSI mode (usually). Try to decode it into str/unicode,
# replacing invalid characters to be safe (not thoeratically necessary,
# I think). Note that we need to use 'mbcs' instead of encoding
# settings from sys because this is from the Windows API, not Python
# internals (which those settings reflect). (pypa/pipenv#3382)
executable = pe.szExeFile
if isinstance(executable, bytes):
executable = executable.decode('mbcs', 'replace')
info = {'executable': executable}
if pe.th32ParentProcessID:
info['parent_pid'] = pe.th32ParentProcessID
yield pe.th32ProcessID, info
success = windll.kernel32.Process32Next(h_process, byref(pe)) |
<SYSTEM_TASK:>
Helper method to fail with an invalid value message.
<END_TASK>
<USER_TASK:>
Description:
def fail(self, message, param=None, ctx=None):
"""Helper method to fail with an invalid value message.""" |
raise BadParameter(message, ctx=ctx, param=param) |
<SYSTEM_TASK:>
Check a bytes string for a BOM to correctly detect the encoding
<END_TASK>
<USER_TASK:>
Description:
def auto_decode(data):
# type: (bytes) -> Text
"""Check a bytes string for a BOM to correctly detect the encoding
Fallback to locale.getpreferredencoding(False) like open() on Python3""" |
for bom, encoding in BOMS:
if data.startswith(bom):
return data[len(bom):].decode(encoding)
# Lets check the first two lines as in PEP263
for line in data.split(b'\n')[:2]:
if line[0:1] == b'#' and ENCODING_RE.search(line):
encoding = ENCODING_RE.search(line).groups()[0].decode('ascii')
return data.decode(encoding)
return data.decode(
locale.getpreferredencoding(False) or sys.getdefaultencoding(),
) |
<SYSTEM_TASK:>
Internal helper to get the default value of the color flag. If a
<END_TASK>
<USER_TASK:>
Description:
def resolve_color_default(color=None):
""""Internal helper to get the default value of the color flag. If a
value is passed it's returned unchanged, otherwise it's looked up from
the current context.
""" |
if color is not None:
return color
ctx = get_current_context(silent=True)
if ctx is not None:
return ctx.color |
<SYSTEM_TASK:>
Parses named file or files as toml and returns a dictionary
<END_TASK>
<USER_TASK:>
Description:
def load(f, _dict=dict, decoder=None):
"""Parses named file or files as toml and returns a dictionary
Args:
f: Path to the file to open, array of files to read into single dict
or a file descriptor
_dict: (optional) Specifies the class of the returned toml dictionary
Returns:
Parsed toml file represented as a dictionary
Raises:
TypeError -- When f is invalid type
TomlDecodeError: Error while decoding toml
IOError / FileNotFoundError -- When an array with no valid (existing)
(Python 2 / Python 3) file paths is passed
""" |
if _ispath(f):
with io.open(_getpath(f), encoding='utf-8') as ffile:
return loads(ffile.read(), _dict, decoder)
elif isinstance(f, list):
from os import path as op
from warnings import warn
if not [path for path in f if op.exists(path)]:
error_msg = "Load expects a list to contain filenames only."
error_msg += linesep
error_msg += ("The list needs to contain the path of at least one "
"existing file.")
raise FNFError(error_msg)
if decoder is None:
decoder = TomlDecoder()
d = decoder.get_empty_table()
for l in f:
if op.exists(l):
d.update(load(l, _dict, decoder))
else:
warn("Non-existent filename in list with at least one valid "
"filename")
return d
else:
try:
return loads(f.read(), _dict, decoder)
except AttributeError:
raise TypeError("You can only load a file descriptor, filename or "
"list") |
<SYSTEM_TASK:>
Concatenation that escapes if necessary and converts to unicode.
<END_TASK>
<USER_TASK:>
Description:
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode.""" |
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
return Markup(u'').join(chain(buf, iterator))
return concat(buf) |
<SYSTEM_TASK:>
Given a logger object this returns a new undefined class that will
<END_TASK>
<USER_TASK:>
Description:
def make_logging_undefined(logger=None, base=None):
"""Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
.. versionadded:: 2.8
:param logger: the logger to use. If not provided, a default logger
is created.
:param base: the base class to add logging functionality to. This
defaults to :class:`Undefined`.
""" |
if logger is None:
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler(sys.stderr))
if base is None:
base = Undefined
def _log_message(undef):
if undef._undefined_hint is None:
if undef._undefined_obj is missing:
hint = '%s is undefined' % undef._undefined_name
elif not isinstance(undef._undefined_name, string_types):
hint = '%s has no element %s' % (
object_type_repr(undef._undefined_obj),
undef._undefined_name)
else:
hint = '%s has no attribute %s' % (
object_type_repr(undef._undefined_obj),
undef._undefined_name)
else:
hint = undef._undefined_hint
logger.warning('Template variable warning: %s', hint)
class LoggingUndefined(base):
def _fail_with_undefined_error(self, *args, **kwargs):
try:
return base._fail_with_undefined_error(self, *args, **kwargs)
except self._undefined_exception as e:
logger.error('Template variable error: %s', str(e))
raise e
def __str__(self):
rv = base.__str__(self)
_log_message(self)
return rv
def __iter__(self):
rv = base.__iter__(self)
_log_message(self)
return rv
if PY2:
def __nonzero__(self):
rv = base.__nonzero__(self)
_log_message(self)
return rv
def __unicode__(self):
rv = base.__unicode__(self)
_log_message(self)
return rv
else:
def __bool__(self):
rv = base.__bool__(self)
_log_message(self)
return rv
return LoggingUndefined |
<SYSTEM_TASK:>
Render a parent block.
<END_TASK>
<USER_TASK:>
Description:
def super(self, name, current):
"""Render a parent block.""" |
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index) |
<SYSTEM_TASK:>
Get a new dict with the exported variables.
<END_TASK>
<USER_TASK:>
Description:
def get_exported(self):
"""Get a new dict with the exported variables.""" |
return dict((k, self.vars[k]) for k in self.exported_vars) |
<SYSTEM_TASK:>
Return the complete context as dict including the exported
<END_TASK>
<USER_TASK:>
Description:
def get_all(self):
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
""" |
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars) |
<SYSTEM_TASK:>
Internal helper function to create a derived context. This is
<END_TASK>
<USER_TASK:>
Description:
def derived(self, locals=None):
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
""" |
context = new_context(self.environment, self.name, {},
self.get_all(), True, None, locals)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
return context |
<SYSTEM_TASK:>
Cycles among the arguments with the current loop index.
<END_TASK>
<USER_TASK:>
Description:
def cycle(self, *args):
"""Cycles among the arguments with the current loop index.""" |
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)] |
<SYSTEM_TASK:>
Checks whether the value has changed since the last call.
<END_TASK>
<USER_TASK:>
Description:
def changed(self, *value):
"""Checks whether the value has changed since the last call.""" |
if self._last_checked_value != value:
self._last_checked_value = value
return True
return False |
<SYSTEM_TASK:>
This method is being swapped out by the async implementation.
<END_TASK>
<USER_TASK:>
Description:
def _invoke(self, arguments, autoescape):
"""This method is being swapped out by the async implementation.""" |
rv = self._func(*arguments)
if autoescape:
rv = Markup(rv)
return rv |
<SYSTEM_TASK:>
Test if this address is allocated for public networks.
<END_TASK>
<USER_TASK:>
Description:
def is_global(self):
"""Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.
""" |
return (not (self.network_address in IPv4Network('100.64.0.0/10') and
self.broadcast_address in IPv4Network('100.64.0.0/10')) and
not self.is_private) |
<SYSTEM_TASK:>
Tuple of embedded teredo IPs.
<END_TASK>
<USER_TASK:>
Description:
def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
""" |
if (self._ip >> 96) != 0x20010000:
return None
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF)) |
<SYSTEM_TASK:>
Serializes the input token stream using the specified treewalker
<END_TASK>
<USER_TASK:>
Description:
def serialize(input, tree="etree", encoding=None, **serializer_opts):
"""Serializes the input token stream using the specified treewalker
:arg input: the token stream to serialize
:arg tree: the treewalker to use
:arg encoding: the encoding to use
:arg serializer_opts: any options to pass to the
:py:class:`html5lib.serializer.HTMLSerializer` that gets created
:returns: the tree serialized as a string
Example:
>>> from html5lib.html5parser import parse
>>> from html5lib.serializer import serialize
>>> token_stream = parse('<html><body><p>Hi!</p></body></html>')
>>> serialize(token_stream, omit_optional_tags=False)
'<html><head></head><body><p>Hi!</p></body></html>'
""" |
# XXX: Should we cache this?
walker = treewalkers.getTreeWalker(tree)
s = HTMLSerializer(**serializer_opts)
return s.render(walker(input), encoding) |
<SYSTEM_TASK:>
Serializes the stream from the treewalker into a string
<END_TASK>
<USER_TASK:>
Description:
def render(self, treewalker, encoding=None):
"""Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTreeWalker
>>> from html5lib.serializer import HTMLSerializer
>>> token_stream = parse('<html><body>Hi!</body></html>')
>>> walker = getTreeWalker('etree')
>>> serializer = HTMLSerializer(omit_optional_tags=False)
>>> serializer.render(walker(token_stream))
'<html><head></head><body>Hi!</body></html>'
""" |
if encoding:
return b"".join(list(self.serialize(treewalker, encoding)))
else:
return "".join(list(self.serialize(treewalker))) |
<SYSTEM_TASK:>
Resolve a revision to a new RevOptions object with the SHA1 of the
<END_TASK>
<USER_TASK:>
Description:
def resolve_revision(self, dest, url, rev_options):
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
""" |
rev = rev_options.arg_rev
sha, is_branch = self.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not rev.startswith('refs/'):
return rev_options
# If it looks like a ref, we have to fetch it explicitly.
self.run_command(
['fetch', '-q', url] + rev_options.to_args(),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = self.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options |
<SYSTEM_TASK:>
Return whether the current commit hash equals the given name.
<END_TASK>
<USER_TASK:>
Description:
def is_commit_id_equal(self, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
""" |
if not name:
# Then avoid an unnecessary subprocess call.
return False
return self.get_revision(dest) == name |
<SYSTEM_TASK:>
Return URL of the first remote encountered.
<END_TASK>
<USER_TASK:>
Description:
def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
""" |
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip() |
<SYSTEM_TASK:>
Get a value from the configuration.
<END_TASK>
<USER_TASK:>
Description:
def get_value(self, key):
# type: (str) -> Any
"""Get a value from the configuration.
""" |
try:
return self._dictionary[key]
except KeyError:
raise ConfigurationError("No such key - {}".format(key)) |
<SYSTEM_TASK:>
Modify a value in the configuration.
<END_TASK>
<USER_TASK:>
Description:
def set_value(self, key, value):
# type: (str, Any) -> None
"""Modify a value in the configuration.
""" |
self._ensure_have_load_only()
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Modify the parser and the configuration
if not parser.has_section(section):
parser.add_section(section)
parser.set(section, name, value)
self._config[self.load_only][key] = value
self._mark_as_modified(fname, parser) |
<SYSTEM_TASK:>
Unset a value in the configuration.
<END_TASK>
<USER_TASK:>
Description:
def unset_value(self, key):
# type: (str) -> None
"""Unset a value in the configuration.
""" |
self._ensure_have_load_only()
if key not in self._config[self.load_only]:
raise ConfigurationError("No such key - {}".format(key))
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Remove the key in the parser
modified_something = False
if parser.has_section(section):
# Returns whether the option was removed or not
modified_something = parser.remove_option(section, name)
if modified_something:
# name removed from parser, section may now be empty
section_iter = iter(parser.items(section))
try:
val = six.next(section_iter)
except StopIteration:
val = None
if val is None:
parser.remove_section(section)
self._mark_as_modified(fname, parser)
else:
raise ConfigurationError(
"Fatal Internal error [id=1]. Please report as a bug."
)
del self._config[self.load_only][key] |
<SYSTEM_TASK:>
A dictionary representing the loaded configuration.
<END_TASK>
<USER_TASK:>
Description:
def _dictionary(self):
# type: () -> Dict[str, Any]
"""A dictionary representing the loaded configuration.
""" |
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
retval = {}
for variant in self._override_order:
retval.update(self._config[variant])
return retval |
<SYSTEM_TASK:>
Loads configuration from configuration files
<END_TASK>
<USER_TASK:>
Description:
def _load_config_files(self):
# type: () -> None
"""Loads configuration from configuration files
""" |
config_files = dict(self._iter_config_files())
if config_files[kinds.ENV][0:1] == [os.devnull]:
logger.debug(
"Skipping loading configuration files due to "
"environment's PIP_CONFIG_FILE being os.devnull"
)
return
for variant, files in config_files.items():
for fname in files:
# If there's specific variant set in `load_only`, load only
# that variant, not the others.
if self.load_only is not None and variant != self.load_only:
logger.debug(
"Skipping file '%s' (variant: %s)", fname, variant
)
continue
parser = self._load_file(variant, fname)
# Keeping track of the parsers used
self._parsers[variant].append((fname, parser)) |
<SYSTEM_TASK:>
Loads configuration from environment variables
<END_TASK>
<USER_TASK:>
Description:
def _load_environment_vars(self):
# type: () -> None
"""Loads configuration from environment variables
""" |
self._config[kinds.ENV_VAR].update(
self._normalized_keys(":env:", self._get_environ_vars())
) |
<SYSTEM_TASK:>
Normalizes items to construct a dictionary with normalized keys.
<END_TASK>
<USER_TASK:>
Description:
def _normalized_keys(self, section, items):
# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]
"""Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
regardless of source - configuration files or environment.
""" |
normalized = {}
for name, val in items:
key = section + "." + _normalize_name(name)
normalized[key] = val
return normalized |
<SYSTEM_TASK:>
Returns a generator with all environmental vars with prefix PIP_
<END_TASK>
<USER_TASK:>
Description:
def _get_environ_vars(self):
# type: () -> Iterable[Tuple[str, str]]
"""Returns a generator with all environmental vars with prefix PIP_""" |
for key, val in os.environ.items():
should_be_yielded = (
key.startswith("PIP_") and
key[4:].lower() not in self._ignore_env_names
)
if should_be_yielded:
yield key[4:].lower(), val |
<SYSTEM_TASK:>
Yields variant and configuration files associated with it.
<END_TASK>
<USER_TASK:>
Description:
def _iter_config_files(self):
# type: () -> Iterable[Tuple[Kind, List[str]]]
"""Yields variant and configuration files associated with it.
This should be treated like items of a dictionary.
""" |
# SMELL: Move the conditions out of this function
# environment variables have the lowest priority
config_file = os.environ.get('PIP_CONFIG_FILE', None)
if config_file is not None:
yield kinds.ENV, [config_file]
else:
yield kinds.ENV, []
# at the base we have any global configuration
yield kinds.GLOBAL, list(site_config_files)
# per-user configuration next
should_load_user_config = not self.isolated and not (
config_file and os.path.exists(config_file)
)
if should_load_user_config:
# The legacy config file is overridden by the new config file
yield kinds.USER, [legacy_config_file, new_config_file]
# finally virtualenv configuration first trumping others
if running_under_virtualenv():
yield kinds.VENV, [venv_config_file] |
<SYSTEM_TASK:>
Helper to make sure the command got the right number of arguments
<END_TASK>
<USER_TASK:>
Description:
def _get_n_args(self, args, example, n):
"""Helper to make sure the command got the right number of arguments
""" |
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise PipError(msg)
if n == 1:
return args[0]
else:
return args |
<SYSTEM_TASK:>
Return a case-normalized absolute variable-expanded path.
<END_TASK>
<USER_TASK:>
Description:
def normalize_path(path):
# type: (AnyStr) -> AnyStr
"""
Return a case-normalized absolute variable-expanded path.
:param str path: The non-normalized path
:return: A normalized, expanded, case-normalized path
:rtype: str
""" |
return os.path.normpath(
os.path.normcase(
os.path.abspath(os.path.expandvars(os.path.expanduser(str(path))))
)
) |
<SYSTEM_TASK:>
Convert the supplied local path to a file uri.
<END_TASK>
<USER_TASK:>
Description:
def path_to_url(path):
# type: (str) -> Text
"""Convert the supplied local path to a file uri.
:param str path: A string pointing to or representing a local path
:return: A `file://` uri for the same location
:rtype: str
>>> path_to_url("/home/user/code/myrepo/myfile.zip")
'file:///home/user/code/myrepo/myfile.zip'
""" |
from .misc import to_text, to_bytes
if not path:
return path
path = to_bytes(path, encoding="utf-8")
normalized_path = to_text(normalize_drive(os.path.abspath(path)), encoding="utf-8")
return to_text(Path(normalized_path).as_uri(), encoding="utf-8") |
<SYSTEM_TASK:>
Convert a valid file url to a local filesystem path
<END_TASK>
<USER_TASK:>
Description:
def url_to_path(url):
# type: (str) -> ByteString
"""
Convert a valid file url to a local filesystem path
Follows logic taken from pip's equivalent function
""" |
from .misc import to_bytes
assert is_file_url(url), "Only file: urls can be converted to local paths"
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# Netlocs are UNC paths
if netloc:
netloc = "\\\\" + netloc
path = urllib_request.url2pathname(netloc + path)
return to_bytes(path, encoding="utf-8") |
<SYSTEM_TASK:>
Returns true if the given url is a file url
<END_TASK>
<USER_TASK:>
Description:
def is_file_url(url):
"""Returns true if the given url is a file url""" |
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text(url, encoding="utf-8")
return urllib_parse.urlparse(url.lower()).scheme == "file" |
<SYSTEM_TASK:>
Recursively creates the target directory and all of its parents if they do not
<END_TASK>
<USER_TASK:>
Description:
def mkdir_p(newdir, mode=0o777):
"""Recursively creates the target directory and all of its parents if they do not
already exist. Fails silently if they do.
:param str newdir: The directory path to ensure
:raises: OSError if a file is encountered along the way
""" |
# http://code.activestate.com/recipes/82465-a-friendly-mkdir/
newdir = fs_encode(newdir)
if os.path.exists(newdir):
if not os.path.isdir(newdir):
raise OSError(
"a file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
else:
head, tail = os.path.split(newdir)
# Make sure the tail doesn't point to the asame place as the head
curdir = fs_encode(".")
tail_and_head_match = (
os.path.relpath(tail, start=os.path.basename(head)) == curdir
)
if tail and not tail_and_head_match and not os.path.isdir(newdir):
target = os.path.join(head, tail)
if os.path.exists(target) and os.path.isfile(target):
raise OSError(
"A file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
os.makedirs(os.path.join(head, tail), mode) |
<SYSTEM_TASK:>
Decorator to ensure `mkdir_p` is called to the function's return value.
<END_TASK>
<USER_TASK:>
Description:
def ensure_mkdir_p(mode=0o777):
"""Decorator to ensure `mkdir_p` is called to the function's return value.
""" |
def decorator(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
path = f(*args, **kwargs)
mkdir_p(path, mode=mode)
return path
return decorated
return decorator |
<SYSTEM_TASK:>
Create a tracked temporary directory.
<END_TASK>
<USER_TASK:>
Description:
def create_tracked_tempdir(*args, **kwargs):
"""Create a tracked temporary directory.
This uses `TemporaryDirectory`, but does not remove the directory when
the return value goes out of scope, instead registers a handler to cleanup
on program exit.
The return value is the path to the created directory.
""" |
tempdir = TemporaryDirectory(*args, **kwargs)
TRACKED_TEMPORARY_DIRECTORIES.append(tempdir)
atexit.register(tempdir.cleanup)
warnings.simplefilter("ignore", ResourceWarning)
return tempdir.name |
<SYSTEM_TASK:>
Retry with backoff up to 1 second to delete files from a directory.
<END_TASK>
<USER_TASK:>
Description:
def _wait_for_files(path):
"""
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
""" |
timeout = 0.001
remaining = []
while timeout < 1.0:
remaining = []
if os.path.isdir(path):
L = os.listdir(path)
for target in L:
_remaining = _wait_for_files(target)
if _remaining:
remaining.extend(_remaining)
continue
try:
os.unlink(path)
except FileNotFoundError as e:
if e.errno == errno.ENOENT:
return
except (OSError, IOError, PermissionError):
time.sleep(timeout)
timeout *= 2
remaining.append(path)
else:
return
return remaining |
<SYSTEM_TASK:>
Checks to see if a pathlib `Path` object is a unc path or not
<END_TASK>
<USER_TASK:>
Description:
def check_for_unc_path(path):
""" Checks to see if a pathlib `Path` object is a unc path or not""" |
if (
os.name == "nt"
and len(path.drive) > 2
and not path.drive[0].isalpha()
and path.drive[1] != ":"
):
return True
else:
return False |
<SYSTEM_TASK:>
Convert `path` to be relative.
<END_TASK>
<USER_TASK:>
Description:
def get_converted_relative_path(path, relative_to=None):
"""Convert `path` to be relative.
Given a vague relative path, return the path relative to the given
location.
:param str path: The location of a target path
:param str relative_to: The starting path to build against, optional
:returns: A relative posix-style path with a leading `./`
This performs additional conversion to ensure the result is of POSIX form,
and starts with `./`, or is precisely `.`.
>>> os.chdir('/home/user/code/myrepo/myfolder')
>>> vistir.path.get_converted_relative_path('/home/user/code/file.zip')
'./../../file.zip'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder/mysubfolder')
'./mysubfolder'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder')
'.'
""" |
from .misc import to_text, to_bytes # noqa
if not relative_to:
relative_to = os.getcwdu() if six.PY2 else os.getcwd()
if six.PY2:
path = to_bytes(path, encoding="utf-8")
else:
path = to_text(path, encoding="utf-8")
relative_to = to_text(relative_to, encoding="utf-8")
start_path = Path(relative_to)
try:
start = start_path.resolve()
except OSError:
start = start_path.absolute()
# check if there is a drive letter or mount point
# if it is a mountpoint use the original absolute path
# instead of the unc path
if check_for_unc_path(start):
start = start_path.absolute()
path = start.joinpath(path).relative_to(start)
# check and see if the path that was passed into the function is a UNC path
# and raise value error if it is not.
if check_for_unc_path(path):
raise ValueError("The path argument does not currently accept UNC paths")
relpath_s = to_text(posixpath.normpath(path.as_posix()))
if not (relpath_s == "." or relpath_s.startswith("./")):
relpath_s = posixpath.join(".", relpath_s)
return relpath_s |
<SYSTEM_TASK:>
Checks whether a given file-like object is closed.
<END_TASK>
<USER_TASK:>
Description:
def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
""" |
try:
# Check `isclosed()` first, in case Python3 doesn't set `closed`.
# GH Issue #928
return obj.isclosed()
except AttributeError:
pass
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object is a container for another file-like object that
# gets released on exhaustion (e.g. HTTPResponse).
return obj.fp is None
except AttributeError:
pass
raise ValueError("Unable to determine whether fp is closed.") |
<SYSTEM_TASK:>
Checks whether the request of a response has been a HEAD-request.
<END_TASK>
<USER_TASK:>
Description:
def is_response_to_head(response):
"""
Checks whether the request of a response has been a HEAD-request.
Handles the quirks of AppEngine.
:param conn:
:type conn: :class:`httplib.HTTPResponse`
""" |
# FIXME: Can we do this somehow without accessing private httplib _method?
method = response._method
if isinstance(method, int): # Platform-specific: Appengine
return method == 3
return method.upper() == 'HEAD' |
<SYSTEM_TASK:>
Return a string representing the user agent.
<END_TASK>
<USER_TASK:>
Description:
def user_agent():
"""
Return a string representing the user agent.
""" |
data = {
"installer": {"name": "pip", "version": pipenv.patched.notpip.__version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["implementation"]["name"] == 'CPython':
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'PyPy':
if sys.pypy_version_info.releaselevel == 'final':
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data["implementation"]["version"] = ".".join(
[str(x) for x in pypy_version_info]
)
elif data["implementation"]["name"] == 'Jython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'IronPython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
if sys.platform.startswith("linux"):
from pipenv.patched.notpip._vendor import distro
distro_infos = dict(filter(
lambda x: x[1],
zip(["name", "version", "id"], distro.linux_distribution()),
))
libc = dict(filter(
lambda x: x[1],
zip(["lib", "version"], libc_ver()),
))
if libc:
distro_infos["libc"] = libc
if distro_infos:
data["distro"] = distro_infos
if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
if platform.system():
data.setdefault("system", {})["name"] = platform.system()
if platform.release():
data.setdefault("system", {})["release"] = platform.release()
if platform.machine():
data["cpu"] = platform.machine()
if HAS_TLS:
data["openssl_version"] = ssl.OPENSSL_VERSION
setuptools_version = get_installed_version("setuptools")
if setuptools_version is not None:
data["setuptools_version"] = setuptools_version
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
) |
<SYSTEM_TASK:>
Return True if `name` is a considered as an archive file.
<END_TASK>
<USER_TASK:>
Description:
def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file.""" |
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False |
<SYSTEM_TASK:>
Unpack link into location.
<END_TASK>
<USER_TASK:>
Description:
def unpack_file_url(
link, # type: Link
location, # type: str
download_dir=None, # type: Optional[str]
hashes=None # type: Optional[Hashes]
):
# type: (...) -> None
"""Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir.
""" |
link_path = url_to_path(link.url_without_fragment)
# If it's a url to a local directory
if is_dir_url(link):
if os.path.isdir(location):
rmtree(location)
shutil.copytree(link_path, location, symlinks=True)
if download_dir:
logger.info('Link is a directory, ignoring download_dir')
return
# If --require-hashes is off, `hashes` is either empty, the
# link's embedded hash, or MissingHashes; it is required to
# match. If --require-hashes is on, we are satisfied by any
# hash in `hashes` matching: a URL-based or an option-based
# one; no internet-sourced hash will be in `hashes`.
if hashes:
hashes.check_against_path(link_path)
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link,
download_dir,
hashes)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link_path
content_type = mimetypes.guess_type(from_path)[0]
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies
unpack_file(from_path, location, content_type, link)
# a download dir is specified and not already downloaded
if download_dir and not already_downloaded_path:
_copy_file(from_path, download_dir, link) |
<SYSTEM_TASK:>
Copy distribution files in `link_path` to `location`.
<END_TASK>
<USER_TASK:>
Description:
def _copy_dist_from_dir(link_path, location):
"""Copy distribution files in `link_path` to `location`.
Invoked when user requests to install a local directory. E.g.:
pip install .
pip install ~/dev/git-repos/python-prompt-toolkit
""" |
# Note: This is currently VERY SLOW if you have a lot of data in the
# directory, because it copies everything with `shutil.copytree`.
# What it should really do is build an sdist and install that.
# See https://github.com/pypa/pip/issues/2195
if os.path.isdir(location):
rmtree(location)
# build an sdist
setup_py = 'setup.py'
sdist_args = [sys.executable]
sdist_args.append('-c')
sdist_args.append(SETUPTOOLS_SHIM % setup_py)
sdist_args.append('sdist')
sdist_args += ['--dist-dir', location]
logger.info('Running setup.py sdist for %s', link_path)
with indent_log():
call_subprocess(sdist_args, cwd=link_path, show_stdout=False)
# unpack sdist into `location`
sdist = os.path.join(location, os.listdir(location)[0])
logger.info('Unpacking sdist %s into %s', sdist, location)
unpack_file(sdist, location, content_type=None, link=None) |
<SYSTEM_TASK:>
Check download_dir for previously downloaded file with correct hash
<END_TASK>
<USER_TASK:>
Description:
def _check_download_dir(link, download_dir, hashes):
# type: (Link, str, Hashes) -> Optional[str]
""" Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
""" |
download_path = os.path.join(download_dir, link.filename)
if os.path.exists(download_path):
# If already downloaded, does its hash match?
logger.info('File was already downloaded %s', download_path)
if hashes:
try:
hashes.check_against_path(download_path)
except HashMismatch:
logger.warning(
'Previously-downloaded file %s has bad hash. '
'Re-downloading.',
download_path
)
os.unlink(download_path)
return None
return download_path
return None |
<SYSTEM_TASK:>
Create a pool key out of a request context dictionary.
<END_TASK>
<USER_TASK:>
Description:
def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey
""" |
# Since we mutate the dictionary, make a copy first
context = request_context.copy()
context['scheme'] = context['scheme'].lower()
context['host'] = context['host'].lower()
# These are both dictionaries and need to be transformed into frozensets
for key in ('headers', '_proxy_headers', '_socks_options'):
if key in context and context[key] is not None:
context[key] = frozenset(context[key].items())
# The socket_options key may be a list and needs to be transformed into a
# tuple.
socket_opts = context.get('socket_options')
if socket_opts is not None:
context['socket_options'] = tuple(socket_opts)
# Map the kwargs to the names in the namedtuple - this is necessary since
# namedtuples can't have fields starting with '_'.
for key in list(context.keys()):
context['key_' + key] = context.pop(key)
# Default to ``None`` for keys missing from the context
for field in key_class._fields:
if field not in context:
context[field] = None
return key_class(**context) |
<SYSTEM_TASK:>
Merge a dictionary of override values for self.connection_pool_kw.
<END_TASK>
<USER_TASK:>
Description:
def _merge_pool_kwargs(self, override):
"""
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary.
""" |
base_pool_kwargs = self.connection_pool_kw.copy()
if override:
for key, value in override.items():
if value is None:
try:
del base_pool_kwargs[key]
except KeyError:
pass
else:
base_pool_kwargs[key] = value
return base_pool_kwargs |
<SYSTEM_TASK:>
Returns a set of all variables in the AST that will be looked up from
<END_TASK>
<USER_TASK:>
Description:
def find_undeclared_variables(ast):
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
""" |
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers |
<SYSTEM_TASK:>
Finds all the referenced templates from the AST. This will return an
<END_TASK>
<USER_TASK:>
Description:
def find_referenced_templates(ast):
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
""" |
for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
nodes.Include)):
if not isinstance(node.template, nodes.Const):
# a tuple with some non consts in there
if isinstance(node.template, (nodes.Tuple, nodes.List)):
for template_name in node.template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, string_types):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(node.template.value, string_types):
yield node.template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and \
isinstance(node.template.value, (tuple, list)):
for template_name in node.template.value:
if isinstance(template_name, string_types):
yield template_name
# something else we don't care about, we could warn here
else:
yield None |
<SYSTEM_TASK:>
Remember all undeclared identifiers.
<END_TASK>
<USER_TASK:>
Description:
def enter_frame(self, frame):
"""Remember all undeclared identifiers.""" |
CodeGenerator.enter_frame(self, frame)
for _, (action, param) in iteritems(frame.symbols.loads):
if action == 'resolve':
self.undeclared_identifiers.add(param) |
<SYSTEM_TASK:>
Parse a marker string and return a dictionary containing a marker expression.
<END_TASK>
<USER_TASK:>
Description:
def parse_marker(marker_string):
"""
Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).
""" |
def marker_var(remaining):
# either identifier, or literal string
m = IDENTIFIER.match(remaining)
if m:
result = m.groups()[0]
remaining = remaining[m.end():]
elif not remaining:
raise SyntaxError('unexpected end of input')
else:
q = remaining[0]
if q not in '\'"':
raise SyntaxError('invalid expression: %s' % remaining)
oq = '\'"'.replace(q, '')
remaining = remaining[1:]
parts = [q]
while remaining:
# either a string chunk, or oq, or q to terminate
if remaining[0] == q:
break
elif remaining[0] == oq:
parts.append(oq)
remaining = remaining[1:]
else:
m = STRING_CHUNK.match(remaining)
if not m:
raise SyntaxError('error in string literal: %s' % remaining)
parts.append(m.groups()[0])
remaining = remaining[m.end():]
else:
s = ''.join(parts)
raise SyntaxError('unterminated string: %s' % s)
parts.append(q)
result = ''.join(parts)
remaining = remaining[1:].lstrip() # skip past closing quote
return result, remaining
def marker_expr(remaining):
if remaining and remaining[0] == '(':
result, remaining = marker(remaining[1:].lstrip())
if remaining[0] != ')':
raise SyntaxError('unterminated parenthesis: %s' % remaining)
remaining = remaining[1:].lstrip()
else:
lhs, remaining = marker_var(remaining)
while remaining:
m = MARKER_OP.match(remaining)
if not m:
break
op = m.groups()[0]
remaining = remaining[m.end():]
rhs, remaining = marker_var(remaining)
lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
result = lhs
return result, remaining
def marker_and(remaining):
lhs, remaining = marker_expr(remaining)
while remaining:
m = AND.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_expr(remaining)
lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
def marker(remaining):
lhs, remaining = marker_and(remaining)
while remaining:
m = OR.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_and(remaining)
lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
return marker(marker_string) |
<SYSTEM_TASK:>
Return 'pathname' as a name that will work on the native filesystem.
<END_TASK>
<USER_TASK:>
Description:
def convert_path(pathname):
"""Return 'pathname' as a name that will work on the native filesystem.
The path is split on '/' and put back together again using the current
directory separator. Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem. Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.
""" |
if os.sep == '/':
return pathname
if not pathname:
return pathname
if pathname[0] == '/':
raise ValueError("path '%s' cannot be absolute" % pathname)
if pathname[-1] == '/':
raise ValueError("path '%s' cannot end with '/'" % pathname)
paths = pathname.split('/')
while os.curdir in paths:
paths.remove(os.curdir)
if not paths:
return os.curdir
return os.path.join(*paths) |
<SYSTEM_TASK:>
Return the default base location for distlib caches. If the directory does
<END_TASK>
<USER_TASK:>
Description:
def get_cache_base(suffix=None):
"""
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.
On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.
The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.
""" |
if suffix is None:
suffix = '.distlib'
if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
result = os.path.expandvars('$localappdata')
else:
# Assume posix, or old Windows
result = os.path.expanduser('~')
# we use 'isdir' instead of 'exists', because we want to
# fail if there's a file with that name
if os.path.isdir(result):
usable = os.access(result, os.W_OK)
if not usable:
logger.warning('Directory exists but is not writable: %s', result)
else:
try:
os.makedirs(result)
usable = True
except OSError:
logger.warning('Unable to create %s', result, exc_info=True)
usable = False
if not usable:
result = tempfile.mkdtemp()
logger.warning('Default location unusable, using %s', result)
return os.path.join(result, suffix) |
<SYSTEM_TASK:>
Convert an absolute path to a directory name for use in a cache.
<END_TASK>
<USER_TASK:>
Description:
def path_to_cache_dir(path):
"""
Convert an absolute path to a directory name for use in a cache.
The algorithm used is:
#. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
#. Any occurrence of ``os.sep`` is replaced with ``'--'``.
#. ``'.cache'`` is appended.
""" |
d, p = os.path.splitdrive(os.path.abspath(path))
if d:
d = d.replace(':', '---')
p = p.replace(os.sep, '--')
return d + p + '.cache' |
<SYSTEM_TASK:>
A utility method used to get name and version from a string.
<END_TASK>
<USER_TASK:>
Description:
def parse_name_and_version(p):
"""
A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.
""" |
m = NAME_VERSION_RE.match(p)
if not m:
raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
d = m.groupdict()
return d['name'].strip().lower(), d['ver'] |
<SYSTEM_TASK:>
zip a directory tree into a BytesIO object
<END_TASK>
<USER_TASK:>
Description:
def zip_dir(directory):
"""zip a directory tree into a BytesIO object""" |
result = io.BytesIO()
dlen = len(directory)
with ZipFile(result, "w") as zf:
for root, dirs, files in os.walk(directory):
for name in files:
full = os.path.join(root, name)
rel = root[dlen:]
dest = os.path.join(rel, name)
zf.write(full, dest)
return result |
<SYSTEM_TASK:>
Tell if the target is newer than the source.
<END_TASK>
<USER_TASK:>
Description:
def newer(self, source, target):
"""Tell if the target is newer than the source.
Returns true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't.
Returns false if both exist and 'target' is the same age or younger
than 'source'. Raise PackagingFileError if 'source' does not exist.
Note that this test is not very accurate: files created in the same
second will have the same "age".
""" |
if not os.path.exists(source):
raise DistlibException("file '%r' does not exist" %
os.path.abspath(source))
if not os.path.exists(target):
return True
return os.stat(source).st_mtime > os.stat(target).st_mtime |
<SYSTEM_TASK:>
Copy a file respecting dry-run and force flags.
<END_TASK>
<USER_TASK:>
Description:
def copy_file(self, infile, outfile, check=True):
"""Copy a file respecting dry-run and force flags.
""" |
self.ensure_dir(os.path.dirname(outfile))
logger.info('Copying %s to %s', infile, outfile)
if not self.dry_run:
msg = None
if check:
if os.path.islink(outfile):
msg = '%s is a symlink' % outfile
elif os.path.exists(outfile) and not os.path.isfile(outfile):
msg = '%s is a non-regular file' % outfile
if msg:
raise ValueError(msg + ' which would be overwritten')
shutil.copyfile(infile, outfile)
self.record_as_written(outfile) |
<SYSTEM_TASK:>
Commit recorded changes, turn off recording, return
<END_TASK>
<USER_TASK:>
Description:
def commit(self):
"""
Commit recorded changes, turn off recording, return
changes.
""" |
assert self.record
result = self.files_written, self.dirs_created
self._init_record()
return result |
<SYSTEM_TASK:>
Add a subscriber for an event.
<END_TASK>
<USER_TASK:>
Description:
def add(self, event, subscriber, append=True):
"""
Add a subscriber for an event.
:param event: The name of an event.
:param subscriber: The subscriber to be added (and called when the
event is published).
:param append: Whether to append or prepend the subscriber to an
existing subscriber list for the event.
""" |
subs = self._subscribers
if event not in subs:
subs[event] = deque([subscriber])
else:
sq = subs[event]
if append:
sq.append(subscriber)
else:
sq.appendleft(subscriber) |
<SYSTEM_TASK:>
Remove a subscriber for an event.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, event, subscriber):
"""
Remove a subscriber for an event.
:param event: The name of an event.
:param subscriber: The subscriber to be removed.
""" |
subs = self._subscribers
if event not in subs:
raise ValueError('No subscribers: %r' % event)
subs[event].remove(subscriber) |
<SYSTEM_TASK:>
Publish a event and return a list of values returned by its
<END_TASK>
<USER_TASK:>
Description:
def publish(self, event, *args, **kwargs):
"""
Publish a event and return a list of values returned by its
subscribers.
:param event: The event to publish.
:param args: The positional arguments to pass to the event's
subscribers.
:param kwargs: The keyword arguments to pass to the event's
subscribers.
""" |
result = []
for subscriber in self.get_subscribers(event):
try:
value = subscriber(event, *args, **kwargs)
except Exception:
logger.exception('Exception during event publication')
value = None
result.append(value)
logger.debug('publish %s: args = %s, kwargs = %s, result = %s',
event, args, kwargs, result)
return result |
<SYSTEM_TASK:>
Query the PyPI RSS feed and return a list
<END_TASK>
<USER_TASK:>
Description:
def _get(pypi_server):
"""
Query the PyPI RSS feed and return a list
of XML items.
""" |
response = requests.get(pypi_server)
if response.status_code >= 300:
raise HTTPError(status_code=response.status_code,
reason=response.reason)
if hasattr(response.content, 'decode'):
tree = xml.etree.ElementTree.fromstring(response.content.decode())
else:
tree = xml.etree.ElementTree.fromstring(response.content)
channel = tree.find('channel')
return channel.findall('item') |
<SYSTEM_TASK:>
Produce a mapping containing all candidates derived from `identifiers`.
<END_TASK>
<USER_TASK:>
Description:
def _collect_derived_entries(state, traces, identifiers):
"""Produce a mapping containing all candidates derived from `identifiers`.
`identifiers` should provide a collection of requirement identifications
from a section (i.e. `packages` or `dev-packages`). This function uses
`trace` to filter out candidates in the state that are present because of
an entry in that collection.
""" |
identifiers = set(identifiers)
if not identifiers:
return {}
entries = {}
extras = {}
for identifier, requirement in state.mapping.items():
routes = {trace[1] for trace in traces[identifier] if len(trace) > 1}
if identifier not in identifiers and not (identifiers & routes):
continue
name = requirement.normalized_name
if requirement.extras:
# Aggregate extras from multiple routes so we can produce their
# union in the lock file. (sarugaku/passa#24)
try:
extras[name].extend(requirement.extras)
except KeyError:
extras[name] = list(requirement.extras)
entries[name] = next(iter(requirement.as_pipfile().values()))
for name, ext in extras.items():
entries[name]["extras"] = ext
return entries |
<SYSTEM_TASK:>
Configures and sets up all of the logging
<END_TASK>
<USER_TASK:>
Description:
def setup_logging(verbosity, no_color, user_log_file):
"""Configures and sets up all of the logging
Returns the requested logging level, as its integer value.
""" |
# Determine the level to be logging at.
if verbosity >= 1:
level = "DEBUG"
elif verbosity == -1:
level = "WARNING"
elif verbosity == -2:
level = "ERROR"
elif verbosity <= -3:
level = "CRITICAL"
else:
level = "INFO"
level_number = getattr(logging, level)
# The "root" logger should match the "console" level *unless* we also need
# to log to a user log file.
include_user_log = user_log_file is not None
if include_user_log:
additional_log_file = user_log_file
root_level = "DEBUG"
else:
additional_log_file = "/dev/null"
root_level = level
# Disable any logging besides WARNING unless we have DEBUG level logging
# enabled for vendored libraries.
vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
# Shorthands for clarity
log_streams = {
"stdout": "ext://sys.stdout",
"stderr": "ext://sys.stderr",
}
handler_classes = {
"stream": "pip._internal.utils.logging.ColorizedStreamHandler",
"file": "pip._internal.utils.logging.BetterRotatingFileHandler",
}
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"filters": {
"exclude_warnings": {
"()": "pip._internal.utils.logging.MaxLevelFilter",
"level": logging.WARNING,
},
},
"formatters": {
"indent": {
"()": IndentingFormatter,
"format": "%(message)s",
},
"indent_with_timestamp": {
"()": IndentingFormatter,
"format": "%(message)s",
"add_timestamp": True,
},
},
"handlers": {
"console": {
"level": level,
"class": handler_classes["stream"],
"no_color": no_color,
"stream": log_streams["stdout"],
"filters": ["exclude_warnings"],
"formatter": "indent",
},
"console_errors": {
"level": "WARNING",
"class": handler_classes["stream"],
"no_color": no_color,
"stream": log_streams["stderr"],
"formatter": "indent",
},
"user_log": {
"level": "DEBUG",
"class": handler_classes["file"],
"filename": additional_log_file,
"delay": True,
"formatter": "indent_with_timestamp",
},
},
"root": {
"level": root_level,
"handlers": ["console", "console_errors"] + (
["user_log"] if include_user_log else []
),
},
"loggers": {
"pip._vendor": {
"level": vendored_log_level
}
},
})
return level_number |
<SYSTEM_TASK:>
Calls the standard formatter, but will indent all of the log messages
<END_TASK>
<USER_TASK:>
Description:
def format(self, record):
"""
Calls the standard formatter, but will indent all of the log messages
by our current indentation level.
""" |
formatted = super(IndentingFormatter, self).format(record)
prefix = ''
if self.add_timestamp:
prefix = self.formatTime(record, "%Y-%m-%dT%H:%M:%S ")
prefix += " " * get_indentation()
formatted = "".join([
prefix + line
for line in formatted.splitlines(True)
])
return formatted |
<SYSTEM_TASK:>
Return whether the handler is using sys.stdout.
<END_TASK>
<USER_TASK:>
Description:
def _using_stdout(self):
"""
Return whether the handler is using sys.stdout.
""" |
if WINDOWS and colorama:
# Then self.stream is an AnsiToWin32 object.
return self.stream.wrapped is sys.stdout
return self.stream is sys.stdout |
<SYSTEM_TASK:>
Writes re-indented text into the buffer. This rewraps and
<END_TASK>
<USER_TASK:>
Description:
def write_text(self, text):
"""Writes re-indented text into the buffer. This rewraps and
preserves paragraphs.
""" |
text_width = max(self.width - self.current_indent, 11)
indent = ' ' * self.current_indent
self.write(wrap_text(text, text_width,
initial_indent=indent,
subsequent_indent=indent,
preserve_paragraphs=True))
self.write('\n') |
<SYSTEM_TASK:>
Writes a definition list into the buffer. This is how options
<END_TASK>
<USER_TASK:>
Description:
def write_dl(self, rows, col_max=30, col_spacing=2):
"""Writes a definition list into the buffer. This is how options
and commands are usually formatted.
:param rows: a list of two item tuples for the terms and values.
:param col_max: the maximum width of the first column.
:param col_spacing: the number of spaces between the first and
second column.
""" |
rows = list(rows)
widths = measure_table(rows)
if len(widths) != 2:
raise TypeError('Expected two columns for definition list')
first_col = min(widths[0], col_max) + col_spacing
for first, second in iter_rows(rows, len(widths)):
self.write('%*s%s' % (self.current_indent, '', first))
if not second:
self.write('\n')
continue
if term_len(first) <= first_col - col_spacing:
self.write(' ' * (first_col - term_len(first)))
else:
self.write('\n')
self.write(' ' * (first_col + self.current_indent))
text_width = max(self.width - first_col - 2, 10)
lines = iter(wrap_text(second, text_width).splitlines())
if lines:
self.write(next(lines) + '\n')
for line in lines:
self.write('%*s%s\n' % (
first_col + self.current_indent, '', line))
else:
self.write('\n') |
<SYSTEM_TASK:>
Helpful context manager that writes a paragraph, a heading,
<END_TASK>
<USER_TASK:>
Description:
def section(self, name):
"""Helpful context manager that writes a paragraph, a heading,
and the indents.
:param name: the section name that is written as heading.
""" |
self.write_paragraph()
self.write_heading(name)
self.indent()
try:
yield
finally:
self.dedent() |
<SYSTEM_TASK:>
Returns a better error message when invalid configuration option
<END_TASK>
<USER_TASK:>
Description:
def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided.""" |
if action in ('store_true', 'store_false'):
return ("{0} is not a valid value for {1} option, "
"please specify a boolean value like yes/no, "
"true/false or 1/0 instead.").format(val, key)
return ("{0} is not a valid value for {1} option, "
"please specify a numerical value like 1/0 "
"instead.").format(val, key) |
<SYSTEM_TASK:>
Return a comma-separated list of option strings and metavars.
<END_TASK>
<USER_TASK:>
Description:
def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '):
"""
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string - evaluated as mvarfmt % metavar
:param optsep: separator
""" |
opts = []
if option._short_opts:
opts.append(option._short_opts[0])
if option._long_opts:
opts.append(option._long_opts[0])
if len(opts) > 1:
opts.insert(1, optsep)
if option.takes_value():
metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt % metavar.lower())
return ''.join(opts) |
<SYSTEM_TASK:>
Ensure there is only one newline between usage and the first heading
<END_TASK>
<USER_TASK:>
Description:
def format_usage(self, usage):
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
""" |
msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ")
return msg |
<SYSTEM_TASK:>
Get a list of all options, including those in option groups.
<END_TASK>
<USER_TASK:>
Description:
def option_list_all(self):
"""Get a list of all options, including those in option groups.""" |
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res |
<SYSTEM_TASK:>
Helper utility for reimporting previously imported modules while inside the env
<END_TASK>
<USER_TASK:>
Description:
def safe_import(self, name):
"""Helper utility for reimporting previously imported modules while inside the env""" |
module = None
if name not in self._modules:
self._modules[name] = importlib.import_module(name)
module = self._modules[name]
if not module:
dist = next(iter(
dist for dist in self.base_working_set if dist.project_name == name
), None)
if dist:
dist.activate()
module = importlib.import_module(name)
if name in sys.modules:
try:
six.moves.reload_module(module)
six.moves.reload_module(sys.modules[name])
except TypeError:
del sys.modules[name]
sys.modules[name] = self._modules[name]
return module |
<SYSTEM_TASK:>
Given a local distribution and a working set, returns all dependencies from the set.
<END_TASK>
<USER_TASK:>
Description:
def resolve_dist(cls, dist, working_set):
"""Given a local distribution and a working set, returns all dependencies from the set.
:param dist: A single distribution to find the dependencies of
:type dist: :class:`pkg_resources.Distribution`
:param working_set: A working set to search for all packages
:type working_set: :class:`pkg_resources.WorkingSet`
:return: A set of distributions which the package depends on, including the package
:rtype: set(:class:`pkg_resources.Distribution`)
""" |
deps = set()
deps.add(dist)
try:
reqs = dist.requires()
except (AttributeError, OSError, IOError): # The METADATA file can't be found
return deps
for req in reqs:
dist = working_set.find(req)
deps |= cls.resolve_dist(dist, working_set)
return deps |
<SYSTEM_TASK:>
Returns the context appropriate paths for the environment.
<END_TASK>
<USER_TASK:>
Description:
def base_paths(self):
"""
Returns the context appropriate paths for the environment.
:return: A dictionary of environment specific paths to be used for installation operations
:rtype: dict
.. note:: The implementation of this is borrowed from a combination of pip and
virtualenv and is likely to change at some point in the future.
>>> from pipenv.core import project
>>> from pipenv.environment import Environment
>>> env = Environment(prefix=project.virtualenv_location, is_venv=True, sources=project.sources)
>>> import pprint
>>> pprint.pprint(env.base_paths)
{'PATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin::/bin:/usr/bin',
'PYTHONPATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages',
'data': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW',
'include': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m',
'libdir': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages',
'platinclude': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m',
'platlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages',
'platstdlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7',
'prefix': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW',
'purelib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages',
'scripts': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin',
'stdlib': '/home/hawk/.pyenv/versions/3.7.1/lib/python3.7'}
""" |
prefix = make_posix(self.prefix.as_posix())
install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
paths = get_paths(install_scheme, vars={
'base': prefix,
'platbase': prefix,
})
paths["PATH"] = paths["scripts"] + os.pathsep + os.defpath
if "prefix" not in paths:
paths["prefix"] = prefix
purelib = make_posix(get_python_lib(plat_specific=0, prefix=prefix))
platlib = make_posix(get_python_lib(plat_specific=1, prefix=prefix))
if purelib == platlib:
lib_dirs = purelib
else:
lib_dirs = purelib + os.pathsep + platlib
paths["libdir"] = purelib
paths["purelib"] = purelib
paths["platlib"] = platlib
paths['PYTHONPATH'] = os.pathsep.join(["", ".", lib_dirs])
paths["libdirs"] = lib_dirs
return paths |
<SYSTEM_TASK:>
Path to the environment python
<END_TASK>
<USER_TASK:>
Description:
def python(self):
"""Path to the environment python""" |
py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix()
if not py:
return vistir.compat.Path(sys.executable).as_posix()
return py |
<SYSTEM_TASK:>
The system path inside the environment
<END_TASK>
<USER_TASK:>
Description:
def sys_path(self):
"""
The system path inside the environment
:return: The :data:`sys.path` from the environment
:rtype: list
""" |
from .vendor.vistir.compat import JSONDecodeError
current_executable = vistir.compat.Path(sys.executable).as_posix()
if not self.python or self.python == current_executable:
return sys.path
elif any([sys.prefix == self.prefix, not self.is_venv]):
return sys.path
cmd_args = [self.python, "-c", "import json, sys; print(json.dumps(sys.path))"]
path, _ = vistir.misc.run(cmd_args, return_object=False, nospin=True, block=True, combine_stderr=False, write_to_stdout=False)
try:
path = json.loads(path.strip())
except JSONDecodeError:
path = sys.path
return path |
<SYSTEM_TASK:>
The prefix run inside the context of the environment
<END_TASK>
<USER_TASK:>
Description:
def sys_prefix(self):
"""
The prefix run inside the context of the environment
:return: The python prefix inside the environment
:rtype: :data:`sys.prefix`
""" |
command = [self.python, "-c" "import sys; print(sys.prefix)"]
c = vistir.misc.run(command, return_object=True, block=True, nospin=True, write_to_stdout=False)
sys_prefix = vistir.compat.Path(vistir.misc.to_text(c.out).strip()).as_posix()
return sys_prefix |
<SYSTEM_TASK:>
Get the pip version in the environment. Useful for knowing which args we can use
<END_TASK>
<USER_TASK:>
Description:
def pip_version(self):
"""
Get the pip version in the environment. Useful for knowing which args we can use
when installing.
""" |
from .vendor.packaging.version import parse as parse_version
pip = next(iter(
pkg for pkg in self.get_installed_packages() if pkg.key == "pip"
), None)
if pip is not None:
pip_version = parse_version(pip.version)
return parse_version("18.0") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.