id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,900 | pypa/pipenv | pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py | get_subj_alt_name | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
# We also want to skip over names which cannot be idna encoded.
names = [
('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
if name is not None
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names | python | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
# We also want to skip over names which cannot be idna encoded.
names = [
('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
if name is not None
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names | [
"def",
"get_subj_alt_name",
"(",
"peer_cert",
")",
":",
"# Pass the cert to cryptography, which has much better APIs for this.",
"if",
"hasattr",
"(",
"peer_cert",
",",
"\"to_cryptography\"",
")",
":",
"cert",
"=",
"peer_cert",
".",
"to_cryptography",
"(",
")",
"else",
":",
"# This is technically using private APIs, but should work across all",
"# relevant versions before PyOpenSSL got a proper API for this.",
"cert",
"=",
"_Certificate",
"(",
"openssl_backend",
",",
"peer_cert",
".",
"_x509",
")",
"# We want to find the SAN extension. Ask Cryptography to locate it (it's",
"# faster than looping in Python)",
"try",
":",
"ext",
"=",
"cert",
".",
"extensions",
".",
"get_extension_for_class",
"(",
"x509",
".",
"SubjectAlternativeName",
")",
".",
"value",
"except",
"x509",
".",
"ExtensionNotFound",
":",
"# No such extension, return the empty list.",
"return",
"[",
"]",
"except",
"(",
"x509",
".",
"DuplicateExtension",
",",
"UnsupportedExtension",
",",
"x509",
".",
"UnsupportedGeneralNameType",
",",
"UnicodeError",
")",
"as",
"e",
":",
"# A problem has been found with the quality of the certificate. Assume",
"# no SAN field is present.",
"log",
".",
"warning",
"(",
"\"A problem was encountered with the certificate that prevented \"",
"\"urllib3 from finding the SubjectAlternativeName field. This can \"",
"\"affect certificate validation. The error was %s\"",
",",
"e",
",",
")",
"return",
"[",
"]",
"# We want to return dNSName and iPAddress fields. We need to cast the IPs",
"# back to strings because the match_hostname function wants them as",
"# strings.",
"# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8",
"# decoded. This is pretty frustrating, but that's what the standard library",
"# does with certificates, and so we need to attempt to do the same.",
"# We also want to skip over names which cannot be idna encoded.",
"names",
"=",
"[",
"(",
"'DNS'",
",",
"name",
")",
"for",
"name",
"in",
"map",
"(",
"_dnsname_to_stdlib",
",",
"ext",
".",
"get_values_for_type",
"(",
"x509",
".",
"DNSName",
")",
")",
"if",
"name",
"is",
"not",
"None",
"]",
"names",
".",
"extend",
"(",
"(",
"'IP Address'",
",",
"str",
"(",
"name",
")",
")",
"for",
"name",
"in",
"ext",
".",
"get_values_for_type",
"(",
"x509",
".",
"IPAddress",
")",
")",
"return",
"names"
] | Given an PyOpenSSL certificate, provides all the subject alternative names. | [
"Given",
"an",
"PyOpenSSL",
"certificate",
"provides",
"all",
"the",
"subject",
"alternative",
"names",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L195-L244 |
24,901 | pypa/pipenv | pipenv/utils.py | _get_requests_session | def _get_requests_session():
"""Load requests lazily."""
global requests_session
if requests_session is not None:
return requests_session
import requests
requests_session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=environments.PIPENV_MAX_RETRIES
)
requests_session.mount("https://pypi.org/pypi", adapter)
return requests_session | python | def _get_requests_session():
"""Load requests lazily."""
global requests_session
if requests_session is not None:
return requests_session
import requests
requests_session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=environments.PIPENV_MAX_RETRIES
)
requests_session.mount("https://pypi.org/pypi", adapter)
return requests_session | [
"def",
"_get_requests_session",
"(",
")",
":",
"global",
"requests_session",
"if",
"requests_session",
"is",
"not",
"None",
":",
"return",
"requests_session",
"import",
"requests",
"requests_session",
"=",
"requests",
".",
"Session",
"(",
")",
"adapter",
"=",
"requests",
".",
"adapters",
".",
"HTTPAdapter",
"(",
"max_retries",
"=",
"environments",
".",
"PIPENV_MAX_RETRIES",
")",
"requests_session",
".",
"mount",
"(",
"\"https://pypi.org/pypi\"",
",",
"adapter",
")",
"return",
"requests_session"
] | Load requests lazily. | [
"Load",
"requests",
"lazily",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L53-L65 |
24,902 | pypa/pipenv | pipenv/utils.py | convert_toml_outline_tables | def convert_toml_outline_tables(parsed):
"""Converts all outline tables to inline tables."""
def convert_tomlkit_table(section):
for key, value in section._body:
if not key:
continue
if hasattr(value, "keys") and not isinstance(value, tomlkit.items.InlineTable):
table = tomlkit.inline_table()
table.update(value.value)
section[key.key] = table
def convert_toml_table(section):
for package, value in section.items():
if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict):
table = toml.TomlDecoder().get_empty_inline_table()
table.update(value)
section[package] = table
is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container)
for section in ("packages", "dev-packages"):
table_data = parsed.get(section, {})
if not table_data:
continue
if is_tomlkit_parsed:
convert_tomlkit_table(table_data)
else:
convert_toml_table(table_data)
return parsed | python | def convert_toml_outline_tables(parsed):
"""Converts all outline tables to inline tables."""
def convert_tomlkit_table(section):
for key, value in section._body:
if not key:
continue
if hasattr(value, "keys") and not isinstance(value, tomlkit.items.InlineTable):
table = tomlkit.inline_table()
table.update(value.value)
section[key.key] = table
def convert_toml_table(section):
for package, value in section.items():
if hasattr(value, "keys") and not isinstance(value, toml.decoder.InlineTableDict):
table = toml.TomlDecoder().get_empty_inline_table()
table.update(value)
section[package] = table
is_tomlkit_parsed = isinstance(parsed, tomlkit.container.Container)
for section in ("packages", "dev-packages"):
table_data = parsed.get(section, {})
if not table_data:
continue
if is_tomlkit_parsed:
convert_tomlkit_table(table_data)
else:
convert_toml_table(table_data)
return parsed | [
"def",
"convert_toml_outline_tables",
"(",
"parsed",
")",
":",
"def",
"convert_tomlkit_table",
"(",
"section",
")",
":",
"for",
"key",
",",
"value",
"in",
"section",
".",
"_body",
":",
"if",
"not",
"key",
":",
"continue",
"if",
"hasattr",
"(",
"value",
",",
"\"keys\"",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"tomlkit",
".",
"items",
".",
"InlineTable",
")",
":",
"table",
"=",
"tomlkit",
".",
"inline_table",
"(",
")",
"table",
".",
"update",
"(",
"value",
".",
"value",
")",
"section",
"[",
"key",
".",
"key",
"]",
"=",
"table",
"def",
"convert_toml_table",
"(",
"section",
")",
":",
"for",
"package",
",",
"value",
"in",
"section",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"\"keys\"",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"toml",
".",
"decoder",
".",
"InlineTableDict",
")",
":",
"table",
"=",
"toml",
".",
"TomlDecoder",
"(",
")",
".",
"get_empty_inline_table",
"(",
")",
"table",
".",
"update",
"(",
"value",
")",
"section",
"[",
"package",
"]",
"=",
"table",
"is_tomlkit_parsed",
"=",
"isinstance",
"(",
"parsed",
",",
"tomlkit",
".",
"container",
".",
"Container",
")",
"for",
"section",
"in",
"(",
"\"packages\"",
",",
"\"dev-packages\"",
")",
":",
"table_data",
"=",
"parsed",
".",
"get",
"(",
"section",
",",
"{",
"}",
")",
"if",
"not",
"table_data",
":",
"continue",
"if",
"is_tomlkit_parsed",
":",
"convert_tomlkit_table",
"(",
"table_data",
")",
"else",
":",
"convert_toml_table",
"(",
"table_data",
")",
"return",
"parsed"
] | Converts all outline tables to inline tables. | [
"Converts",
"all",
"outline",
"tables",
"to",
"inline",
"tables",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L91-L119 |
24,903 | pypa/pipenv | pipenv/utils.py | run_command | def run_command(cmd, *args, **kwargs):
"""
Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError
"""
from pipenv.vendor import delegator
from ._compat import decode_for_output
from .cmdparse import Script
catch_exceptions = kwargs.pop("catch_exceptions", True)
if isinstance(cmd, (six.string_types, list, tuple)):
cmd = Script.parse(cmd)
if not isinstance(cmd, Script):
raise TypeError("Command input must be a string, list or tuple")
if "env" not in kwargs:
kwargs["env"] = os.environ.copy()
kwargs["env"]["PYTHONIOENCODING"] = "UTF-8"
try:
cmd_string = cmd.cmdify()
except TypeError:
click_echo("Error turning command into string: {0}".format(cmd), err=True)
sys.exit(1)
if environments.is_verbose():
click_echo("Running command: $ {0}".format(cmd_string, err=True))
c = delegator.run(cmd_string, *args, **kwargs)
return_code = c.return_code
if environments.is_verbose():
click_echo("Command output: {0}".format(
crayons.blue(decode_for_output(c.out))
), err=True)
if not c.ok and catch_exceptions:
raise PipenvCmdError(cmd_string, c.out, c.err, return_code)
return c | python | def run_command(cmd, *args, **kwargs):
"""
Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError
"""
from pipenv.vendor import delegator
from ._compat import decode_for_output
from .cmdparse import Script
catch_exceptions = kwargs.pop("catch_exceptions", True)
if isinstance(cmd, (six.string_types, list, tuple)):
cmd = Script.parse(cmd)
if not isinstance(cmd, Script):
raise TypeError("Command input must be a string, list or tuple")
if "env" not in kwargs:
kwargs["env"] = os.environ.copy()
kwargs["env"]["PYTHONIOENCODING"] = "UTF-8"
try:
cmd_string = cmd.cmdify()
except TypeError:
click_echo("Error turning command into string: {0}".format(cmd), err=True)
sys.exit(1)
if environments.is_verbose():
click_echo("Running command: $ {0}".format(cmd_string, err=True))
c = delegator.run(cmd_string, *args, **kwargs)
return_code = c.return_code
if environments.is_verbose():
click_echo("Command output: {0}".format(
crayons.blue(decode_for_output(c.out))
), err=True)
if not c.ok and catch_exceptions:
raise PipenvCmdError(cmd_string, c.out, c.err, return_code)
return c | [
"def",
"run_command",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pipenv",
".",
"vendor",
"import",
"delegator",
"from",
".",
"_compat",
"import",
"decode_for_output",
"from",
".",
"cmdparse",
"import",
"Script",
"catch_exceptions",
"=",
"kwargs",
".",
"pop",
"(",
"\"catch_exceptions\"",
",",
"True",
")",
"if",
"isinstance",
"(",
"cmd",
",",
"(",
"six",
".",
"string_types",
",",
"list",
",",
"tuple",
")",
")",
":",
"cmd",
"=",
"Script",
".",
"parse",
"(",
"cmd",
")",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"Script",
")",
":",
"raise",
"TypeError",
"(",
"\"Command input must be a string, list or tuple\"",
")",
"if",
"\"env\"",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"env\"",
"]",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"kwargs",
"[",
"\"env\"",
"]",
"[",
"\"PYTHONIOENCODING\"",
"]",
"=",
"\"UTF-8\"",
"try",
":",
"cmd_string",
"=",
"cmd",
".",
"cmdify",
"(",
")",
"except",
"TypeError",
":",
"click_echo",
"(",
"\"Error turning command into string: {0}\"",
".",
"format",
"(",
"cmd",
")",
",",
"err",
"=",
"True",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"environments",
".",
"is_verbose",
"(",
")",
":",
"click_echo",
"(",
"\"Running command: $ {0}\"",
".",
"format",
"(",
"cmd_string",
",",
"err",
"=",
"True",
")",
")",
"c",
"=",
"delegator",
".",
"run",
"(",
"cmd_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return_code",
"=",
"c",
".",
"return_code",
"if",
"environments",
".",
"is_verbose",
"(",
")",
":",
"click_echo",
"(",
"\"Command output: {0}\"",
".",
"format",
"(",
"crayons",
".",
"blue",
"(",
"decode_for_output",
"(",
"c",
".",
"out",
")",
")",
")",
",",
"err",
"=",
"True",
")",
"if",
"not",
"c",
".",
"ok",
"and",
"catch_exceptions",
":",
"raise",
"PipenvCmdError",
"(",
"cmd_string",
",",
"c",
".",
"out",
",",
"c",
".",
"err",
",",
"return_code",
")",
"return",
"c"
] | Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError | [
"Take",
"an",
"input",
"command",
"and",
"run",
"it",
"handling",
"exceptions",
"and",
"error",
"codes",
"and",
"returning",
"its",
"stdout",
"and",
"stderr",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L122-L160 |
24,904 | pypa/pipenv | pipenv/utils.py | convert_deps_to_pip | def convert_deps_to_pip(deps, project=None, r=True, include_index=True):
""""Converts a Pipfile-formatted dependency to a pip-formatted one."""
from .vendor.requirementslib.models.requirements import Requirement
dependencies = []
for dep_name, dep in deps.items():
if project:
project.clear_pipfile_cache()
indexes = getattr(project, "pipfile_sources", []) if project is not None else []
new_dep = Requirement.from_pipfile(dep_name, dep)
if new_dep.index:
include_index = True
req = new_dep.as_line(sources=indexes if include_index else None).strip()
dependencies.append(req)
if not r:
return dependencies
# Write requirements.txt to tmp directory.
from .vendor.vistir.path import create_tracked_tempfile
f = create_tracked_tempfile(suffix="-requirements.txt", delete=False)
f.write("\n".join(dependencies).encode("utf-8"))
f.close()
return f.name | python | def convert_deps_to_pip(deps, project=None, r=True, include_index=True):
""""Converts a Pipfile-formatted dependency to a pip-formatted one."""
from .vendor.requirementslib.models.requirements import Requirement
dependencies = []
for dep_name, dep in deps.items():
if project:
project.clear_pipfile_cache()
indexes = getattr(project, "pipfile_sources", []) if project is not None else []
new_dep = Requirement.from_pipfile(dep_name, dep)
if new_dep.index:
include_index = True
req = new_dep.as_line(sources=indexes if include_index else None).strip()
dependencies.append(req)
if not r:
return dependencies
# Write requirements.txt to tmp directory.
from .vendor.vistir.path import create_tracked_tempfile
f = create_tracked_tempfile(suffix="-requirements.txt", delete=False)
f.write("\n".join(dependencies).encode("utf-8"))
f.close()
return f.name | [
"def",
"convert_deps_to_pip",
"(",
"deps",
",",
"project",
"=",
"None",
",",
"r",
"=",
"True",
",",
"include_index",
"=",
"True",
")",
":",
"from",
".",
"vendor",
".",
"requirementslib",
".",
"models",
".",
"requirements",
"import",
"Requirement",
"dependencies",
"=",
"[",
"]",
"for",
"dep_name",
",",
"dep",
"in",
"deps",
".",
"items",
"(",
")",
":",
"if",
"project",
":",
"project",
".",
"clear_pipfile_cache",
"(",
")",
"indexes",
"=",
"getattr",
"(",
"project",
",",
"\"pipfile_sources\"",
",",
"[",
"]",
")",
"if",
"project",
"is",
"not",
"None",
"else",
"[",
"]",
"new_dep",
"=",
"Requirement",
".",
"from_pipfile",
"(",
"dep_name",
",",
"dep",
")",
"if",
"new_dep",
".",
"index",
":",
"include_index",
"=",
"True",
"req",
"=",
"new_dep",
".",
"as_line",
"(",
"sources",
"=",
"indexes",
"if",
"include_index",
"else",
"None",
")",
".",
"strip",
"(",
")",
"dependencies",
".",
"append",
"(",
"req",
")",
"if",
"not",
"r",
":",
"return",
"dependencies",
"# Write requirements.txt to tmp directory.",
"from",
".",
"vendor",
".",
"vistir",
".",
"path",
"import",
"create_tracked_tempfile",
"f",
"=",
"create_tracked_tempfile",
"(",
"suffix",
"=",
"\"-requirements.txt\"",
",",
"delete",
"=",
"False",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
".",
"join",
"(",
"dependencies",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"f",
".",
"name"
] | Converts a Pipfile-formatted dependency to a pip-formatted one. | [
"Converts",
"a",
"Pipfile",
"-",
"formatted",
"dependency",
"to",
"a",
"pip",
"-",
"formatted",
"one",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1127-L1149 |
24,905 | pypa/pipenv | pipenv/utils.py | is_required_version | def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("version", "")
if specified_version.startswith("=="):
return version.strip() == specified_version.split("==")[1].strip()
return True | python | def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("version", "")
if specified_version.startswith("=="):
return version.strip() == specified_version.split("==")[1].strip()
return True | [
"def",
"is_required_version",
"(",
"version",
",",
"specified_version",
")",
":",
"# Certain packages may be defined with multiple values.",
"if",
"isinstance",
"(",
"specified_version",
",",
"dict",
")",
":",
"specified_version",
"=",
"specified_version",
".",
"get",
"(",
"\"version\"",
",",
"\"\"",
")",
"if",
"specified_version",
".",
"startswith",
"(",
"\"==\"",
")",
":",
"return",
"version",
".",
"strip",
"(",
")",
"==",
"specified_version",
".",
"split",
"(",
"\"==\"",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"True"
] | Check to see if there's a hard requirement for version
number provided in the Pipfile. | [
"Check",
"to",
"see",
"if",
"there",
"s",
"a",
"hard",
"requirement",
"for",
"version",
"number",
"provided",
"in",
"the",
"Pipfile",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1185-L1195 |
24,906 | pypa/pipenv | pipenv/utils.py | is_file | def is_file(package):
"""Determine if a package name is for a File dependency."""
if hasattr(package, "keys"):
return any(key for key in package.keys() if key in ["file", "path"])
if os.path.exists(str(package)):
return True
for start in SCHEME_LIST:
if str(package).startswith(start):
return True
return False | python | def is_file(package):
"""Determine if a package name is for a File dependency."""
if hasattr(package, "keys"):
return any(key for key in package.keys() if key in ["file", "path"])
if os.path.exists(str(package)):
return True
for start in SCHEME_LIST:
if str(package).startswith(start):
return True
return False | [
"def",
"is_file",
"(",
"package",
")",
":",
"if",
"hasattr",
"(",
"package",
",",
"\"keys\"",
")",
":",
"return",
"any",
"(",
"key",
"for",
"key",
"in",
"package",
".",
"keys",
"(",
")",
"if",
"key",
"in",
"[",
"\"file\"",
",",
"\"path\"",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"str",
"(",
"package",
")",
")",
":",
"return",
"True",
"for",
"start",
"in",
"SCHEME_LIST",
":",
"if",
"str",
"(",
"package",
")",
".",
"startswith",
"(",
"start",
")",
":",
"return",
"True",
"return",
"False"
] | Determine if a package name is for a File dependency. | [
"Determine",
"if",
"a",
"package",
"name",
"is",
"for",
"a",
"File",
"dependency",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1244-L1256 |
24,907 | pypa/pipenv | pipenv/utils.py | pep423_name | def pep423_name(name):
"""Normalize package name to PEP 423 style standard."""
name = name.lower()
if any(i not in name for i in (VCS_LIST + SCHEME_LIST)):
return name.replace("_", "-")
else:
return name | python | def pep423_name(name):
"""Normalize package name to PEP 423 style standard."""
name = name.lower()
if any(i not in name for i in (VCS_LIST + SCHEME_LIST)):
return name.replace("_", "-")
else:
return name | [
"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. | [
"Normalize",
"package",
"name",
"to",
"PEP",
"423",
"style",
"standard",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1267-L1274 |
24,908 | pypa/pipenv | pipenv/utils.py | proper_case | def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} in PyPI repository.".format(package_name)
)
r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
good_name = r["name"]
return good_name | python | def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} in PyPI repository.".format(package_name)
)
r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
good_name = r["name"]
return good_name | [
"def",
"proper_case",
"(",
"package_name",
")",
":",
"# Hit the simple API.",
"r",
"=",
"_get_requests_session",
"(",
")",
".",
"get",
"(",
"\"https://pypi.org/pypi/{0}/json\"",
".",
"format",
"(",
"package_name",
")",
",",
"timeout",
"=",
"0.3",
",",
"stream",
"=",
"True",
")",
"if",
"not",
"r",
".",
"ok",
":",
"raise",
"IOError",
"(",
"\"Unable to find package {0} in PyPI repository.\"",
".",
"format",
"(",
"package_name",
")",
")",
"r",
"=",
"parse",
".",
"parse",
"(",
"\"https://pypi.org/pypi/{name}/json\"",
",",
"r",
".",
"url",
")",
"good_name",
"=",
"r",
"[",
"\"name\"",
"]",
"return",
"good_name"
] | Properly case project name from pypi.org. | [
"Properly",
"case",
"project",
"name",
"from",
"pypi",
".",
"org",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1277-L1290 |
24,909 | pypa/pipenv | pipenv/utils.py | find_windows_executable | def find_windows_executable(bin_path, exe_name):
"""Given an executable name, search the given location for an executable"""
requested_path = get_windows_path(bin_path, exe_name)
if os.path.isfile(requested_path):
return requested_path
try:
pathext = os.environ["PATHEXT"]
except KeyError:
pass
else:
for ext in pathext.split(os.pathsep):
path = get_windows_path(bin_path, exe_name + ext.strip().lower())
if os.path.isfile(path):
return path
return find_executable(exe_name) | python | def find_windows_executable(bin_path, exe_name):
"""Given an executable name, search the given location for an executable"""
requested_path = get_windows_path(bin_path, exe_name)
if os.path.isfile(requested_path):
return requested_path
try:
pathext = os.environ["PATHEXT"]
except KeyError:
pass
else:
for ext in pathext.split(os.pathsep):
path = get_windows_path(bin_path, exe_name + ext.strip().lower())
if os.path.isfile(path):
return path
return find_executable(exe_name) | [
"def",
"find_windows_executable",
"(",
"bin_path",
",",
"exe_name",
")",
":",
"requested_path",
"=",
"get_windows_path",
"(",
"bin_path",
",",
"exe_name",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"requested_path",
")",
":",
"return",
"requested_path",
"try",
":",
"pathext",
"=",
"os",
".",
"environ",
"[",
"\"PATHEXT\"",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"for",
"ext",
"in",
"pathext",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"path",
"=",
"get_windows_path",
"(",
"bin_path",
",",
"exe_name",
"+",
"ext",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"path",
"return",
"find_executable",
"(",
"exe_name",
")"
] | Given an executable name, search the given location for an executable | [
"Given",
"an",
"executable",
"name",
"search",
"the",
"given",
"location",
"for",
"an",
"executable"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1300-L1316 |
24,910 | pypa/pipenv | pipenv/utils.py | get_canonical_names | def get_canonical_names(packages):
"""Canonicalize a list of packages and return a set of canonical names"""
from .vendor.packaging.utils import canonicalize_name
if not isinstance(packages, Sequence):
if not isinstance(packages, six.string_types):
return packages
packages = [packages]
return set([canonicalize_name(pkg) for pkg in packages if pkg]) | python | def get_canonical_names(packages):
"""Canonicalize a list of packages and return a set of canonical names"""
from .vendor.packaging.utils import canonicalize_name
if not isinstance(packages, Sequence):
if not isinstance(packages, six.string_types):
return packages
packages = [packages]
return set([canonicalize_name(pkg) for pkg in packages if pkg]) | [
"def",
"get_canonical_names",
"(",
"packages",
")",
":",
"from",
".",
"vendor",
".",
"packaging",
".",
"utils",
"import",
"canonicalize_name",
"if",
"not",
"isinstance",
"(",
"packages",
",",
"Sequence",
")",
":",
"if",
"not",
"isinstance",
"(",
"packages",
",",
"six",
".",
"string_types",
")",
":",
"return",
"packages",
"packages",
"=",
"[",
"packages",
"]",
"return",
"set",
"(",
"[",
"canonicalize_name",
"(",
"pkg",
")",
"for",
"pkg",
"in",
"packages",
"if",
"pkg",
"]",
")"
] | Canonicalize a list of packages and return a set of canonical names | [
"Canonicalize",
"a",
"list",
"of",
"packages",
"and",
"return",
"a",
"set",
"of",
"canonical",
"names"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1337-L1345 |
24,911 | pypa/pipenv | pipenv/utils.py | download_file | def download_file(url, filename):
"""Downloads file from url to a path with 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) | python | def download_file(url, filename):
"""Downloads file from url to a path with 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) | [
"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 | [
"Downloads",
"file",
"from",
"url",
"to",
"a",
"path",
"with",
"filename"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1451-L1458 |
24,912 | pypa/pipenv | pipenv/utils.py | normalize_drive | def normalize_drive(path):
"""Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218>
"""
if os.name != "nt" or not isinstance(path, six.string_types):
return path
drive, tail = os.path.splitdrive(path)
# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.
if drive.islower() and len(drive) == 2 and drive[1] == ":":
return "{}{}".format(drive.upper(), tail)
return path | python | def normalize_drive(path):
"""Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218>
"""
if os.name != "nt" or not isinstance(path, six.string_types):
return path
drive, tail = os.path.splitdrive(path)
# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.
if drive.islower() and len(drive) == 2 and drive[1] == ":":
return "{}{}".format(drive.upper(), tail)
return path | [
"def",
"normalize_drive",
"(",
"path",
")",
":",
"if",
"os",
".",
"name",
"!=",
"\"nt\"",
"or",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"path",
"drive",
",",
"tail",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.",
"if",
"drive",
".",
"islower",
"(",
")",
"and",
"len",
"(",
"drive",
")",
"==",
"2",
"and",
"drive",
"[",
"1",
"]",
"==",
"\":\"",
":",
"return",
"\"{}{}\"",
".",
"format",
"(",
"drive",
".",
"upper",
"(",
")",
",",
"tail",
")",
"return",
"path"
] | Normalize drive in path so they stay consistent.
This currently only affects local drives on Windows, which can be
identified with either upper or lower cased drive names. The case is
always converted to uppercase because it seems to be preferred.
See: <https://github.com/pypa/pipenv/issues/1218> | [
"Normalize",
"drive",
"in",
"path",
"so",
"they",
"stay",
"consistent",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1461-L1478 |
24,913 | pypa/pipenv | pipenv/utils.py | safe_expandvars | def safe_expandvars(value):
"""Call os.path.expandvars if value is a string, otherwise do nothing.
"""
if isinstance(value, six.string_types):
return os.path.expandvars(value)
return value | python | def safe_expandvars(value):
"""Call os.path.expandvars if value is a string, otherwise do nothing.
"""
if isinstance(value, six.string_types):
return os.path.expandvars(value)
return value | [
"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. | [
"Call",
"os",
".",
"path",
".",
"expandvars",
"if",
"value",
"is",
"a",
"string",
"otherwise",
"do",
"nothing",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1539-L1544 |
24,914 | pypa/pipenv | pipenv/utils.py | translate_markers | def translate_markers(pipfile_entry):
"""Take a pipfile entry and normalize its markers
Provide a pipfile entry which may have 'markers' as a key or it may have
any valid key from `packaging.markers.marker_context.keys()` and standardize
the format into {'markers': 'key == "some_value"'}.
:param pipfile_entry: A dictionariy of keys and values representing a pipfile entry
:type pipfile_entry: dict
:returns: A normalized dictionary with cleaned marker entries
"""
if not isinstance(pipfile_entry, Mapping):
raise TypeError("Entry is not a pipfile formatted mapping.")
from .vendor.distlib.markers import DEFAULT_CONTEXT as marker_context
from .vendor.packaging.markers import Marker
from .vendor.vistir.misc import dedup
allowed_marker_keys = ["markers"] + [k for k in marker_context.keys()]
provided_keys = list(pipfile_entry.keys()) if hasattr(pipfile_entry, "keys") else []
pipfile_markers = [k for k in provided_keys if k in allowed_marker_keys]
new_pipfile = dict(pipfile_entry).copy()
marker_set = set()
if "markers" in new_pipfile:
marker = str(Marker(new_pipfile.pop("markers")))
if 'extra' not in marker:
marker_set.add(marker)
for m in pipfile_markers:
entry = "{0}".format(pipfile_entry[m])
if m != "markers":
marker_set.add(str(Marker("{0}{1}".format(m, entry))))
new_pipfile.pop(m)
if marker_set:
new_pipfile["markers"] = str(Marker(" or ".join(
"{0}".format(s) if " and " in s else s
for s in sorted(dedup(marker_set))
))).replace('"', "'")
return new_pipfile | python | def translate_markers(pipfile_entry):
"""Take a pipfile entry and normalize its markers
Provide a pipfile entry which may have 'markers' as a key or it may have
any valid key from `packaging.markers.marker_context.keys()` and standardize
the format into {'markers': 'key == "some_value"'}.
:param pipfile_entry: A dictionariy of keys and values representing a pipfile entry
:type pipfile_entry: dict
:returns: A normalized dictionary with cleaned marker entries
"""
if not isinstance(pipfile_entry, Mapping):
raise TypeError("Entry is not a pipfile formatted mapping.")
from .vendor.distlib.markers import DEFAULT_CONTEXT as marker_context
from .vendor.packaging.markers import Marker
from .vendor.vistir.misc import dedup
allowed_marker_keys = ["markers"] + [k for k in marker_context.keys()]
provided_keys = list(pipfile_entry.keys()) if hasattr(pipfile_entry, "keys") else []
pipfile_markers = [k for k in provided_keys if k in allowed_marker_keys]
new_pipfile = dict(pipfile_entry).copy()
marker_set = set()
if "markers" in new_pipfile:
marker = str(Marker(new_pipfile.pop("markers")))
if 'extra' not in marker:
marker_set.add(marker)
for m in pipfile_markers:
entry = "{0}".format(pipfile_entry[m])
if m != "markers":
marker_set.add(str(Marker("{0}{1}".format(m, entry))))
new_pipfile.pop(m)
if marker_set:
new_pipfile["markers"] = str(Marker(" or ".join(
"{0}".format(s) if " and " in s else s
for s in sorted(dedup(marker_set))
))).replace('"', "'")
return new_pipfile | [
"def",
"translate_markers",
"(",
"pipfile_entry",
")",
":",
"if",
"not",
"isinstance",
"(",
"pipfile_entry",
",",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"\"Entry is not a pipfile formatted mapping.\"",
")",
"from",
".",
"vendor",
".",
"distlib",
".",
"markers",
"import",
"DEFAULT_CONTEXT",
"as",
"marker_context",
"from",
".",
"vendor",
".",
"packaging",
".",
"markers",
"import",
"Marker",
"from",
".",
"vendor",
".",
"vistir",
".",
"misc",
"import",
"dedup",
"allowed_marker_keys",
"=",
"[",
"\"markers\"",
"]",
"+",
"[",
"k",
"for",
"k",
"in",
"marker_context",
".",
"keys",
"(",
")",
"]",
"provided_keys",
"=",
"list",
"(",
"pipfile_entry",
".",
"keys",
"(",
")",
")",
"if",
"hasattr",
"(",
"pipfile_entry",
",",
"\"keys\"",
")",
"else",
"[",
"]",
"pipfile_markers",
"=",
"[",
"k",
"for",
"k",
"in",
"provided_keys",
"if",
"k",
"in",
"allowed_marker_keys",
"]",
"new_pipfile",
"=",
"dict",
"(",
"pipfile_entry",
")",
".",
"copy",
"(",
")",
"marker_set",
"=",
"set",
"(",
")",
"if",
"\"markers\"",
"in",
"new_pipfile",
":",
"marker",
"=",
"str",
"(",
"Marker",
"(",
"new_pipfile",
".",
"pop",
"(",
"\"markers\"",
")",
")",
")",
"if",
"'extra'",
"not",
"in",
"marker",
":",
"marker_set",
".",
"add",
"(",
"marker",
")",
"for",
"m",
"in",
"pipfile_markers",
":",
"entry",
"=",
"\"{0}\"",
".",
"format",
"(",
"pipfile_entry",
"[",
"m",
"]",
")",
"if",
"m",
"!=",
"\"markers\"",
":",
"marker_set",
".",
"add",
"(",
"str",
"(",
"Marker",
"(",
"\"{0}{1}\"",
".",
"format",
"(",
"m",
",",
"entry",
")",
")",
")",
")",
"new_pipfile",
".",
"pop",
"(",
"m",
")",
"if",
"marker_set",
":",
"new_pipfile",
"[",
"\"markers\"",
"]",
"=",
"str",
"(",
"Marker",
"(",
"\" or \"",
".",
"join",
"(",
"\"{0}\"",
".",
"format",
"(",
"s",
")",
"if",
"\" and \"",
"in",
"s",
"else",
"s",
"for",
"s",
"in",
"sorted",
"(",
"dedup",
"(",
"marker_set",
")",
")",
")",
")",
")",
".",
"replace",
"(",
"'\"'",
",",
"\"'\"",
")",
"return",
"new_pipfile"
] | Take a pipfile entry and normalize its markers
Provide a pipfile entry which may have 'markers' as a key or it may have
any valid key from `packaging.markers.marker_context.keys()` and standardize
the format into {'markers': 'key == "some_value"'}.
:param pipfile_entry: A dictionariy of keys and values representing a pipfile entry
:type pipfile_entry: dict
:returns: A normalized dictionary with cleaned marker entries | [
"Take",
"a",
"pipfile",
"entry",
"and",
"normalize",
"its",
"markers"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1597-L1633 |
24,915 | pypa/pipenv | pipenv/utils.py | is_virtual_environment | def is_virtual_environment(path):
"""Check if a given path is a virtual environment's root.
This is done by checking if the directory contains a Python executable in
its bin/Scripts directory. Not technically correct, but good enough for
general usage.
"""
if not path.is_dir():
return False
for bindir_name in ('bin', 'Scripts'):
for python in path.joinpath(bindir_name).glob('python*'):
try:
exeness = python.is_file() and os.access(str(python), os.X_OK)
except OSError:
exeness = False
if exeness:
return True
return False | python | def is_virtual_environment(path):
"""Check if a given path is a virtual environment's root.
This is done by checking if the directory contains a Python executable in
its bin/Scripts directory. Not technically correct, but good enough for
general usage.
"""
if not path.is_dir():
return False
for bindir_name in ('bin', 'Scripts'):
for python in path.joinpath(bindir_name).glob('python*'):
try:
exeness = python.is_file() and os.access(str(python), os.X_OK)
except OSError:
exeness = False
if exeness:
return True
return False | [
"def",
"is_virtual_environment",
"(",
"path",
")",
":",
"if",
"not",
"path",
".",
"is_dir",
"(",
")",
":",
"return",
"False",
"for",
"bindir_name",
"in",
"(",
"'bin'",
",",
"'Scripts'",
")",
":",
"for",
"python",
"in",
"path",
".",
"joinpath",
"(",
"bindir_name",
")",
".",
"glob",
"(",
"'python*'",
")",
":",
"try",
":",
"exeness",
"=",
"python",
".",
"is_file",
"(",
")",
"and",
"os",
".",
"access",
"(",
"str",
"(",
"python",
")",
",",
"os",
".",
"X_OK",
")",
"except",
"OSError",
":",
"exeness",
"=",
"False",
"if",
"exeness",
":",
"return",
"True",
"return",
"False"
] | Check if a given path is a virtual environment's root.
This is done by checking if the directory contains a Python executable in
its bin/Scripts directory. Not technically correct, but good enough for
general usage. | [
"Check",
"if",
"a",
"given",
"path",
"is",
"a",
"virtual",
"environment",
"s",
"root",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1707-L1724 |
24,916 | pypa/pipenv | pipenv/utils.py | sys_version | def sys_version(version_tuple):
"""
Set a temporary sys.version_info tuple
:param version_tuple: a fake sys.version_info tuple
"""
old_version = sys.version_info
sys.version_info = version_tuple
yield
sys.version_info = old_version | python | def sys_version(version_tuple):
"""
Set a temporary sys.version_info tuple
:param version_tuple: a fake sys.version_info tuple
"""
old_version = sys.version_info
sys.version_info = version_tuple
yield
sys.version_info = old_version | [
"def",
"sys_version",
"(",
"version_tuple",
")",
":",
"old_version",
"=",
"sys",
".",
"version_info",
"sys",
".",
"version_info",
"=",
"version_tuple",
"yield",
"sys",
".",
"version_info",
"=",
"old_version"
] | Set a temporary sys.version_info tuple
:param version_tuple: a fake sys.version_info tuple | [
"Set",
"a",
"temporary",
"sys",
".",
"version_info",
"tuple"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1785-L1795 |
24,917 | pypa/pipenv | pipenv/utils.py | is_url_equal | def is_url_equal(url, other_url):
# type: (str, str) -> bool
"""
Compare two urls by scheme, host, and path, ignoring auth
:param str url: The initial URL to compare
:param str url: Second url to compare to the first
:return: Whether the URLs are equal without **auth**, **query**, and **fragment**
:rtype: bool
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://user2:pass2@mydomain.com/some/path")
True
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://mydomain.com/some?some_query")
False
"""
if not isinstance(url, six.string_types):
raise TypeError("Expected string for url, received {0!r}".format(url))
if not isinstance(other_url, six.string_types):
raise TypeError("Expected string for url, received {0!r}".format(other_url))
parsed_url = urllib3_util.parse_url(url)
parsed_other_url = urllib3_util.parse_url(other_url)
unparsed = parsed_url._replace(auth=None, query=None, fragment=None).url
unparsed_other = parsed_other_url._replace(auth=None, query=None, fragment=None).url
return unparsed == unparsed_other | python | def is_url_equal(url, other_url):
# type: (str, str) -> bool
"""
Compare two urls by scheme, host, and path, ignoring auth
:param str url: The initial URL to compare
:param str url: Second url to compare to the first
:return: Whether the URLs are equal without **auth**, **query**, and **fragment**
:rtype: bool
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://user2:pass2@mydomain.com/some/path")
True
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://mydomain.com/some?some_query")
False
"""
if not isinstance(url, six.string_types):
raise TypeError("Expected string for url, received {0!r}".format(url))
if not isinstance(other_url, six.string_types):
raise TypeError("Expected string for url, received {0!r}".format(other_url))
parsed_url = urllib3_util.parse_url(url)
parsed_other_url = urllib3_util.parse_url(other_url)
unparsed = parsed_url._replace(auth=None, query=None, fragment=None).url
unparsed_other = parsed_other_url._replace(auth=None, query=None, fragment=None).url
return unparsed == unparsed_other | [
"def",
"is_url_equal",
"(",
"url",
",",
"other_url",
")",
":",
"# type: (str, str) -> bool",
"if",
"not",
"isinstance",
"(",
"url",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string for url, received {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"if",
"not",
"isinstance",
"(",
"other_url",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string for url, received {0!r}\"",
".",
"format",
"(",
"other_url",
")",
")",
"parsed_url",
"=",
"urllib3_util",
".",
"parse_url",
"(",
"url",
")",
"parsed_other_url",
"=",
"urllib3_util",
".",
"parse_url",
"(",
"other_url",
")",
"unparsed",
"=",
"parsed_url",
".",
"_replace",
"(",
"auth",
"=",
"None",
",",
"query",
"=",
"None",
",",
"fragment",
"=",
"None",
")",
".",
"url",
"unparsed_other",
"=",
"parsed_other_url",
".",
"_replace",
"(",
"auth",
"=",
"None",
",",
"query",
"=",
"None",
",",
"fragment",
"=",
"None",
")",
".",
"url",
"return",
"unparsed",
"==",
"unparsed_other"
] | Compare two urls by scheme, host, and path, ignoring auth
:param str url: The initial URL to compare
:param str url: Second url to compare to the first
:return: Whether the URLs are equal without **auth**, **query**, and **fragment**
:rtype: bool
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://user2:pass2@mydomain.com/some/path")
True
>>> is_url_equal("https://user:pass@mydomain.com/some/path?some_query",
"https://mydomain.com/some?some_query")
False | [
"Compare",
"two",
"urls",
"by",
"scheme",
"host",
"and",
"path",
"ignoring",
"auth"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1811-L1837 |
24,918 | pypa/pipenv | pipenv/utils.py | find_python | def find_python(finder, line=None):
"""
Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python
:param finder: A :class:`pythonfinder.Finder` instance to use for searching
:type finder: :class:pythonfinder.Finder`
:param str line: A version, path, name, or nothing, defaults to None
:return: A path to python
:rtype: str
"""
if line and not isinstance(line, six.string_types):
raise TypeError(
"Invalid python search type: expected string, received {0!r}".format(line)
)
if line and os.path.isabs(line):
if os.name == "nt":
line = posixpath.join(*line.split(os.path.sep))
return line
if not finder:
from pipenv.vendor.pythonfinder import Finder
finder = Finder(global_search=True)
if not line:
result = next(iter(finder.find_all_python_versions()), None)
elif line and line[0].isdigit() or re.match(r'[\d\.]+', line):
result = finder.find_python_version(line)
else:
result = finder.find_python_version(name=line)
if not result:
result = finder.which(line)
if not result and not line.startswith("python"):
line = "python{0}".format(line)
result = find_python(finder, line)
if not result:
result = next(iter(finder.find_all_python_versions()), None)
if result:
if not isinstance(result, six.string_types):
return result.path.as_posix()
return result
return | python | def find_python(finder, line=None):
"""
Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python
:param finder: A :class:`pythonfinder.Finder` instance to use for searching
:type finder: :class:pythonfinder.Finder`
:param str line: A version, path, name, or nothing, defaults to None
:return: A path to python
:rtype: str
"""
if line and not isinstance(line, six.string_types):
raise TypeError(
"Invalid python search type: expected string, received {0!r}".format(line)
)
if line and os.path.isabs(line):
if os.name == "nt":
line = posixpath.join(*line.split(os.path.sep))
return line
if not finder:
from pipenv.vendor.pythonfinder import Finder
finder = Finder(global_search=True)
if not line:
result = next(iter(finder.find_all_python_versions()), None)
elif line and line[0].isdigit() or re.match(r'[\d\.]+', line):
result = finder.find_python_version(line)
else:
result = finder.find_python_version(name=line)
if not result:
result = finder.which(line)
if not result and not line.startswith("python"):
line = "python{0}".format(line)
result = find_python(finder, line)
if not result:
result = next(iter(finder.find_all_python_versions()), None)
if result:
if not isinstance(result, six.string_types):
return result.path.as_posix()
return result
return | [
"def",
"find_python",
"(",
"finder",
",",
"line",
"=",
"None",
")",
":",
"if",
"line",
"and",
"not",
"isinstance",
"(",
"line",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid python search type: expected string, received {0!r}\"",
".",
"format",
"(",
"line",
")",
")",
"if",
"line",
"and",
"os",
".",
"path",
".",
"isabs",
"(",
"line",
")",
":",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"line",
"=",
"posixpath",
".",
"join",
"(",
"*",
"line",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"return",
"line",
"if",
"not",
"finder",
":",
"from",
"pipenv",
".",
"vendor",
".",
"pythonfinder",
"import",
"Finder",
"finder",
"=",
"Finder",
"(",
"global_search",
"=",
"True",
")",
"if",
"not",
"line",
":",
"result",
"=",
"next",
"(",
"iter",
"(",
"finder",
".",
"find_all_python_versions",
"(",
")",
")",
",",
"None",
")",
"elif",
"line",
"and",
"line",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"or",
"re",
".",
"match",
"(",
"r'[\\d\\.]+'",
",",
"line",
")",
":",
"result",
"=",
"finder",
".",
"find_python_version",
"(",
"line",
")",
"else",
":",
"result",
"=",
"finder",
".",
"find_python_version",
"(",
"name",
"=",
"line",
")",
"if",
"not",
"result",
":",
"result",
"=",
"finder",
".",
"which",
"(",
"line",
")",
"if",
"not",
"result",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"python\"",
")",
":",
"line",
"=",
"\"python{0}\"",
".",
"format",
"(",
"line",
")",
"result",
"=",
"find_python",
"(",
"finder",
",",
"line",
")",
"if",
"not",
"result",
":",
"result",
"=",
"next",
"(",
"iter",
"(",
"finder",
".",
"find_all_python_versions",
"(",
")",
")",
",",
"None",
")",
"if",
"result",
":",
"if",
"not",
"isinstance",
"(",
"result",
",",
"six",
".",
"string_types",
")",
":",
"return",
"result",
".",
"path",
".",
"as_posix",
"(",
")",
"return",
"result",
"return"
] | Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python
:param finder: A :class:`pythonfinder.Finder` instance to use for searching
:type finder: :class:pythonfinder.Finder`
:param str line: A version, path, name, or nothing, defaults to None
:return: A path to python
:rtype: str | [
"Given",
"a",
"pythonfinder",
".",
"Finder",
"instance",
"and",
"an",
"optional",
"line",
"find",
"a",
"corresponding",
"python"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1877-L1916 |
24,919 | pypa/pipenv | pipenv/utils.py | is_python_command | def is_python_command(line):
"""
Given an input, checks whether the input is a request for python or notself.
This can be a version, a python runtime name, or a generic 'python' or 'pythonX.Y'
:param str line: A potential request to find python
:returns: Whether the line is a python lookup
:rtype: bool
"""
if not isinstance(line, six.string_types):
raise TypeError("Not a valid command to check: {0!r}".format(line))
from pipenv.vendor.pythonfinder.utils import PYTHON_IMPLEMENTATIONS
is_version = re.match(r'[\d\.]+', line)
if (line.startswith("python") or is_version or
any(line.startswith(v) for v in PYTHON_IMPLEMENTATIONS)):
return True
# we are less sure about this but we can guess
if line.startswith("py"):
return True
return False | python | def is_python_command(line):
"""
Given an input, checks whether the input is a request for python or notself.
This can be a version, a python runtime name, or a generic 'python' or 'pythonX.Y'
:param str line: A potential request to find python
:returns: Whether the line is a python lookup
:rtype: bool
"""
if not isinstance(line, six.string_types):
raise TypeError("Not a valid command to check: {0!r}".format(line))
from pipenv.vendor.pythonfinder.utils import PYTHON_IMPLEMENTATIONS
is_version = re.match(r'[\d\.]+', line)
if (line.startswith("python") or is_version or
any(line.startswith(v) for v in PYTHON_IMPLEMENTATIONS)):
return True
# we are less sure about this but we can guess
if line.startswith("py"):
return True
return False | [
"def",
"is_python_command",
"(",
"line",
")",
":",
"if",
"not",
"isinstance",
"(",
"line",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Not a valid command to check: {0!r}\"",
".",
"format",
"(",
"line",
")",
")",
"from",
"pipenv",
".",
"vendor",
".",
"pythonfinder",
".",
"utils",
"import",
"PYTHON_IMPLEMENTATIONS",
"is_version",
"=",
"re",
".",
"match",
"(",
"r'[\\d\\.]+'",
",",
"line",
")",
"if",
"(",
"line",
".",
"startswith",
"(",
"\"python\"",
")",
"or",
"is_version",
"or",
"any",
"(",
"line",
".",
"startswith",
"(",
"v",
")",
"for",
"v",
"in",
"PYTHON_IMPLEMENTATIONS",
")",
")",
":",
"return",
"True",
"# we are less sure about this but we can guess",
"if",
"line",
".",
"startswith",
"(",
"\"py\"",
")",
":",
"return",
"True",
"return",
"False"
] | Given an input, checks whether the input is a request for python or notself.
This can be a version, a python runtime name, or a generic 'python' or 'pythonX.Y'
:param str line: A potential request to find python
:returns: Whether the line is a python lookup
:rtype: bool | [
"Given",
"an",
"input",
"checks",
"whether",
"the",
"input",
"is",
"a",
"request",
"for",
"python",
"or",
"notself",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1919-L1941 |
24,920 | pypa/pipenv | pipenv/utils.py | Resolver.get_hash | def get_hash(self, ireq, ireq_hashes=None):
"""
Retrieve hashes for a specific ``InstallRequirement`` instance.
:param ireq: An ``InstallRequirement`` to retrieve hashes for
:type ireq: :class:`~pip_shims.InstallRequirement`
:return: A set of hashes.
:rtype: Set
"""
# We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources
# PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH
# RESOLVED. The resolver will pull hashes from PyPI and only from PyPI.
# The entire purpose of this approach is to include missing hashes.
# This fixes a race condition in resolution for missing dependency caches
# see pypa/pipenv#3289
if not self._should_include_hash(ireq):
return set()
elif self._should_include_hash(ireq) and (
not ireq_hashes or ireq.link.scheme == "file"
):
if not ireq_hashes:
ireq_hashes = set()
new_hashes = self.resolver.repository._hash_cache.get_hash(ireq.link)
ireq_hashes = add_to_set(ireq_hashes, new_hashes)
else:
ireq_hashes = set(ireq_hashes)
# The _ONLY CASE_ where we flat out set the value is if it isn't present
# It's a set, so otherwise we *always* need to do a union update
if ireq not in self.hashes:
return ireq_hashes
else:
return self.hashes[ireq] | ireq_hashes | python | def get_hash(self, ireq, ireq_hashes=None):
"""
Retrieve hashes for a specific ``InstallRequirement`` instance.
:param ireq: An ``InstallRequirement`` to retrieve hashes for
:type ireq: :class:`~pip_shims.InstallRequirement`
:return: A set of hashes.
:rtype: Set
"""
# We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources
# PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH
# RESOLVED. The resolver will pull hashes from PyPI and only from PyPI.
# The entire purpose of this approach is to include missing hashes.
# This fixes a race condition in resolution for missing dependency caches
# see pypa/pipenv#3289
if not self._should_include_hash(ireq):
return set()
elif self._should_include_hash(ireq) and (
not ireq_hashes or ireq.link.scheme == "file"
):
if not ireq_hashes:
ireq_hashes = set()
new_hashes = self.resolver.repository._hash_cache.get_hash(ireq.link)
ireq_hashes = add_to_set(ireq_hashes, new_hashes)
else:
ireq_hashes = set(ireq_hashes)
# The _ONLY CASE_ where we flat out set the value is if it isn't present
# It's a set, so otherwise we *always* need to do a union update
if ireq not in self.hashes:
return ireq_hashes
else:
return self.hashes[ireq] | ireq_hashes | [
"def",
"get_hash",
"(",
"self",
",",
"ireq",
",",
"ireq_hashes",
"=",
"None",
")",
":",
"# We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources",
"# PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH",
"# RESOLVED. The resolver will pull hashes from PyPI and only from PyPI.",
"# The entire purpose of this approach is to include missing hashes.",
"# This fixes a race condition in resolution for missing dependency caches",
"# see pypa/pipenv#3289",
"if",
"not",
"self",
".",
"_should_include_hash",
"(",
"ireq",
")",
":",
"return",
"set",
"(",
")",
"elif",
"self",
".",
"_should_include_hash",
"(",
"ireq",
")",
"and",
"(",
"not",
"ireq_hashes",
"or",
"ireq",
".",
"link",
".",
"scheme",
"==",
"\"file\"",
")",
":",
"if",
"not",
"ireq_hashes",
":",
"ireq_hashes",
"=",
"set",
"(",
")",
"new_hashes",
"=",
"self",
".",
"resolver",
".",
"repository",
".",
"_hash_cache",
".",
"get_hash",
"(",
"ireq",
".",
"link",
")",
"ireq_hashes",
"=",
"add_to_set",
"(",
"ireq_hashes",
",",
"new_hashes",
")",
"else",
":",
"ireq_hashes",
"=",
"set",
"(",
"ireq_hashes",
")",
"# The _ONLY CASE_ where we flat out set the value is if it isn't present",
"# It's a set, so otherwise we *always* need to do a union update",
"if",
"ireq",
"not",
"in",
"self",
".",
"hashes",
":",
"return",
"ireq_hashes",
"else",
":",
"return",
"self",
".",
"hashes",
"[",
"ireq",
"]",
"|",
"ireq_hashes"
] | Retrieve hashes for a specific ``InstallRequirement`` instance.
:param ireq: An ``InstallRequirement`` to retrieve hashes for
:type ireq: :class:`~pip_shims.InstallRequirement`
:return: A set of hashes.
:rtype: Set | [
"Retrieve",
"hashes",
"for",
"a",
"specific",
"InstallRequirement",
"instance",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L682-L714 |
24,921 | pypa/pipenv | pipenv/vendor/shellingham/posix/__init__.py | _get_process_mapping | def _get_process_mapping():
"""Select a way to obtain process information from the system.
* `/proc` is used if supported.
* The system `ps` utility is used as a fallback option.
"""
for impl in (proc, ps):
try:
mapping = impl.get_process_mapping()
except EnvironmentError:
continue
return mapping
raise ShellDetectionFailure('compatible proc fs or ps utility is required') | python | def _get_process_mapping():
"""Select a way to obtain process information from the system.
* `/proc` is used if supported.
* The system `ps` utility is used as a fallback option.
"""
for impl in (proc, ps):
try:
mapping = impl.get_process_mapping()
except EnvironmentError:
continue
return mapping
raise ShellDetectionFailure('compatible proc fs or ps utility is required') | [
"def",
"_get_process_mapping",
"(",
")",
":",
"for",
"impl",
"in",
"(",
"proc",
",",
"ps",
")",
":",
"try",
":",
"mapping",
"=",
"impl",
".",
"get_process_mapping",
"(",
")",
"except",
"EnvironmentError",
":",
"continue",
"return",
"mapping",
"raise",
"ShellDetectionFailure",
"(",
"'compatible proc fs or ps utility is required'",
")"
] | Select a way to obtain process information from the system.
* `/proc` is used if supported.
* The system `ps` utility is used as a fallback option. | [
"Select",
"a",
"way",
"to",
"obtain",
"process",
"information",
"from",
"the",
"system",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/posix/__init__.py#L7-L19 |
24,922 | pypa/pipenv | pipenv/vendor/shellingham/posix/__init__.py | _get_login_shell | def _get_login_shell(proc_cmd):
"""Form shell information from the SHELL environment variable if possible.
"""
login_shell = os.environ.get('SHELL', '')
if login_shell:
proc_cmd = login_shell
else:
proc_cmd = proc_cmd[1:]
return (os.path.basename(proc_cmd).lower(), proc_cmd) | python | def _get_login_shell(proc_cmd):
"""Form shell information from the SHELL environment variable if possible.
"""
login_shell = os.environ.get('SHELL', '')
if login_shell:
proc_cmd = login_shell
else:
proc_cmd = proc_cmd[1:]
return (os.path.basename(proc_cmd).lower(), proc_cmd) | [
"def",
"_get_login_shell",
"(",
"proc_cmd",
")",
":",
"login_shell",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SHELL'",
",",
"''",
")",
"if",
"login_shell",
":",
"proc_cmd",
"=",
"login_shell",
"else",
":",
"proc_cmd",
"=",
"proc_cmd",
"[",
"1",
":",
"]",
"return",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"proc_cmd",
")",
".",
"lower",
"(",
")",
",",
"proc_cmd",
")"
] | Form shell information from the SHELL environment variable if possible. | [
"Form",
"shell",
"information",
"from",
"the",
"SHELL",
"environment",
"variable",
"if",
"possible",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/shellingham/posix/__init__.py#L39-L47 |
24,923 | pypa/pipenv | pipenv/vendor/requests/adapters.py | HTTPAdapter.init_poolmanager | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs) | python | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs) | [
"def",
"init_poolmanager",
"(",
"self",
",",
"connections",
",",
"maxsize",
",",
"block",
"=",
"DEFAULT_POOLBLOCK",
",",
"*",
"*",
"pool_kwargs",
")",
":",
"# save these values for pickling",
"self",
".",
"_pool_connections",
"=",
"connections",
"self",
".",
"_pool_maxsize",
"=",
"maxsize",
"self",
".",
"_pool_block",
"=",
"block",
"self",
".",
"poolmanager",
"=",
"PoolManager",
"(",
"num_pools",
"=",
"connections",
",",
"maxsize",
"=",
"maxsize",
",",
"block",
"=",
"block",
",",
"strict",
"=",
"True",
",",
"*",
"*",
"pool_kwargs",
")"
] | Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. | [
"Initializes",
"a",
"urllib3",
"PoolManager",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/adapters.py#L146-L164 |
24,924 | pypa/pipenv | pipenv/vendor/requests/adapters.py | HTTPAdapter.close | def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | python | def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"poolmanager",
".",
"clear",
"(",
")",
"for",
"proxy",
"in",
"self",
".",
"proxy_manager",
".",
"values",
"(",
")",
":",
"proxy",
".",
"clear",
"(",
")"
] | Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections. | [
"Disposes",
"of",
"any",
"internal",
"state",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/adapters.py#L319-L327 |
24,925 | pypa/pipenv | pipenv/vendor/requirementslib/utils.py | add_ssh_scheme_to_git_uri | def add_ssh_scheme_to_git_uri(uri):
# type: (S) -> S
"""Cleans VCS uris from pipenv.patched.notpip format"""
if isinstance(uri, six.string_types):
# Add scheme for parsing purposes, this is also what pip does
if uri.startswith("git+") and "://" not in uri:
uri = uri.replace("git+", "git+ssh://", 1)
parsed = urlparse(uri)
if ":" in parsed.netloc:
netloc, _, path_start = parsed.netloc.rpartition(":")
path = "/{0}{1}".format(path_start, parsed.path)
uri = urlunparse(parsed._replace(netloc=netloc, path=path))
return uri | python | def add_ssh_scheme_to_git_uri(uri):
# type: (S) -> S
"""Cleans VCS uris from pipenv.patched.notpip format"""
if isinstance(uri, six.string_types):
# Add scheme for parsing purposes, this is also what pip does
if uri.startswith("git+") and "://" not in uri:
uri = uri.replace("git+", "git+ssh://", 1)
parsed = urlparse(uri)
if ":" in parsed.netloc:
netloc, _, path_start = parsed.netloc.rpartition(":")
path = "/{0}{1}".format(path_start, parsed.path)
uri = urlunparse(parsed._replace(netloc=netloc, path=path))
return uri | [
"def",
"add_ssh_scheme_to_git_uri",
"(",
"uri",
")",
":",
"# type: (S) -> S",
"if",
"isinstance",
"(",
"uri",
",",
"six",
".",
"string_types",
")",
":",
"# Add scheme for parsing purposes, this is also what pip does",
"if",
"uri",
".",
"startswith",
"(",
"\"git+\"",
")",
"and",
"\"://\"",
"not",
"in",
"uri",
":",
"uri",
"=",
"uri",
".",
"replace",
"(",
"\"git+\"",
",",
"\"git+ssh://\"",
",",
"1",
")",
"parsed",
"=",
"urlparse",
"(",
"uri",
")",
"if",
"\":\"",
"in",
"parsed",
".",
"netloc",
":",
"netloc",
",",
"_",
",",
"path_start",
"=",
"parsed",
".",
"netloc",
".",
"rpartition",
"(",
"\":\"",
")",
"path",
"=",
"\"/{0}{1}\"",
".",
"format",
"(",
"path_start",
",",
"parsed",
".",
"path",
")",
"uri",
"=",
"urlunparse",
"(",
"parsed",
".",
"_replace",
"(",
"netloc",
"=",
"netloc",
",",
"path",
"=",
"path",
")",
")",
"return",
"uri"
] | Cleans VCS uris from pipenv.patched.notpip format | [
"Cleans",
"VCS",
"uris",
"from",
"pipenv",
".",
"patched",
".",
"notpip",
"format"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/utils.py#L133-L145 |
24,926 | pypa/pipenv | pipenv/vendor/requirementslib/utils.py | is_vcs | def is_vcs(pipfile_entry):
# type: (PipfileType) -> bool
"""Determine if dictionary entry from Pipfile is for a vcs dependency."""
if isinstance(pipfile_entry, Mapping):
return any(key for key in pipfile_entry.keys() if key in VCS_LIST)
elif isinstance(pipfile_entry, six.string_types):
if not is_valid_url(pipfile_entry) and pipfile_entry.startswith("git+"):
pipfile_entry = add_ssh_scheme_to_git_uri(pipfile_entry)
parsed_entry = urlsplit(pipfile_entry)
return parsed_entry.scheme in VCS_SCHEMES
return False | python | def is_vcs(pipfile_entry):
# type: (PipfileType) -> bool
"""Determine if dictionary entry from Pipfile is for a vcs dependency."""
if isinstance(pipfile_entry, Mapping):
return any(key for key in pipfile_entry.keys() if key in VCS_LIST)
elif isinstance(pipfile_entry, six.string_types):
if not is_valid_url(pipfile_entry) and pipfile_entry.startswith("git+"):
pipfile_entry = add_ssh_scheme_to_git_uri(pipfile_entry)
parsed_entry = urlsplit(pipfile_entry)
return parsed_entry.scheme in VCS_SCHEMES
return False | [
"def",
"is_vcs",
"(",
"pipfile_entry",
")",
":",
"# type: (PipfileType) -> bool",
"if",
"isinstance",
"(",
"pipfile_entry",
",",
"Mapping",
")",
":",
"return",
"any",
"(",
"key",
"for",
"key",
"in",
"pipfile_entry",
".",
"keys",
"(",
")",
"if",
"key",
"in",
"VCS_LIST",
")",
"elif",
"isinstance",
"(",
"pipfile_entry",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"is_valid_url",
"(",
"pipfile_entry",
")",
"and",
"pipfile_entry",
".",
"startswith",
"(",
"\"git+\"",
")",
":",
"pipfile_entry",
"=",
"add_ssh_scheme_to_git_uri",
"(",
"pipfile_entry",
")",
"parsed_entry",
"=",
"urlsplit",
"(",
"pipfile_entry",
")",
"return",
"parsed_entry",
".",
"scheme",
"in",
"VCS_SCHEMES",
"return",
"False"
] | Determine if dictionary entry from Pipfile is for a vcs dependency. | [
"Determine",
"if",
"dictionary",
"entry",
"from",
"Pipfile",
"is",
"for",
"a",
"vcs",
"dependency",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/utils.py#L148-L160 |
24,927 | pypa/pipenv | pipenv/vendor/requirementslib/utils.py | multi_split | def multi_split(s, split):
# type: (S, Iterable[S]) -> List[S]
"""Splits on multiple given separators."""
for r in split:
s = s.replace(r, "|")
return [i for i in s.split("|") if len(i) > 0] | python | def multi_split(s, split):
# type: (S, Iterable[S]) -> List[S]
"""Splits on multiple given separators."""
for r in split:
s = s.replace(r, "|")
return [i for i in s.split("|") if len(i) > 0] | [
"def",
"multi_split",
"(",
"s",
",",
"split",
")",
":",
"# type: (S, Iterable[S]) -> List[S]",
"for",
"r",
"in",
"split",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"r",
",",
"\"|\"",
")",
"return",
"[",
"i",
"for",
"i",
"in",
"s",
".",
"split",
"(",
"\"|\"",
")",
"if",
"len",
"(",
"i",
")",
">",
"0",
"]"
] | Splits on multiple given separators. | [
"Splits",
"on",
"multiple",
"given",
"separators",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/utils.py#L172-L177 |
24,928 | pypa/pipenv | pipenv/vendor/requirementslib/utils.py | convert_entry_to_path | def convert_entry_to_path(path):
# type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S
"""Convert a pipfile entry to a string"""
if not isinstance(path, Mapping):
raise TypeError("expecting a mapping, received {0!r}".format(path))
if not any(key in path for key in ["file", "path"]):
raise ValueError("missing path-like entry in supplied mapping {0!r}".format(path))
if "file" in path:
path = vistir.path.url_to_path(path["file"])
elif "path" in path:
path = path["path"]
return path | python | def convert_entry_to_path(path):
# type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S
"""Convert a pipfile entry to a string"""
if not isinstance(path, Mapping):
raise TypeError("expecting a mapping, received {0!r}".format(path))
if not any(key in path for key in ["file", "path"]):
raise ValueError("missing path-like entry in supplied mapping {0!r}".format(path))
if "file" in path:
path = vistir.path.url_to_path(path["file"])
elif "path" in path:
path = path["path"]
return path | [
"def",
"convert_entry_to_path",
"(",
"path",
")",
":",
"# type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S",
"if",
"not",
"isinstance",
"(",
"path",
",",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"\"expecting a mapping, received {0!r}\"",
".",
"format",
"(",
"path",
")",
")",
"if",
"not",
"any",
"(",
"key",
"in",
"path",
"for",
"key",
"in",
"[",
"\"file\"",
",",
"\"path\"",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"missing path-like entry in supplied mapping {0!r}\"",
".",
"format",
"(",
"path",
")",
")",
"if",
"\"file\"",
"in",
"path",
":",
"path",
"=",
"vistir",
".",
"path",
".",
"url_to_path",
"(",
"path",
"[",
"\"file\"",
"]",
")",
"elif",
"\"path\"",
"in",
"path",
":",
"path",
"=",
"path",
"[",
"\"path\"",
"]",
"return",
"path"
] | Convert a pipfile entry to a string | [
"Convert",
"a",
"pipfile",
"entry",
"to",
"a",
"string"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/utils.py#L187-L202 |
24,929 | pypa/pipenv | pipenv/patched/notpip/_internal/exceptions.py | HashMismatch._hash_comparison | def _hash_comparison(self):
"""
Return a comparison of actual and expected hash values.
Example::
Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
or 123451234512345123451234512345123451234512345
Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
"""
def hash_then_or(hash_name):
# For now, all the decent hashes have 6-char names, so we can get
# away with hard-coding space literals.
return chain([hash_name], repeat(' or'))
lines = []
for hash_name, expecteds in iteritems(self.allowed):
prefix = hash_then_or(hash_name)
lines.extend((' Expected %s %s' % (next(prefix), e))
for e in expecteds)
lines.append(' Got %s\n' %
self.gots[hash_name].hexdigest())
prefix = ' or'
return '\n'.join(lines) | python | def _hash_comparison(self):
"""
Return a comparison of actual and expected hash values.
Example::
Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
or 123451234512345123451234512345123451234512345
Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
"""
def hash_then_or(hash_name):
# For now, all the decent hashes have 6-char names, so we can get
# away with hard-coding space literals.
return chain([hash_name], repeat(' or'))
lines = []
for hash_name, expecteds in iteritems(self.allowed):
prefix = hash_then_or(hash_name)
lines.extend((' Expected %s %s' % (next(prefix), e))
for e in expecteds)
lines.append(' Got %s\n' %
self.gots[hash_name].hexdigest())
prefix = ' or'
return '\n'.join(lines) | [
"def",
"_hash_comparison",
"(",
"self",
")",
":",
"def",
"hash_then_or",
"(",
"hash_name",
")",
":",
"# For now, all the decent hashes have 6-char names, so we can get",
"# away with hard-coding space literals.",
"return",
"chain",
"(",
"[",
"hash_name",
"]",
",",
"repeat",
"(",
"' or'",
")",
")",
"lines",
"=",
"[",
"]",
"for",
"hash_name",
",",
"expecteds",
"in",
"iteritems",
"(",
"self",
".",
"allowed",
")",
":",
"prefix",
"=",
"hash_then_or",
"(",
"hash_name",
")",
"lines",
".",
"extend",
"(",
"(",
"' Expected %s %s'",
"%",
"(",
"next",
"(",
"prefix",
")",
",",
"e",
")",
")",
"for",
"e",
"in",
"expecteds",
")",
"lines",
".",
"append",
"(",
"' Got %s\\n'",
"%",
"self",
".",
"gots",
"[",
"hash_name",
"]",
".",
"hexdigest",
"(",
")",
")",
"prefix",
"=",
"' or'",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | Return a comparison of actual and expected hash values.
Example::
Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
or 123451234512345123451234512345123451234512345
Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef | [
"Return",
"a",
"comparison",
"of",
"actual",
"and",
"expected",
"hash",
"values",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/exceptions.py#L226-L250 |
24,930 | pypa/pipenv | pipenv/vendor/chardet/universaldetector.py | UniversalDetector.feed | def feed(self, byte_str):
"""
Takes a chunk of a document and feeds it through all of the relevant
charset probers.
After calling ``feed``, you can check the value of the ``done``
attribute to see if you need to continue feeding the
``UniversalDetector`` more data, or if it has made a prediction
(in the ``result`` attribute).
.. note::
You should always call ``close`` when you're done feeding in your
document if ``done`` is not already ``True``.
"""
if self.done:
return
if not len(byte_str):
return
if not isinstance(byte_str, bytearray):
byte_str = bytearray(byte_str)
# First check for known BOMs, since these are guaranteed to be correct
if not self._got_data:
# If the data starts with BOM, we know it is UTF
if byte_str.startswith(codecs.BOM_UTF8):
# EF BB BF UTF-8 with BOM
self.result = {'encoding': "UTF-8-SIG",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith((codecs.BOM_UTF32_LE,
codecs.BOM_UTF32_BE)):
# FF FE 00 00 UTF-32, little-endian BOM
# 00 00 FE FF UTF-32, big-endian BOM
self.result = {'encoding': "UTF-32",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith(b'\xFE\xFF\x00\x00'):
# FE FF 00 00 UCS-4, unusual octet order BOM (3412)
self.result = {'encoding': "X-ISO-10646-UCS-4-3412",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith(b'\x00\x00\xFF\xFE'):
# 00 00 FF FE UCS-4, unusual octet order BOM (2143)
self.result = {'encoding': "X-ISO-10646-UCS-4-2143",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)):
# FF FE UTF-16, little endian BOM
# FE FF UTF-16, big endian BOM
self.result = {'encoding': "UTF-16",
'confidence': 1.0,
'language': ''}
self._got_data = True
if self.result['encoding'] is not None:
self.done = True
return
# If none of those matched and we've only see ASCII so far, check
# for high bytes and escape sequences
if self._input_state == InputState.PURE_ASCII:
if self.HIGH_BYTE_DETECTOR.search(byte_str):
self._input_state = InputState.HIGH_BYTE
elif self._input_state == InputState.PURE_ASCII and \
self.ESC_DETECTOR.search(self._last_char + byte_str):
self._input_state = InputState.ESC_ASCII
self._last_char = byte_str[-1:]
# If we've seen escape sequences, use the EscCharSetProber, which
# uses a simple state machine to check for known escape sequences in
# HZ and ISO-2022 encodings, since those are the only encodings that
# use such sequences.
if self._input_state == InputState.ESC_ASCII:
if not self._esc_charset_prober:
self._esc_charset_prober = EscCharSetProber(self.lang_filter)
if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT:
self.result = {'encoding':
self._esc_charset_prober.charset_name,
'confidence':
self._esc_charset_prober.get_confidence(),
'language':
self._esc_charset_prober.language}
self.done = True
# If we've seen high bytes (i.e., those with values greater than 127),
# we need to do more complicated checks using all our multi-byte and
# single-byte probers that are left. The single-byte probers
# use character bigram distributions to determine the encoding, whereas
# the multi-byte probers use a combination of character unigram and
# bigram distributions.
elif self._input_state == InputState.HIGH_BYTE:
if not self._charset_probers:
self._charset_probers = [MBCSGroupProber(self.lang_filter)]
# If we're checking non-CJK encodings, use single-byte prober
if self.lang_filter & LanguageFilter.NON_CJK:
self._charset_probers.append(SBCSGroupProber())
self._charset_probers.append(Latin1Prober())
for prober in self._charset_probers:
if prober.feed(byte_str) == ProbingState.FOUND_IT:
self.result = {'encoding': prober.charset_name,
'confidence': prober.get_confidence(),
'language': prober.language}
self.done = True
break
if self.WIN_BYTE_DETECTOR.search(byte_str):
self._has_win_bytes = True | python | def feed(self, byte_str):
"""
Takes a chunk of a document and feeds it through all of the relevant
charset probers.
After calling ``feed``, you can check the value of the ``done``
attribute to see if you need to continue feeding the
``UniversalDetector`` more data, or if it has made a prediction
(in the ``result`` attribute).
.. note::
You should always call ``close`` when you're done feeding in your
document if ``done`` is not already ``True``.
"""
if self.done:
return
if not len(byte_str):
return
if not isinstance(byte_str, bytearray):
byte_str = bytearray(byte_str)
# First check for known BOMs, since these are guaranteed to be correct
if not self._got_data:
# If the data starts with BOM, we know it is UTF
if byte_str.startswith(codecs.BOM_UTF8):
# EF BB BF UTF-8 with BOM
self.result = {'encoding': "UTF-8-SIG",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith((codecs.BOM_UTF32_LE,
codecs.BOM_UTF32_BE)):
# FF FE 00 00 UTF-32, little-endian BOM
# 00 00 FE FF UTF-32, big-endian BOM
self.result = {'encoding': "UTF-32",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith(b'\xFE\xFF\x00\x00'):
# FE FF 00 00 UCS-4, unusual octet order BOM (3412)
self.result = {'encoding': "X-ISO-10646-UCS-4-3412",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith(b'\x00\x00\xFF\xFE'):
# 00 00 FF FE UCS-4, unusual octet order BOM (2143)
self.result = {'encoding': "X-ISO-10646-UCS-4-2143",
'confidence': 1.0,
'language': ''}
elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)):
# FF FE UTF-16, little endian BOM
# FE FF UTF-16, big endian BOM
self.result = {'encoding': "UTF-16",
'confidence': 1.0,
'language': ''}
self._got_data = True
if self.result['encoding'] is not None:
self.done = True
return
# If none of those matched and we've only see ASCII so far, check
# for high bytes and escape sequences
if self._input_state == InputState.PURE_ASCII:
if self.HIGH_BYTE_DETECTOR.search(byte_str):
self._input_state = InputState.HIGH_BYTE
elif self._input_state == InputState.PURE_ASCII and \
self.ESC_DETECTOR.search(self._last_char + byte_str):
self._input_state = InputState.ESC_ASCII
self._last_char = byte_str[-1:]
# If we've seen escape sequences, use the EscCharSetProber, which
# uses a simple state machine to check for known escape sequences in
# HZ and ISO-2022 encodings, since those are the only encodings that
# use such sequences.
if self._input_state == InputState.ESC_ASCII:
if not self._esc_charset_prober:
self._esc_charset_prober = EscCharSetProber(self.lang_filter)
if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT:
self.result = {'encoding':
self._esc_charset_prober.charset_name,
'confidence':
self._esc_charset_prober.get_confidence(),
'language':
self._esc_charset_prober.language}
self.done = True
# If we've seen high bytes (i.e., those with values greater than 127),
# we need to do more complicated checks using all our multi-byte and
# single-byte probers that are left. The single-byte probers
# use character bigram distributions to determine the encoding, whereas
# the multi-byte probers use a combination of character unigram and
# bigram distributions.
elif self._input_state == InputState.HIGH_BYTE:
if not self._charset_probers:
self._charset_probers = [MBCSGroupProber(self.lang_filter)]
# If we're checking non-CJK encodings, use single-byte prober
if self.lang_filter & LanguageFilter.NON_CJK:
self._charset_probers.append(SBCSGroupProber())
self._charset_probers.append(Latin1Prober())
for prober in self._charset_probers:
if prober.feed(byte_str) == ProbingState.FOUND_IT:
self.result = {'encoding': prober.charset_name,
'confidence': prober.get_confidence(),
'language': prober.language}
self.done = True
break
if self.WIN_BYTE_DETECTOR.search(byte_str):
self._has_win_bytes = True | [
"def",
"feed",
"(",
"self",
",",
"byte_str",
")",
":",
"if",
"self",
".",
"done",
":",
"return",
"if",
"not",
"len",
"(",
"byte_str",
")",
":",
"return",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytearray",
")",
":",
"byte_str",
"=",
"bytearray",
"(",
"byte_str",
")",
"# First check for known BOMs, since these are guaranteed to be correct",
"if",
"not",
"self",
".",
"_got_data",
":",
"# If the data starts with BOM, we know it is UTF",
"if",
"byte_str",
".",
"startswith",
"(",
"codecs",
".",
"BOM_UTF8",
")",
":",
"# EF BB BF UTF-8 with BOM",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"\"UTF-8-SIG\"",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"elif",
"byte_str",
".",
"startswith",
"(",
"(",
"codecs",
".",
"BOM_UTF32_LE",
",",
"codecs",
".",
"BOM_UTF32_BE",
")",
")",
":",
"# FF FE 00 00 UTF-32, little-endian BOM",
"# 00 00 FE FF UTF-32, big-endian BOM",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"\"UTF-32\"",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"elif",
"byte_str",
".",
"startswith",
"(",
"b'\\xFE\\xFF\\x00\\x00'",
")",
":",
"# FE FF 00 00 UCS-4, unusual octet order BOM (3412)",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"\"X-ISO-10646-UCS-4-3412\"",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"elif",
"byte_str",
".",
"startswith",
"(",
"b'\\x00\\x00\\xFF\\xFE'",
")",
":",
"# 00 00 FF FE UCS-4, unusual octet order BOM (2143)",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"\"X-ISO-10646-UCS-4-2143\"",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"elif",
"byte_str",
".",
"startswith",
"(",
"(",
"codecs",
".",
"BOM_LE",
",",
"codecs",
".",
"BOM_BE",
")",
")",
":",
"# FF FE UTF-16, little endian BOM",
"# FE FF UTF-16, big endian BOM",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"\"UTF-16\"",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"self",
".",
"_got_data",
"=",
"True",
"if",
"self",
".",
"result",
"[",
"'encoding'",
"]",
"is",
"not",
"None",
":",
"self",
".",
"done",
"=",
"True",
"return",
"# If none of those matched and we've only see ASCII so far, check",
"# for high bytes and escape sequences",
"if",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"PURE_ASCII",
":",
"if",
"self",
".",
"HIGH_BYTE_DETECTOR",
".",
"search",
"(",
"byte_str",
")",
":",
"self",
".",
"_input_state",
"=",
"InputState",
".",
"HIGH_BYTE",
"elif",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"PURE_ASCII",
"and",
"self",
".",
"ESC_DETECTOR",
".",
"search",
"(",
"self",
".",
"_last_char",
"+",
"byte_str",
")",
":",
"self",
".",
"_input_state",
"=",
"InputState",
".",
"ESC_ASCII",
"self",
".",
"_last_char",
"=",
"byte_str",
"[",
"-",
"1",
":",
"]",
"# If we've seen escape sequences, use the EscCharSetProber, which",
"# uses a simple state machine to check for known escape sequences in",
"# HZ and ISO-2022 encodings, since those are the only encodings that",
"# use such sequences.",
"if",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"ESC_ASCII",
":",
"if",
"not",
"self",
".",
"_esc_charset_prober",
":",
"self",
".",
"_esc_charset_prober",
"=",
"EscCharSetProber",
"(",
"self",
".",
"lang_filter",
")",
"if",
"self",
".",
"_esc_charset_prober",
".",
"feed",
"(",
"byte_str",
")",
"==",
"ProbingState",
".",
"FOUND_IT",
":",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"self",
".",
"_esc_charset_prober",
".",
"charset_name",
",",
"'confidence'",
":",
"self",
".",
"_esc_charset_prober",
".",
"get_confidence",
"(",
")",
",",
"'language'",
":",
"self",
".",
"_esc_charset_prober",
".",
"language",
"}",
"self",
".",
"done",
"=",
"True",
"# If we've seen high bytes (i.e., those with values greater than 127),",
"# we need to do more complicated checks using all our multi-byte and",
"# single-byte probers that are left. The single-byte probers",
"# use character bigram distributions to determine the encoding, whereas",
"# the multi-byte probers use a combination of character unigram and",
"# bigram distributions.",
"elif",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"HIGH_BYTE",
":",
"if",
"not",
"self",
".",
"_charset_probers",
":",
"self",
".",
"_charset_probers",
"=",
"[",
"MBCSGroupProber",
"(",
"self",
".",
"lang_filter",
")",
"]",
"# If we're checking non-CJK encodings, use single-byte prober",
"if",
"self",
".",
"lang_filter",
"&",
"LanguageFilter",
".",
"NON_CJK",
":",
"self",
".",
"_charset_probers",
".",
"append",
"(",
"SBCSGroupProber",
"(",
")",
")",
"self",
".",
"_charset_probers",
".",
"append",
"(",
"Latin1Prober",
"(",
")",
")",
"for",
"prober",
"in",
"self",
".",
"_charset_probers",
":",
"if",
"prober",
".",
"feed",
"(",
"byte_str",
")",
"==",
"ProbingState",
".",
"FOUND_IT",
":",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"prober",
".",
"charset_name",
",",
"'confidence'",
":",
"prober",
".",
"get_confidence",
"(",
")",
",",
"'language'",
":",
"prober",
".",
"language",
"}",
"self",
".",
"done",
"=",
"True",
"break",
"if",
"self",
".",
"WIN_BYTE_DETECTOR",
".",
"search",
"(",
"byte_str",
")",
":",
"self",
".",
"_has_win_bytes",
"=",
"True"
] | Takes a chunk of a document and feeds it through all of the relevant
charset probers.
After calling ``feed``, you can check the value of the ``done``
attribute to see if you need to continue feeding the
``UniversalDetector`` more data, or if it has made a prediction
(in the ``result`` attribute).
.. note::
You should always call ``close`` when you're done feeding in your
document if ``done`` is not already ``True``. | [
"Takes",
"a",
"chunk",
"of",
"a",
"document",
"and",
"feeds",
"it",
"through",
"all",
"of",
"the",
"relevant",
"charset",
"probers",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/universaldetector.py#L111-L218 |
24,931 | pypa/pipenv | pipenv/vendor/chardet/universaldetector.py | UniversalDetector.close | def close(self):
"""
Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`.
"""
# Don't bother with checks if we're already done
if self.done:
return self.result
self.done = True
if not self._got_data:
self.logger.debug('no data received!')
# Default to ASCII if it is all we've seen so far
elif self._input_state == InputState.PURE_ASCII:
self.result = {'encoding': 'ascii',
'confidence': 1.0,
'language': ''}
# If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD
elif self._input_state == InputState.HIGH_BYTE:
prober_confidence = None
max_prober_confidence = 0.0
max_prober = None
for prober in self._charset_probers:
if not prober:
continue
prober_confidence = prober.get_confidence()
if prober_confidence > max_prober_confidence:
max_prober_confidence = prober_confidence
max_prober = prober
if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD):
charset_name = max_prober.charset_name
lower_charset_name = max_prober.charset_name.lower()
confidence = max_prober.get_confidence()
# Use Windows encoding name instead of ISO-8859 if we saw any
# extra Windows-specific bytes
if lower_charset_name.startswith('iso-8859'):
if self._has_win_bytes:
charset_name = self.ISO_WIN_MAP.get(lower_charset_name,
charset_name)
self.result = {'encoding': charset_name,
'confidence': confidence,
'language': max_prober.language}
# Log all prober confidences if none met MINIMUM_THRESHOLD
if self.logger.getEffectiveLevel() == logging.DEBUG:
if self.result['encoding'] is None:
self.logger.debug('no probers hit minimum threshold')
for group_prober in self._charset_probers:
if not group_prober:
continue
if isinstance(group_prober, CharSetGroupProber):
for prober in group_prober.probers:
self.logger.debug('%s %s confidence = %s',
prober.charset_name,
prober.language,
prober.get_confidence())
else:
self.logger.debug('%s %s confidence = %s',
prober.charset_name,
prober.language,
prober.get_confidence())
return self.result | python | def close(self):
"""
Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`.
"""
# Don't bother with checks if we're already done
if self.done:
return self.result
self.done = True
if not self._got_data:
self.logger.debug('no data received!')
# Default to ASCII if it is all we've seen so far
elif self._input_state == InputState.PURE_ASCII:
self.result = {'encoding': 'ascii',
'confidence': 1.0,
'language': ''}
# If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD
elif self._input_state == InputState.HIGH_BYTE:
prober_confidence = None
max_prober_confidence = 0.0
max_prober = None
for prober in self._charset_probers:
if not prober:
continue
prober_confidence = prober.get_confidence()
if prober_confidence > max_prober_confidence:
max_prober_confidence = prober_confidence
max_prober = prober
if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD):
charset_name = max_prober.charset_name
lower_charset_name = max_prober.charset_name.lower()
confidence = max_prober.get_confidence()
# Use Windows encoding name instead of ISO-8859 if we saw any
# extra Windows-specific bytes
if lower_charset_name.startswith('iso-8859'):
if self._has_win_bytes:
charset_name = self.ISO_WIN_MAP.get(lower_charset_name,
charset_name)
self.result = {'encoding': charset_name,
'confidence': confidence,
'language': max_prober.language}
# Log all prober confidences if none met MINIMUM_THRESHOLD
if self.logger.getEffectiveLevel() == logging.DEBUG:
if self.result['encoding'] is None:
self.logger.debug('no probers hit minimum threshold')
for group_prober in self._charset_probers:
if not group_prober:
continue
if isinstance(group_prober, CharSetGroupProber):
for prober in group_prober.probers:
self.logger.debug('%s %s confidence = %s',
prober.charset_name,
prober.language,
prober.get_confidence())
else:
self.logger.debug('%s %s confidence = %s',
prober.charset_name,
prober.language,
prober.get_confidence())
return self.result | [
"def",
"close",
"(",
"self",
")",
":",
"# Don't bother with checks if we're already done",
"if",
"self",
".",
"done",
":",
"return",
"self",
".",
"result",
"self",
".",
"done",
"=",
"True",
"if",
"not",
"self",
".",
"_got_data",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'no data received!'",
")",
"# Default to ASCII if it is all we've seen so far",
"elif",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"PURE_ASCII",
":",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"'ascii'",
",",
"'confidence'",
":",
"1.0",
",",
"'language'",
":",
"''",
"}",
"# If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD",
"elif",
"self",
".",
"_input_state",
"==",
"InputState",
".",
"HIGH_BYTE",
":",
"prober_confidence",
"=",
"None",
"max_prober_confidence",
"=",
"0.0",
"max_prober",
"=",
"None",
"for",
"prober",
"in",
"self",
".",
"_charset_probers",
":",
"if",
"not",
"prober",
":",
"continue",
"prober_confidence",
"=",
"prober",
".",
"get_confidence",
"(",
")",
"if",
"prober_confidence",
">",
"max_prober_confidence",
":",
"max_prober_confidence",
"=",
"prober_confidence",
"max_prober",
"=",
"prober",
"if",
"max_prober",
"and",
"(",
"max_prober_confidence",
">",
"self",
".",
"MINIMUM_THRESHOLD",
")",
":",
"charset_name",
"=",
"max_prober",
".",
"charset_name",
"lower_charset_name",
"=",
"max_prober",
".",
"charset_name",
".",
"lower",
"(",
")",
"confidence",
"=",
"max_prober",
".",
"get_confidence",
"(",
")",
"# Use Windows encoding name instead of ISO-8859 if we saw any",
"# extra Windows-specific bytes",
"if",
"lower_charset_name",
".",
"startswith",
"(",
"'iso-8859'",
")",
":",
"if",
"self",
".",
"_has_win_bytes",
":",
"charset_name",
"=",
"self",
".",
"ISO_WIN_MAP",
".",
"get",
"(",
"lower_charset_name",
",",
"charset_name",
")",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"charset_name",
",",
"'confidence'",
":",
"confidence",
",",
"'language'",
":",
"max_prober",
".",
"language",
"}",
"# Log all prober confidences if none met MINIMUM_THRESHOLD",
"if",
"self",
".",
"logger",
".",
"getEffectiveLevel",
"(",
")",
"==",
"logging",
".",
"DEBUG",
":",
"if",
"self",
".",
"result",
"[",
"'encoding'",
"]",
"is",
"None",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'no probers hit minimum threshold'",
")",
"for",
"group_prober",
"in",
"self",
".",
"_charset_probers",
":",
"if",
"not",
"group_prober",
":",
"continue",
"if",
"isinstance",
"(",
"group_prober",
",",
"CharSetGroupProber",
")",
":",
"for",
"prober",
"in",
"group_prober",
".",
"probers",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s %s confidence = %s'",
",",
"prober",
".",
"charset_name",
",",
"prober",
".",
"language",
",",
"prober",
".",
"get_confidence",
"(",
")",
")",
"else",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s %s confidence = %s'",
",",
"prober",
".",
"charset_name",
",",
"prober",
".",
"language",
",",
"prober",
".",
"get_confidence",
"(",
")",
")",
"return",
"self",
".",
"result"
] | Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`. | [
"Stop",
"analyzing",
"the",
"current",
"document",
"and",
"come",
"up",
"with",
"a",
"final",
"prediction",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/universaldetector.py#L220-L286 |
24,932 | pypa/pipenv | pipenv/vendor/pexpect/replwrap.py | REPLWrapper.run_command | def run_command(self, command, timeout=-1):
"""Send a command to the REPL, wait for and return output.
:param str command: The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input, :exc:`ValueError`
will be raised.
:param int timeout: How long to wait for the next prompt. -1 means the
default from the :class:`pexpect.spawn` object (default 30 seconds).
None means to wait indefinitely.
"""
# Split up multiline commands and feed them in bit-by-bit
cmdlines = command.splitlines()
# splitlines ignores trailing newlines - add it back in manually
if command.endswith('\n'):
cmdlines.append('')
if not cmdlines:
raise ValueError("No command was given")
res = []
self.child.sendline(cmdlines[0])
for line in cmdlines[1:]:
self._expect_prompt(timeout=timeout)
res.append(self.child.before)
self.child.sendline(line)
# Command was fully submitted, now wait for the next prompt
if self._expect_prompt(timeout=timeout) == 1:
# We got the continuation prompt - command was incomplete
self.child.kill(signal.SIGINT)
self._expect_prompt(timeout=1)
raise ValueError("Continuation prompt found - input was incomplete:\n"
+ command)
return u''.join(res + [self.child.before]) | python | def run_command(self, command, timeout=-1):
"""Send a command to the REPL, wait for and return output.
:param str command: The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input, :exc:`ValueError`
will be raised.
:param int timeout: How long to wait for the next prompt. -1 means the
default from the :class:`pexpect.spawn` object (default 30 seconds).
None means to wait indefinitely.
"""
# Split up multiline commands and feed them in bit-by-bit
cmdlines = command.splitlines()
# splitlines ignores trailing newlines - add it back in manually
if command.endswith('\n'):
cmdlines.append('')
if not cmdlines:
raise ValueError("No command was given")
res = []
self.child.sendline(cmdlines[0])
for line in cmdlines[1:]:
self._expect_prompt(timeout=timeout)
res.append(self.child.before)
self.child.sendline(line)
# Command was fully submitted, now wait for the next prompt
if self._expect_prompt(timeout=timeout) == 1:
# We got the continuation prompt - command was incomplete
self.child.kill(signal.SIGINT)
self._expect_prompt(timeout=1)
raise ValueError("Continuation prompt found - input was incomplete:\n"
+ command)
return u''.join(res + [self.child.before]) | [
"def",
"run_command",
"(",
"self",
",",
"command",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"# Split up multiline commands and feed them in bit-by-bit",
"cmdlines",
"=",
"command",
".",
"splitlines",
"(",
")",
"# splitlines ignores trailing newlines - add it back in manually",
"if",
"command",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"cmdlines",
".",
"append",
"(",
"''",
")",
"if",
"not",
"cmdlines",
":",
"raise",
"ValueError",
"(",
"\"No command was given\"",
")",
"res",
"=",
"[",
"]",
"self",
".",
"child",
".",
"sendline",
"(",
"cmdlines",
"[",
"0",
"]",
")",
"for",
"line",
"in",
"cmdlines",
"[",
"1",
":",
"]",
":",
"self",
".",
"_expect_prompt",
"(",
"timeout",
"=",
"timeout",
")",
"res",
".",
"append",
"(",
"self",
".",
"child",
".",
"before",
")",
"self",
".",
"child",
".",
"sendline",
"(",
"line",
")",
"# Command was fully submitted, now wait for the next prompt",
"if",
"self",
".",
"_expect_prompt",
"(",
"timeout",
"=",
"timeout",
")",
"==",
"1",
":",
"# We got the continuation prompt - command was incomplete",
"self",
".",
"child",
".",
"kill",
"(",
"signal",
".",
"SIGINT",
")",
"self",
".",
"_expect_prompt",
"(",
"timeout",
"=",
"1",
")",
"raise",
"ValueError",
"(",
"\"Continuation prompt found - input was incomplete:\\n\"",
"+",
"command",
")",
"return",
"u''",
".",
"join",
"(",
"res",
"+",
"[",
"self",
".",
"child",
".",
"before",
"]",
")"
] | Send a command to the REPL, wait for and return output.
:param str command: The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input, :exc:`ValueError`
will be raised.
:param int timeout: How long to wait for the next prompt. -1 means the
default from the :class:`pexpect.spawn` object (default 30 seconds).
None means to wait indefinitely. | [
"Send",
"a",
"command",
"to",
"the",
"REPL",
"wait",
"for",
"and",
"return",
"output",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/replwrap.py#L68-L101 |
24,933 | pypa/pipenv | pipenv/vendor/click/utils.py | safecall | def safecall(func):
"""Wraps a function so that it swallows exceptions."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper | python | def safecall(func):
"""Wraps a function so that it swallows exceptions."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper | [
"def",
"safecall",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"pass",
"return",
"wrapper"
] | Wraps a function so that it swallows exceptions. | [
"Wraps",
"a",
"function",
"so",
"that",
"it",
"swallows",
"exceptions",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L25-L32 |
24,934 | pypa/pipenv | pipenv/vendor/click/utils.py | make_default_short_help | def make_default_short_help(help, max_length=45):
"""Return a condensed version of help string."""
words = help.split()
total_length = 0
result = []
done = False
for word in words:
if word[-1:] == '.':
done = True
new_length = result and 1 + len(word) or len(word)
if total_length + new_length > max_length:
result.append('...')
done = True
else:
if result:
result.append(' ')
result.append(word)
if done:
break
total_length += new_length
return ''.join(result) | python | def make_default_short_help(help, max_length=45):
"""Return a condensed version of help string."""
words = help.split()
total_length = 0
result = []
done = False
for word in words:
if word[-1:] == '.':
done = True
new_length = result and 1 + len(word) or len(word)
if total_length + new_length > max_length:
result.append('...')
done = True
else:
if result:
result.append(' ')
result.append(word)
if done:
break
total_length += new_length
return ''.join(result) | [
"def",
"make_default_short_help",
"(",
"help",
",",
"max_length",
"=",
"45",
")",
":",
"words",
"=",
"help",
".",
"split",
"(",
")",
"total_length",
"=",
"0",
"result",
"=",
"[",
"]",
"done",
"=",
"False",
"for",
"word",
"in",
"words",
":",
"if",
"word",
"[",
"-",
"1",
":",
"]",
"==",
"'.'",
":",
"done",
"=",
"True",
"new_length",
"=",
"result",
"and",
"1",
"+",
"len",
"(",
"word",
")",
"or",
"len",
"(",
"word",
")",
"if",
"total_length",
"+",
"new_length",
">",
"max_length",
":",
"result",
".",
"append",
"(",
"'...'",
")",
"done",
"=",
"True",
"else",
":",
"if",
"result",
":",
"result",
".",
"append",
"(",
"' '",
")",
"result",
".",
"append",
"(",
"word",
")",
"if",
"done",
":",
"break",
"total_length",
"+=",
"new_length",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Return a condensed version of help string. | [
"Return",
"a",
"condensed",
"version",
"of",
"help",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L45-L67 |
24,935 | pypa/pipenv | pipenv/vendor/click/utils.py | get_binary_stream | def get_binary_stream(name):
"""Returns a system stream for byte processing. This essentially
returns the stream from the sys module with the given name but it
solves some compatibility issues between different Python versions.
Primarily this function is necessary for getting binary streams on
Python 3.
:param name: the name of the stream to open. Valid names are ``'stdin'``,
``'stdout'`` and ``'stderr'``
"""
opener = binary_streams.get(name)
if opener is None:
raise TypeError('Unknown standard stream %r' % name)
return opener() | python | def get_binary_stream(name):
"""Returns a system stream for byte processing. This essentially
returns the stream from the sys module with the given name but it
solves some compatibility issues between different Python versions.
Primarily this function is necessary for getting binary streams on
Python 3.
:param name: the name of the stream to open. Valid names are ``'stdin'``,
``'stdout'`` and ``'stderr'``
"""
opener = binary_streams.get(name)
if opener is None:
raise TypeError('Unknown standard stream %r' % name)
return opener() | [
"def",
"get_binary_stream",
"(",
"name",
")",
":",
"opener",
"=",
"binary_streams",
".",
"get",
"(",
"name",
")",
"if",
"opener",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Unknown standard stream %r'",
"%",
"name",
")",
"return",
"opener",
"(",
")"
] | Returns a system stream for byte processing. This essentially
returns the stream from the sys module with the given name but it
solves some compatibility issues between different Python versions.
Primarily this function is necessary for getting binary streams on
Python 3.
:param name: the name of the stream to open. Valid names are ``'stdin'``,
``'stdout'`` and ``'stderr'`` | [
"Returns",
"a",
"system",
"stream",
"for",
"byte",
"processing",
".",
"This",
"essentially",
"returns",
"the",
"stream",
"from",
"the",
"sys",
"module",
"with",
"the",
"given",
"name",
"but",
"it",
"solves",
"some",
"compatibility",
"issues",
"between",
"different",
"Python",
"versions",
".",
"Primarily",
"this",
"function",
"is",
"necessary",
"for",
"getting",
"binary",
"streams",
"on",
"Python",
"3",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L264-L277 |
24,936 | pypa/pipenv | pipenv/vendor/click/utils.py | format_filename | def format_filename(filename, shorten=False):
"""Formats a filename for user display. The main purpose of this
function is to ensure that the filename can be displayed at all. This
will decode the filename to unicode if necessary in a way that it will
not fail. Optionally, it can shorten the filename to not include the
full path to the filename.
:param filename: formats a filename for UI display. This will also convert
the filename into unicode without failing.
:param shorten: this optionally shortens the filename to strip of the
path that leads up to it.
"""
if shorten:
filename = os.path.basename(filename)
return filename_to_ui(filename) | python | def format_filename(filename, shorten=False):
"""Formats a filename for user display. The main purpose of this
function is to ensure that the filename can be displayed at all. This
will decode the filename to unicode if necessary in a way that it will
not fail. Optionally, it can shorten the filename to not include the
full path to the filename.
:param filename: formats a filename for UI display. This will also convert
the filename into unicode without failing.
:param shorten: this optionally shortens the filename to strip of the
path that leads up to it.
"""
if shorten:
filename = os.path.basename(filename)
return filename_to_ui(filename) | [
"def",
"format_filename",
"(",
"filename",
",",
"shorten",
"=",
"False",
")",
":",
"if",
"shorten",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"return",
"filename_to_ui",
"(",
"filename",
")"
] | Formats a filename for user display. The main purpose of this
function is to ensure that the filename can be displayed at all. This
will decode the filename to unicode if necessary in a way that it will
not fail. Optionally, it can shorten the filename to not include the
full path to the filename.
:param filename: formats a filename for UI display. This will also convert
the filename into unicode without failing.
:param shorten: this optionally shortens the filename to strip of the
path that leads up to it. | [
"Formats",
"a",
"filename",
"for",
"user",
"display",
".",
"The",
"main",
"purpose",
"of",
"this",
"function",
"is",
"to",
"ensure",
"that",
"the",
"filename",
"can",
"be",
"displayed",
"at",
"all",
".",
"This",
"will",
"decode",
"the",
"filename",
"to",
"unicode",
"if",
"necessary",
"in",
"a",
"way",
"that",
"it",
"will",
"not",
"fail",
".",
"Optionally",
"it",
"can",
"shorten",
"the",
"filename",
"to",
"not",
"include",
"the",
"full",
"path",
"to",
"the",
"filename",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L351-L365 |
24,937 | pypa/pipenv | pipenv/vendor/click/utils.py | get_app_dir | def get_app_dir(app_name, roaming=True, force_posix=False):
r"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like
the following folders could be returned:
Mac OS X:
``~/Library/Application Support/Foo Bar``
Mac OS X (POSIX):
``~/.foo-bar``
Unix:
``~/.config/foo-bar``
Unix (POSIX):
``~/.foo-bar``
Win XP (roaming):
``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
Win XP (not roaming):
``C:\Documents and Settings\<user>\Application Data\Foo Bar``
Win 7 (roaming):
``C:\Users\<user>\AppData\Roaming\Foo Bar``
Win 7 (not roaming):
``C:\Users\<user>\AppData\Local\Foo Bar``
.. versionadded:: 2.0
:param app_name: the application name. This should be properly capitalized
and can contain whitespace.
:param roaming: controls if the folder should be roaming or not on Windows.
Has no affect otherwise.
:param force_posix: if this is set to `True` then on any POSIX system the
folder will be stored in the home folder with a leading
dot instead of the XDG config home or darwin's
application support folder.
"""
if WIN:
key = roaming and 'APPDATA' or 'LOCALAPPDATA'
folder = os.environ.get(key)
if folder is None:
folder = os.path.expanduser('~')
return os.path.join(folder, app_name)
if force_posix:
return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))
if sys.platform == 'darwin':
return os.path.join(os.path.expanduser(
'~/Library/Application Support'), app_name)
return os.path.join(
os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),
_posixify(app_name)) | python | def get_app_dir(app_name, roaming=True, force_posix=False):
r"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like
the following folders could be returned:
Mac OS X:
``~/Library/Application Support/Foo Bar``
Mac OS X (POSIX):
``~/.foo-bar``
Unix:
``~/.config/foo-bar``
Unix (POSIX):
``~/.foo-bar``
Win XP (roaming):
``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
Win XP (not roaming):
``C:\Documents and Settings\<user>\Application Data\Foo Bar``
Win 7 (roaming):
``C:\Users\<user>\AppData\Roaming\Foo Bar``
Win 7 (not roaming):
``C:\Users\<user>\AppData\Local\Foo Bar``
.. versionadded:: 2.0
:param app_name: the application name. This should be properly capitalized
and can contain whitespace.
:param roaming: controls if the folder should be roaming or not on Windows.
Has no affect otherwise.
:param force_posix: if this is set to `True` then on any POSIX system the
folder will be stored in the home folder with a leading
dot instead of the XDG config home or darwin's
application support folder.
"""
if WIN:
key = roaming and 'APPDATA' or 'LOCALAPPDATA'
folder = os.environ.get(key)
if folder is None:
folder = os.path.expanduser('~')
return os.path.join(folder, app_name)
if force_posix:
return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))
if sys.platform == 'darwin':
return os.path.join(os.path.expanduser(
'~/Library/Application Support'), app_name)
return os.path.join(
os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),
_posixify(app_name)) | [
"def",
"get_app_dir",
"(",
"app_name",
",",
"roaming",
"=",
"True",
",",
"force_posix",
"=",
"False",
")",
":",
"if",
"WIN",
":",
"key",
"=",
"roaming",
"and",
"'APPDATA'",
"or",
"'LOCALAPPDATA'",
"folder",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"folder",
"is",
"None",
":",
"folder",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"app_name",
")",
"if",
"force_posix",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.'",
"+",
"_posixify",
"(",
"app_name",
")",
")",
")",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/Library/Application Support'",
")",
",",
"app_name",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.config'",
")",
")",
",",
"_posixify",
"(",
"app_name",
")",
")"
] | r"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like
the following folders could be returned:
Mac OS X:
``~/Library/Application Support/Foo Bar``
Mac OS X (POSIX):
``~/.foo-bar``
Unix:
``~/.config/foo-bar``
Unix (POSIX):
``~/.foo-bar``
Win XP (roaming):
``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
Win XP (not roaming):
``C:\Documents and Settings\<user>\Application Data\Foo Bar``
Win 7 (roaming):
``C:\Users\<user>\AppData\Roaming\Foo Bar``
Win 7 (not roaming):
``C:\Users\<user>\AppData\Local\Foo Bar``
.. versionadded:: 2.0
:param app_name: the application name. This should be properly capitalized
and can contain whitespace.
:param roaming: controls if the folder should be roaming or not on Windows.
Has no affect otherwise.
:param force_posix: if this is set to `True` then on any POSIX system the
folder will be stored in the home folder with a leading
dot instead of the XDG config home or darwin's
application support folder. | [
"r",
"Returns",
"the",
"config",
"folder",
"for",
"the",
"application",
".",
"The",
"default",
"behavior",
"is",
"to",
"return",
"whatever",
"is",
"most",
"appropriate",
"for",
"the",
"operating",
"system",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L368-L416 |
24,938 | pypa/pipenv | pipenv/vendor/click_completion/lib.py | split_args | def split_args(line):
"""Version of shlex.split that silently accept incomplete strings.
Parameters
----------
line : str
The string to split
Returns
-------
[str]
The line split in separated arguments
"""
lex = shlex.shlex(line, posix=True)
lex.whitespace_split = True
lex.commenters = ''
res = []
try:
while True:
res.append(next(lex))
except ValueError: # No closing quotation
pass
except StopIteration: # End of loop
pass
if lex.token:
res.append(lex.token)
return res | python | def split_args(line):
"""Version of shlex.split that silently accept incomplete strings.
Parameters
----------
line : str
The string to split
Returns
-------
[str]
The line split in separated arguments
"""
lex = shlex.shlex(line, posix=True)
lex.whitespace_split = True
lex.commenters = ''
res = []
try:
while True:
res.append(next(lex))
except ValueError: # No closing quotation
pass
except StopIteration: # End of loop
pass
if lex.token:
res.append(lex.token)
return res | [
"def",
"split_args",
"(",
"line",
")",
":",
"lex",
"=",
"shlex",
".",
"shlex",
"(",
"line",
",",
"posix",
"=",
"True",
")",
"lex",
".",
"whitespace_split",
"=",
"True",
"lex",
".",
"commenters",
"=",
"''",
"res",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"res",
".",
"append",
"(",
"next",
"(",
"lex",
")",
")",
"except",
"ValueError",
":",
"# No closing quotation",
"pass",
"except",
"StopIteration",
":",
"# End of loop",
"pass",
"if",
"lex",
".",
"token",
":",
"res",
".",
"append",
"(",
"lex",
".",
"token",
")",
"return",
"res"
] | Version of shlex.split that silently accept incomplete strings.
Parameters
----------
line : str
The string to split
Returns
-------
[str]
The line split in separated arguments | [
"Version",
"of",
"shlex",
".",
"split",
"that",
"silently",
"accept",
"incomplete",
"strings",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/lib.py#L94-L120 |
24,939 | pypa/pipenv | pipenv/vendor/click/termui.py | echo_via_pager | def echo_via_pager(text_or_generator, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emitting the text to page.
:param color: controls if the pager supports ANSI colors or not. The
default is autodetection.
"""
color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator):
i = text_or_generator()
elif isinstance(text_or_generator, string_types):
i = [text_or_generator]
else:
i = iter(text_or_generator)
# convert every element of i to a text type if necessary
text_generator = (el if isinstance(el, string_types) else text_type(el)
for el in i)
from ._termui_impl import pager
return pager(itertools.chain(text_generator, "\n"), color) | python | def echo_via_pager(text_or_generator, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emitting the text to page.
:param color: controls if the pager supports ANSI colors or not. The
default is autodetection.
"""
color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator):
i = text_or_generator()
elif isinstance(text_or_generator, string_types):
i = [text_or_generator]
else:
i = iter(text_or_generator)
# convert every element of i to a text type if necessary
text_generator = (el if isinstance(el, string_types) else text_type(el)
for el in i)
from ._termui_impl import pager
return pager(itertools.chain(text_generator, "\n"), color) | [
"def",
"echo_via_pager",
"(",
"text_or_generator",
",",
"color",
"=",
"None",
")",
":",
"color",
"=",
"resolve_color_default",
"(",
"color",
")",
"if",
"inspect",
".",
"isgeneratorfunction",
"(",
"text_or_generator",
")",
":",
"i",
"=",
"text_or_generator",
"(",
")",
"elif",
"isinstance",
"(",
"text_or_generator",
",",
"string_types",
")",
":",
"i",
"=",
"[",
"text_or_generator",
"]",
"else",
":",
"i",
"=",
"iter",
"(",
"text_or_generator",
")",
"# convert every element of i to a text type if necessary",
"text_generator",
"=",
"(",
"el",
"if",
"isinstance",
"(",
"el",
",",
"string_types",
")",
"else",
"text_type",
"(",
"el",
")",
"for",
"el",
"in",
"i",
")",
"from",
".",
"_termui_impl",
"import",
"pager",
"return",
"pager",
"(",
"itertools",
".",
"chain",
"(",
"text_generator",
",",
"\"\\n\"",
")",
",",
"color",
")"
] | This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emitting the text to page.
:param color: controls if the pager supports ANSI colors or not. The
default is autodetection. | [
"This",
"function",
"takes",
"a",
"text",
"and",
"shows",
"it",
"via",
"an",
"environment",
"specific",
"pager",
"on",
"stdout",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L232-L258 |
24,940 | pypa/pipenv | pipenv/vendor/click/termui.py | clear | def clear():
"""Clears the terminal screen. This will have the effect of clearing
the whole visible space of the terminal and moving the cursor to the
top left. This does not do anything if not connected to a terminal.
.. versionadded:: 2.0
"""
if not isatty(sys.stdout):
return
# If we're on Windows and we don't have colorama available, then we
# clear the screen by shelling out. Otherwise we can use an escape
# sequence.
if WIN:
os.system('cls')
else:
sys.stdout.write('\033[2J\033[1;1H') | python | def clear():
"""Clears the terminal screen. This will have the effect of clearing
the whole visible space of the terminal and moving the cursor to the
top left. This does not do anything if not connected to a terminal.
.. versionadded:: 2.0
"""
if not isatty(sys.stdout):
return
# If we're on Windows and we don't have colorama available, then we
# clear the screen by shelling out. Otherwise we can use an escape
# sequence.
if WIN:
os.system('cls')
else:
sys.stdout.write('\033[2J\033[1;1H') | [
"def",
"clear",
"(",
")",
":",
"if",
"not",
"isatty",
"(",
"sys",
".",
"stdout",
")",
":",
"return",
"# If we're on Windows and we don't have colorama available, then we",
"# clear the screen by shelling out. Otherwise we can use an escape",
"# sequence.",
"if",
"WIN",
":",
"os",
".",
"system",
"(",
"'cls'",
")",
"else",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\033[2J\\033[1;1H'",
")"
] | Clears the terminal screen. This will have the effect of clearing
the whole visible space of the terminal and moving the cursor to the
top left. This does not do anything if not connected to a terminal.
.. versionadded:: 2.0 | [
"Clears",
"the",
"terminal",
"screen",
".",
"This",
"will",
"have",
"the",
"effect",
"of",
"clearing",
"the",
"whole",
"visible",
"space",
"of",
"the",
"terminal",
"and",
"moving",
"the",
"cursor",
"to",
"the",
"top",
"left",
".",
"This",
"does",
"not",
"do",
"anything",
"if",
"not",
"connected",
"to",
"a",
"terminal",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L354-L369 |
24,941 | pypa/pipenv | pipenv/vendor/click/termui.py | getchar | def getchar(echo=False):
"""Fetches a single character from the terminal and returns it. This
will always return a unicode character and under certain rare
circumstances this might return more than one character. The
situations which more than one character is returned is when for
whatever reason multiple characters end up in the terminal buffer or
standard input was not actually a terminal.
Note that this will always read from the terminal, even if something
is piped into the standard input.
Note for Windows: in rare cases when typing non-ASCII characters, this
function might wait for a second character and then return both at once.
This is because certain Unicode characters look like special-key markers.
.. versionadded:: 2.0
:param echo: if set to `True`, the character read will also show up on
the terminal. The default is to not show it.
"""
f = _getchar
if f is None:
from ._termui_impl import getchar as f
return f(echo) | python | def getchar(echo=False):
"""Fetches a single character from the terminal and returns it. This
will always return a unicode character and under certain rare
circumstances this might return more than one character. The
situations which more than one character is returned is when for
whatever reason multiple characters end up in the terminal buffer or
standard input was not actually a terminal.
Note that this will always read from the terminal, even if something
is piped into the standard input.
Note for Windows: in rare cases when typing non-ASCII characters, this
function might wait for a second character and then return both at once.
This is because certain Unicode characters look like special-key markers.
.. versionadded:: 2.0
:param echo: if set to `True`, the character read will also show up on
the terminal. The default is to not show it.
"""
f = _getchar
if f is None:
from ._termui_impl import getchar as f
return f(echo) | [
"def",
"getchar",
"(",
"echo",
"=",
"False",
")",
":",
"f",
"=",
"_getchar",
"if",
"f",
"is",
"None",
":",
"from",
".",
"_termui_impl",
"import",
"getchar",
"as",
"f",
"return",
"f",
"(",
"echo",
")"
] | Fetches a single character from the terminal and returns it. This
will always return a unicode character and under certain rare
circumstances this might return more than one character. The
situations which more than one character is returned is when for
whatever reason multiple characters end up in the terminal buffer or
standard input was not actually a terminal.
Note that this will always read from the terminal, even if something
is piped into the standard input.
Note for Windows: in rare cases when typing non-ASCII characters, this
function might wait for a second character and then return both at once.
This is because certain Unicode characters look like special-key markers.
.. versionadded:: 2.0
:param echo: if set to `True`, the character read will also show up on
the terminal. The default is to not show it. | [
"Fetches",
"a",
"single",
"character",
"from",
"the",
"terminal",
"and",
"returns",
"it",
".",
"This",
"will",
"always",
"return",
"a",
"unicode",
"character",
"and",
"under",
"certain",
"rare",
"circumstances",
"this",
"might",
"return",
"more",
"than",
"one",
"character",
".",
"The",
"situations",
"which",
"more",
"than",
"one",
"character",
"is",
"returned",
"is",
"when",
"for",
"whatever",
"reason",
"multiple",
"characters",
"end",
"up",
"in",
"the",
"terminal",
"buffer",
"or",
"standard",
"input",
"was",
"not",
"actually",
"a",
"terminal",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L549-L572 |
24,942 | pypa/pipenv | pipenv/vendor/click/termui.py | pause | def pause(info='Press any key to continue ...', err=False):
"""This command stops execution and waits for the user to press any
key to continue. This is similar to the Windows batch "pause"
command. If the program is not run through a terminal, this command
will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0
Added the `err` parameter.
:param info: the info string to print before pausing.
:param err: if set to message goes to ``stderr`` instead of
``stdout``, the same as with echo.
"""
if not isatty(sys.stdin) or not isatty(sys.stdout):
return
try:
if info:
echo(info, nl=False, err=err)
try:
getchar()
except (KeyboardInterrupt, EOFError):
pass
finally:
if info:
echo(err=err) | python | def pause(info='Press any key to continue ...', err=False):
"""This command stops execution and waits for the user to press any
key to continue. This is similar to the Windows batch "pause"
command. If the program is not run through a terminal, this command
will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0
Added the `err` parameter.
:param info: the info string to print before pausing.
:param err: if set to message goes to ``stderr`` instead of
``stdout``, the same as with echo.
"""
if not isatty(sys.stdin) or not isatty(sys.stdout):
return
try:
if info:
echo(info, nl=False, err=err)
try:
getchar()
except (KeyboardInterrupt, EOFError):
pass
finally:
if info:
echo(err=err) | [
"def",
"pause",
"(",
"info",
"=",
"'Press any key to continue ...'",
",",
"err",
"=",
"False",
")",
":",
"if",
"not",
"isatty",
"(",
"sys",
".",
"stdin",
")",
"or",
"not",
"isatty",
"(",
"sys",
".",
"stdout",
")",
":",
"return",
"try",
":",
"if",
"info",
":",
"echo",
"(",
"info",
",",
"nl",
"=",
"False",
",",
"err",
"=",
"err",
")",
"try",
":",
"getchar",
"(",
")",
"except",
"(",
"KeyboardInterrupt",
",",
"EOFError",
")",
":",
"pass",
"finally",
":",
"if",
"info",
":",
"echo",
"(",
"err",
"=",
"err",
")"
] | This command stops execution and waits for the user to press any
key to continue. This is similar to the Windows batch "pause"
command. If the program is not run through a terminal, this command
will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0
Added the `err` parameter.
:param info: the info string to print before pausing.
:param err: if set to message goes to ``stderr`` instead of
``stdout``, the same as with echo. | [
"This",
"command",
"stops",
"execution",
"and",
"waits",
"for",
"the",
"user",
"to",
"press",
"any",
"key",
"to",
"continue",
".",
"This",
"is",
"similar",
"to",
"the",
"Windows",
"batch",
"pause",
"command",
".",
"If",
"the",
"program",
"is",
"not",
"run",
"through",
"a",
"terminal",
"this",
"command",
"will",
"instead",
"do",
"nothing",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/termui.py#L580-L606 |
24,943 | pypa/pipenv | pipenv/vendor/attr/validators.py | optional | def optional(validator):
"""
A validator that makes an attribute optional. An optional attribute is one
which can be set to ``None`` in addition to satisfying the requirements of
the sub-validator.
:param validator: A validator (or a list of validators) that is used for
non-``None`` values.
:type validator: callable or :class:`list` of callables.
.. versionadded:: 15.1.0
.. versionchanged:: 17.1.0 *validator* can be a list of validators.
"""
if isinstance(validator, list):
return _OptionalValidator(_AndValidator(validator))
return _OptionalValidator(validator) | python | def optional(validator):
"""
A validator that makes an attribute optional. An optional attribute is one
which can be set to ``None`` in addition to satisfying the requirements of
the sub-validator.
:param validator: A validator (or a list of validators) that is used for
non-``None`` values.
:type validator: callable or :class:`list` of callables.
.. versionadded:: 15.1.0
.. versionchanged:: 17.1.0 *validator* can be a list of validators.
"""
if isinstance(validator, list):
return _OptionalValidator(_AndValidator(validator))
return _OptionalValidator(validator) | [
"def",
"optional",
"(",
"validator",
")",
":",
"if",
"isinstance",
"(",
"validator",
",",
"list",
")",
":",
"return",
"_OptionalValidator",
"(",
"_AndValidator",
"(",
"validator",
")",
")",
"return",
"_OptionalValidator",
"(",
"validator",
")"
] | A validator that makes an attribute optional. An optional attribute is one
which can be set to ``None`` in addition to satisfying the requirements of
the sub-validator.
:param validator: A validator (or a list of validators) that is used for
non-``None`` values.
:type validator: callable or :class:`list` of callables.
.. versionadded:: 15.1.0
.. versionchanged:: 17.1.0 *validator* can be a list of validators. | [
"A",
"validator",
"that",
"makes",
"an",
"attribute",
"optional",
".",
"An",
"optional",
"attribute",
"is",
"one",
"which",
"can",
"be",
"set",
"to",
"None",
"in",
"addition",
"to",
"satisfying",
"the",
"requirements",
"of",
"the",
"sub",
"-",
"validator",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/validators.py#L114-L129 |
24,944 | pypa/pipenv | pipenv/vendor/resolvelib/structs.py | DirectedGraph.copy | def copy(self):
"""Return a shallow copy of this graph.
"""
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other | python | def copy(self):
"""Return a shallow copy of this graph.
"""
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"DirectedGraph",
"(",
")",
"other",
".",
"_vertices",
"=",
"set",
"(",
"self",
".",
"_vertices",
")",
"other",
".",
"_forwards",
"=",
"{",
"k",
":",
"set",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_forwards",
".",
"items",
"(",
")",
"}",
"other",
".",
"_backwards",
"=",
"{",
"k",
":",
"set",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_backwards",
".",
"items",
"(",
")",
"}",
"return",
"other"
] | Return a shallow copy of this graph. | [
"Return",
"a",
"shallow",
"copy",
"of",
"this",
"graph",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/structs.py#L18-L25 |
24,945 | pypa/pipenv | pipenv/vendor/resolvelib/structs.py | DirectedGraph.add | def add(self, key):
"""Add a new vertex to the graph.
"""
if key in self._vertices:
raise ValueError('vertex exists')
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | python | def add(self, key):
"""Add a new vertex to the graph.
"""
if key in self._vertices:
raise ValueError('vertex exists')
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | [
"def",
"add",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_vertices",
":",
"raise",
"ValueError",
"(",
"'vertex exists'",
")",
"self",
".",
"_vertices",
".",
"add",
"(",
"key",
")",
"self",
".",
"_forwards",
"[",
"key",
"]",
"=",
"set",
"(",
")",
"self",
".",
"_backwards",
"[",
"key",
"]",
"=",
"set",
"(",
")"
] | Add a new vertex to the graph. | [
"Add",
"a",
"new",
"vertex",
"to",
"the",
"graph",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/structs.py#L27-L34 |
24,946 | pypa/pipenv | pipenv/vendor/resolvelib/structs.py | DirectedGraph.connect | def connect(self, f, t):
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
"""
if t not in self._vertices:
raise KeyError(t)
self._forwards[f].add(t)
self._backwards[t].add(f) | python | def connect(self, f, t):
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
"""
if t not in self._vertices:
raise KeyError(t)
self._forwards[f].add(t)
self._backwards[t].add(f) | [
"def",
"connect",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"if",
"t",
"not",
"in",
"self",
".",
"_vertices",
":",
"raise",
"KeyError",
"(",
"t",
")",
"self",
".",
"_forwards",
"[",
"f",
"]",
".",
"add",
"(",
"t",
")",
"self",
".",
"_backwards",
"[",
"t",
"]",
".",
"add",
"(",
"f",
")"
] | Connect two existing vertices.
Nothing happens if the vertices are already connected. | [
"Connect",
"two",
"existing",
"vertices",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/resolvelib/structs.py#L48-L56 |
24,947 | pypa/pipenv | pipenv/vendor/urllib3/util/ssl_.py | _const_compare_digest_backport | def _const_compare_digest_backport(a, b):
"""
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
"""
result = abs(len(a) - len(b))
for l, r in zip(bytearray(a), bytearray(b)):
result |= l ^ r
return result == 0 | python | def _const_compare_digest_backport(a, b):
"""
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
"""
result = abs(len(a) - len(b))
for l, r in zip(bytearray(a), bytearray(b)):
result |= l ^ r
return result == 0 | [
"def",
"_const_compare_digest_backport",
"(",
"a",
",",
"b",
")",
":",
"result",
"=",
"abs",
"(",
"len",
"(",
"a",
")",
"-",
"len",
"(",
"b",
")",
")",
"for",
"l",
",",
"r",
"in",
"zip",
"(",
"bytearray",
"(",
"a",
")",
",",
"bytearray",
"(",
"b",
")",
")",
":",
"result",
"|=",
"l",
"^",
"r",
"return",
"result",
"==",
"0"
] | Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise. | [
"Compare",
"two",
"digests",
"of",
"equal",
"length",
"in",
"constant",
"time",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/ssl_.py#L27-L37 |
24,948 | pypa/pipenv | pipenv/vendor/urllib3/util/ssl_.py | is_ipaddress | def is_ipaddress(hostname):
"""Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
"""
if six.PY3 and isinstance(hostname, bytes):
# IDN A-label bytes are ASCII compatible.
hostname = hostname.decode('ascii')
families = [socket.AF_INET]
if hasattr(socket, 'AF_INET6'):
families.append(socket.AF_INET6)
for af in families:
try:
inet_pton(af, hostname)
except (socket.error, ValueError, OSError):
pass
else:
return True
return False | python | def is_ipaddress(hostname):
"""Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
"""
if six.PY3 and isinstance(hostname, bytes):
# IDN A-label bytes are ASCII compatible.
hostname = hostname.decode('ascii')
families = [socket.AF_INET]
if hasattr(socket, 'AF_INET6'):
families.append(socket.AF_INET6)
for af in families:
try:
inet_pton(af, hostname)
except (socket.error, ValueError, OSError):
pass
else:
return True
return False | [
"def",
"is_ipaddress",
"(",
"hostname",
")",
":",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"hostname",
",",
"bytes",
")",
":",
"# IDN A-label bytes are ASCII compatible.",
"hostname",
"=",
"hostname",
".",
"decode",
"(",
"'ascii'",
")",
"families",
"=",
"[",
"socket",
".",
"AF_INET",
"]",
"if",
"hasattr",
"(",
"socket",
",",
"'AF_INET6'",
")",
":",
"families",
".",
"append",
"(",
"socket",
".",
"AF_INET6",
")",
"for",
"af",
"in",
"families",
":",
"try",
":",
"inet_pton",
"(",
"af",
",",
"hostname",
")",
"except",
"(",
"socket",
".",
"error",
",",
"ValueError",
",",
"OSError",
")",
":",
"pass",
"else",
":",
"return",
"True",
"return",
"False"
] | Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise. | [
"Detects",
"whether",
"the",
"hostname",
"given",
"is",
"an",
"IP",
"address",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/ssl_.py#L360-L381 |
24,949 | pypa/pipenv | pipenv/vendor/urllib3/util/retry.py | Retry.get_retry_after | def get_retry_after(self, response):
""" Get the value of Retry-After in seconds. """
retry_after = response.getheader("Retry-After")
if retry_after is None:
return None
return self.parse_retry_after(retry_after) | python | def get_retry_after(self, response):
""" Get the value of Retry-After in seconds. """
retry_after = response.getheader("Retry-After")
if retry_after is None:
return None
return self.parse_retry_after(retry_after) | [
"def",
"get_retry_after",
"(",
"self",
",",
"response",
")",
":",
"retry_after",
"=",
"response",
".",
"getheader",
"(",
"\"Retry-After\"",
")",
"if",
"retry_after",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"parse_retry_after",
"(",
"retry_after",
")"
] | Get the value of Retry-After in seconds. | [
"Get",
"the",
"value",
"of",
"Retry",
"-",
"After",
"in",
"seconds",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/retry.py#L243-L251 |
24,950 | pypa/pipenv | pipenv/vendor/urllib3/util/retry.py | Retry.sleep | def sleep(self, response=None):
""" Sleep between retry attempts.
This method will respect a server's ``Retry-After`` response header
and sleep the duration of the time requested. If that is not present, it
will use an exponential backoff. By default, the backoff factor is 0 and
this method will return immediately.
"""
if response:
slept = self.sleep_for_retry(response)
if slept:
return
self._sleep_backoff() | python | def sleep(self, response=None):
""" Sleep between retry attempts.
This method will respect a server's ``Retry-After`` response header
and sleep the duration of the time requested. If that is not present, it
will use an exponential backoff. By default, the backoff factor is 0 and
this method will return immediately.
"""
if response:
slept = self.sleep_for_retry(response)
if slept:
return
self._sleep_backoff() | [
"def",
"sleep",
"(",
"self",
",",
"response",
"=",
"None",
")",
":",
"if",
"response",
":",
"slept",
"=",
"self",
".",
"sleep_for_retry",
"(",
"response",
")",
"if",
"slept",
":",
"return",
"self",
".",
"_sleep_backoff",
"(",
")"
] | Sleep between retry attempts.
This method will respect a server's ``Retry-After`` response header
and sleep the duration of the time requested. If that is not present, it
will use an exponential backoff. By default, the backoff factor is 0 and
this method will return immediately. | [
"Sleep",
"between",
"retry",
"attempts",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/retry.py#L267-L281 |
24,951 | pypa/pipenv | pipenv/vendor/urllib3/util/retry.py | Retry._is_method_retryable | def _is_method_retryable(self, method):
""" Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist.
"""
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return True | python | def _is_method_retryable(self, method):
""" Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist.
"""
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return True | [
"def",
"_is_method_retryable",
"(",
"self",
",",
"method",
")",
":",
"if",
"self",
".",
"method_whitelist",
"and",
"method",
".",
"upper",
"(",
")",
"not",
"in",
"self",
".",
"method_whitelist",
":",
"return",
"False",
"return",
"True"
] | Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist. | [
"Checks",
"if",
"a",
"given",
"HTTP",
"method",
"should",
"be",
"retried",
"upon",
"depending",
"if",
"it",
"is",
"included",
"on",
"the",
"method",
"whitelist",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/retry.py#L295-L302 |
24,952 | pypa/pipenv | pipenv/vendor/urllib3/util/retry.py | Retry.is_exhausted | def is_exhausted(self):
""" Are we out of retries? """
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
retry_counts = list(filter(None, retry_counts))
if not retry_counts:
return False
return min(retry_counts) < 0 | python | def is_exhausted(self):
""" Are we out of retries? """
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
retry_counts = list(filter(None, retry_counts))
if not retry_counts:
return False
return min(retry_counts) < 0 | [
"def",
"is_exhausted",
"(",
"self",
")",
":",
"retry_counts",
"=",
"(",
"self",
".",
"total",
",",
"self",
".",
"connect",
",",
"self",
".",
"read",
",",
"self",
".",
"redirect",
",",
"self",
".",
"status",
")",
"retry_counts",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"retry_counts",
")",
")",
"if",
"not",
"retry_counts",
":",
"return",
"False",
"return",
"min",
"(",
"retry_counts",
")",
"<",
"0"
] | Are we out of retries? | [
"Are",
"we",
"out",
"of",
"retries?"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/retry.py#L320-L327 |
24,953 | pypa/pipenv | pipenv/patched/notpip/_vendor/cachecontrol/adapter.py | CacheControlAdapter.build_response | def build_response(
self, request, response, from_cache=False, cacheable_methods=None
):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
cacheable = cacheable_methods or self.cacheable_methods
if not from_cache and request.method in cacheable:
# Check for any heuristics that might update headers
# before trying to cache.
if self.heuristic:
response = self.heuristic.apply(response)
# apply any expiration heuristics
if response.status == 304:
# We must have sent an ETag request. This could mean
# that we've been expired already or that we simply
# have an etag. In either case, we want to try and
# update the cache if that is the case.
cached_response = self.controller.update_cached_response(
request, response
)
if cached_response is not response:
from_cache = True
# We are done with the server response, read a
# possible response body (compliant servers will
# not return one, but we cannot be 100% sure) and
# release the connection back to the pool.
response.read(decode_content=False)
response.release_conn()
response = cached_response
# We always cache the 301 responses
elif response.status == 301:
self.controller.cache_response(request, response)
else:
# Wrap the response file with a wrapper that will cache the
# response when the stream has been consumed.
response._fp = CallbackFileWrapper(
response._fp,
functools.partial(
self.controller.cache_response, request, response
),
)
if response.chunked:
super_update_chunk_length = response._update_chunk_length
def _update_chunk_length(self):
super_update_chunk_length()
if self.chunk_left == 0:
self._fp._close()
response._update_chunk_length = types.MethodType(
_update_chunk_length, response
)
resp = super(CacheControlAdapter, self).build_response(request, response)
# See if we should invalidate the cache.
if request.method in self.invalidating_methods and resp.ok:
cache_url = self.controller.cache_url(request.url)
self.cache.delete(cache_url)
# Give the request a from_cache attr to let people use it
resp.from_cache = from_cache
return resp | python | def build_response(
self, request, response, from_cache=False, cacheable_methods=None
):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
cacheable = cacheable_methods or self.cacheable_methods
if not from_cache and request.method in cacheable:
# Check for any heuristics that might update headers
# before trying to cache.
if self.heuristic:
response = self.heuristic.apply(response)
# apply any expiration heuristics
if response.status == 304:
# We must have sent an ETag request. This could mean
# that we've been expired already or that we simply
# have an etag. In either case, we want to try and
# update the cache if that is the case.
cached_response = self.controller.update_cached_response(
request, response
)
if cached_response is not response:
from_cache = True
# We are done with the server response, read a
# possible response body (compliant servers will
# not return one, but we cannot be 100% sure) and
# release the connection back to the pool.
response.read(decode_content=False)
response.release_conn()
response = cached_response
# We always cache the 301 responses
elif response.status == 301:
self.controller.cache_response(request, response)
else:
# Wrap the response file with a wrapper that will cache the
# response when the stream has been consumed.
response._fp = CallbackFileWrapper(
response._fp,
functools.partial(
self.controller.cache_response, request, response
),
)
if response.chunked:
super_update_chunk_length = response._update_chunk_length
def _update_chunk_length(self):
super_update_chunk_length()
if self.chunk_left == 0:
self._fp._close()
response._update_chunk_length = types.MethodType(
_update_chunk_length, response
)
resp = super(CacheControlAdapter, self).build_response(request, response)
# See if we should invalidate the cache.
if request.method in self.invalidating_methods and resp.ok:
cache_url = self.controller.cache_url(request.url)
self.cache.delete(cache_url)
# Give the request a from_cache attr to let people use it
resp.from_cache = from_cache
return resp | [
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
",",
"cacheable_methods",
"=",
"None",
")",
":",
"cacheable",
"=",
"cacheable_methods",
"or",
"self",
".",
"cacheable_methods",
"if",
"not",
"from_cache",
"and",
"request",
".",
"method",
"in",
"cacheable",
":",
"# Check for any heuristics that might update headers",
"# before trying to cache.",
"if",
"self",
".",
"heuristic",
":",
"response",
"=",
"self",
".",
"heuristic",
".",
"apply",
"(",
"response",
")",
"# apply any expiration heuristics",
"if",
"response",
".",
"status",
"==",
"304",
":",
"# We must have sent an ETag request. This could mean",
"# that we've been expired already or that we simply",
"# have an etag. In either case, we want to try and",
"# update the cache if that is the case.",
"cached_response",
"=",
"self",
".",
"controller",
".",
"update_cached_response",
"(",
"request",
",",
"response",
")",
"if",
"cached_response",
"is",
"not",
"response",
":",
"from_cache",
"=",
"True",
"# We are done with the server response, read a",
"# possible response body (compliant servers will",
"# not return one, but we cannot be 100% sure) and",
"# release the connection back to the pool.",
"response",
".",
"read",
"(",
"decode_content",
"=",
"False",
")",
"response",
".",
"release_conn",
"(",
")",
"response",
"=",
"cached_response",
"# We always cache the 301 responses",
"elif",
"response",
".",
"status",
"==",
"301",
":",
"self",
".",
"controller",
".",
"cache_response",
"(",
"request",
",",
"response",
")",
"else",
":",
"# Wrap the response file with a wrapper that will cache the",
"# response when the stream has been consumed.",
"response",
".",
"_fp",
"=",
"CallbackFileWrapper",
"(",
"response",
".",
"_fp",
",",
"functools",
".",
"partial",
"(",
"self",
".",
"controller",
".",
"cache_response",
",",
"request",
",",
"response",
")",
",",
")",
"if",
"response",
".",
"chunked",
":",
"super_update_chunk_length",
"=",
"response",
".",
"_update_chunk_length",
"def",
"_update_chunk_length",
"(",
"self",
")",
":",
"super_update_chunk_length",
"(",
")",
"if",
"self",
".",
"chunk_left",
"==",
"0",
":",
"self",
".",
"_fp",
".",
"_close",
"(",
")",
"response",
".",
"_update_chunk_length",
"=",
"types",
".",
"MethodType",
"(",
"_update_chunk_length",
",",
"response",
")",
"resp",
"=",
"super",
"(",
"CacheControlAdapter",
",",
"self",
")",
".",
"build_response",
"(",
"request",
",",
"response",
")",
"# See if we should invalidate the cache.",
"if",
"request",
".",
"method",
"in",
"self",
".",
"invalidating_methods",
"and",
"resp",
".",
"ok",
":",
"cache_url",
"=",
"self",
".",
"controller",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"# Give the request a from_cache attr to let people use it",
"resp",
".",
"from_cache",
"=",
"from_cache",
"return",
"resp"
] | Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response | [
"Build",
"a",
"response",
"by",
"making",
"a",
"request",
"or",
"using",
"the",
"cache",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/adapter.py#L57-L129 |
24,954 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | replace_python_tag | def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
"""Replace the Python tag in a wheel file name with a new value.
"""
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts) | python | def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
"""Replace the Python tag in a wheel file name with a new value.
"""
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts) | [
"def",
"replace_python_tag",
"(",
"wheelname",
",",
"new_tag",
")",
":",
"# type: (str, str) -> str",
"parts",
"=",
"wheelname",
".",
"split",
"(",
"'-'",
")",
"parts",
"[",
"-",
"3",
"]",
"=",
"new_tag",
"return",
"'-'",
".",
"join",
"(",
"parts",
")"
] | Replace the Python tag in a wheel file name with a new value. | [
"Replace",
"the",
"Python",
"tag",
"in",
"a",
"wheel",
"file",
"name",
"with",
"a",
"new",
"value",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L98-L104 |
24,955 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | message_about_scripts_not_on_PATH | def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
"""Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
"""
if not scripts:
return None
# Group scripts by the path they were installed in
grouped_by_dir = collections.defaultdict(set) # type: Dict[str, set]
for destfile in scripts:
parent_dir = os.path.dirname(destfile)
script_name = os.path.basename(destfile)
grouped_by_dir[parent_dir].add(script_name)
# We don't want to warn for directories that are on PATH.
not_warn_dirs = [
os.path.normcase(i).rstrip(os.sep) for i in
os.environ.get("PATH", "").split(os.pathsep)
]
# If an executable sits with sys.executable, we don't warn for it.
# This covers the case of venv invocations without activating the venv.
executable_loc = os.environ.get("PIP_PYTHON_PATH", sys.executable)
not_warn_dirs.append(os.path.normcase(os.path.dirname(executable_loc)))
warn_for = {
parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items()
if os.path.normcase(parent_dir) not in not_warn_dirs
}
if not warn_for:
return None
# Format a message
msg_lines = []
for parent_dir, scripts in warn_for.items():
scripts = sorted(scripts)
if len(scripts) == 1:
start_text = "script {} is".format(scripts[0])
else:
start_text = "scripts {} are".format(
", ".join(scripts[:-1]) + " and " + scripts[-1]
)
msg_lines.append(
"The {} installed in '{}' which is not on PATH."
.format(start_text, parent_dir)
)
last_line_fmt = (
"Consider adding {} to PATH or, if you prefer "
"to suppress this warning, use --no-warn-script-location."
)
if len(msg_lines) == 1:
msg_lines.append(last_line_fmt.format("this directory"))
else:
msg_lines.append(last_line_fmt.format("these directories"))
# Returns the formatted multiline message
return "\n".join(msg_lines) | python | def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
"""Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
"""
if not scripts:
return None
# Group scripts by the path they were installed in
grouped_by_dir = collections.defaultdict(set) # type: Dict[str, set]
for destfile in scripts:
parent_dir = os.path.dirname(destfile)
script_name = os.path.basename(destfile)
grouped_by_dir[parent_dir].add(script_name)
# We don't want to warn for directories that are on PATH.
not_warn_dirs = [
os.path.normcase(i).rstrip(os.sep) for i in
os.environ.get("PATH", "").split(os.pathsep)
]
# If an executable sits with sys.executable, we don't warn for it.
# This covers the case of venv invocations without activating the venv.
executable_loc = os.environ.get("PIP_PYTHON_PATH", sys.executable)
not_warn_dirs.append(os.path.normcase(os.path.dirname(executable_loc)))
warn_for = {
parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items()
if os.path.normcase(parent_dir) not in not_warn_dirs
}
if not warn_for:
return None
# Format a message
msg_lines = []
for parent_dir, scripts in warn_for.items():
scripts = sorted(scripts)
if len(scripts) == 1:
start_text = "script {} is".format(scripts[0])
else:
start_text = "scripts {} are".format(
", ".join(scripts[:-1]) + " and " + scripts[-1]
)
msg_lines.append(
"The {} installed in '{}' which is not on PATH."
.format(start_text, parent_dir)
)
last_line_fmt = (
"Consider adding {} to PATH or, if you prefer "
"to suppress this warning, use --no-warn-script-location."
)
if len(msg_lines) == 1:
msg_lines.append(last_line_fmt.format("this directory"))
else:
msg_lines.append(last_line_fmt.format("these directories"))
# Returns the formatted multiline message
return "\n".join(msg_lines) | [
"def",
"message_about_scripts_not_on_PATH",
"(",
"scripts",
")",
":",
"# type: (Sequence[str]) -> Optional[str]",
"if",
"not",
"scripts",
":",
"return",
"None",
"# Group scripts by the path they were installed in",
"grouped_by_dir",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"# type: Dict[str, set]",
"for",
"destfile",
"in",
"scripts",
":",
"parent_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"destfile",
")",
"script_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"destfile",
")",
"grouped_by_dir",
"[",
"parent_dir",
"]",
".",
"add",
"(",
"script_name",
")",
"# We don't want to warn for directories that are on PATH.",
"not_warn_dirs",
"=",
"[",
"os",
".",
"path",
".",
"normcase",
"(",
"i",
")",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"for",
"i",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"\"PATH\"",
",",
"\"\"",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"]",
"# If an executable sits with sys.executable, we don't warn for it.",
"# This covers the case of venv invocations without activating the venv.",
"executable_loc",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PIP_PYTHON_PATH\"",
",",
"sys",
".",
"executable",
")",
"not_warn_dirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"executable_loc",
")",
")",
")",
"warn_for",
"=",
"{",
"parent_dir",
":",
"scripts",
"for",
"parent_dir",
",",
"scripts",
"in",
"grouped_by_dir",
".",
"items",
"(",
")",
"if",
"os",
".",
"path",
".",
"normcase",
"(",
"parent_dir",
")",
"not",
"in",
"not_warn_dirs",
"}",
"if",
"not",
"warn_for",
":",
"return",
"None",
"# Format a message",
"msg_lines",
"=",
"[",
"]",
"for",
"parent_dir",
",",
"scripts",
"in",
"warn_for",
".",
"items",
"(",
")",
":",
"scripts",
"=",
"sorted",
"(",
"scripts",
")",
"if",
"len",
"(",
"scripts",
")",
"==",
"1",
":",
"start_text",
"=",
"\"script {} is\"",
".",
"format",
"(",
"scripts",
"[",
"0",
"]",
")",
"else",
":",
"start_text",
"=",
"\"scripts {} are\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"scripts",
"[",
":",
"-",
"1",
"]",
")",
"+",
"\" and \"",
"+",
"scripts",
"[",
"-",
"1",
"]",
")",
"msg_lines",
".",
"append",
"(",
"\"The {} installed in '{}' which is not on PATH.\"",
".",
"format",
"(",
"start_text",
",",
"parent_dir",
")",
")",
"last_line_fmt",
"=",
"(",
"\"Consider adding {} to PATH or, if you prefer \"",
"\"to suppress this warning, use --no-warn-script-location.\"",
")",
"if",
"len",
"(",
"msg_lines",
")",
"==",
"1",
":",
"msg_lines",
".",
"append",
"(",
"last_line_fmt",
".",
"format",
"(",
"\"this directory\"",
")",
")",
"else",
":",
"msg_lines",
".",
"append",
"(",
"last_line_fmt",
".",
"format",
"(",
"\"these directories\"",
")",
")",
"# Returns the formatted multiline message",
"return",
"\"\\n\"",
".",
"join",
"(",
"msg_lines",
")"
] | Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None. | [
"Determine",
"if",
"any",
"scripts",
"are",
"not",
"on",
"PATH",
"and",
"format",
"a",
"warning",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L180-L239 |
24,956 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | sorted_outrows | def sorted_outrows(outrows):
# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]
"""
Return the given rows of a RECORD file in sorted order.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed to this function, the size can be an integer as an int or string,
or the empty string.
"""
# Normally, there should only be one row per path, in which case the
# second and third elements don't come into play when sorting.
# However, in cases in the wild where a path might happen to occur twice,
# we don't want the sort operation to trigger an error (but still want
# determinism). Since the third element can be an int or string, we
# coerce each element to a string to avoid a TypeError in this case.
# For additional background, see--
# https://github.com/pypa/pip/issues/5868
return sorted(outrows, key=lambda row: tuple(str(x) for x in row)) | python | def sorted_outrows(outrows):
# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]
"""
Return the given rows of a RECORD file in sorted order.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed to this function, the size can be an integer as an int or string,
or the empty string.
"""
# Normally, there should only be one row per path, in which case the
# second and third elements don't come into play when sorting.
# However, in cases in the wild where a path might happen to occur twice,
# we don't want the sort operation to trigger an error (but still want
# determinism). Since the third element can be an int or string, we
# coerce each element to a string to avoid a TypeError in this case.
# For additional background, see--
# https://github.com/pypa/pip/issues/5868
return sorted(outrows, key=lambda row: tuple(str(x) for x in row)) | [
"def",
"sorted_outrows",
"(",
"outrows",
")",
":",
"# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]",
"# Normally, there should only be one row per path, in which case the",
"# second and third elements don't come into play when sorting.",
"# However, in cases in the wild where a path might happen to occur twice,",
"# we don't want the sort operation to trigger an error (but still want",
"# determinism). Since the third element can be an int or string, we",
"# coerce each element to a string to avoid a TypeError in this case.",
"# For additional background, see--",
"# https://github.com/pypa/pip/issues/5868",
"return",
"sorted",
"(",
"outrows",
",",
"key",
"=",
"lambda",
"row",
":",
"tuple",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"row",
")",
")"
] | Return the given rows of a RECORD file in sorted order.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed to this function, the size can be an integer as an int or string,
or the empty string. | [
"Return",
"the",
"given",
"rows",
"of",
"a",
"RECORD",
"file",
"in",
"sorted",
"order",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L242-L260 |
24,957 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | wheel_version | def wheel_version(source_dir):
# type: (Optional[str]) -> Optional[Tuple[int, ...]]
"""
Return the Wheel-Version of an extracted wheel, if possible.
Otherwise, return None if we couldn't parse / extract it.
"""
try:
dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0]
wheel_data = dist.get_metadata('WHEEL')
wheel_data = Parser().parsestr(wheel_data)
version = wheel_data['Wheel-Version'].strip()
version = tuple(map(int, version.split('.')))
return version
except Exception:
return None | python | def wheel_version(source_dir):
# type: (Optional[str]) -> Optional[Tuple[int, ...]]
"""
Return the Wheel-Version of an extracted wheel, if possible.
Otherwise, return None if we couldn't parse / extract it.
"""
try:
dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0]
wheel_data = dist.get_metadata('WHEEL')
wheel_data = Parser().parsestr(wheel_data)
version = wheel_data['Wheel-Version'].strip()
version = tuple(map(int, version.split('.')))
return version
except Exception:
return None | [
"def",
"wheel_version",
"(",
"source_dir",
")",
":",
"# type: (Optional[str]) -> Optional[Tuple[int, ...]]",
"try",
":",
"dist",
"=",
"[",
"d",
"for",
"d",
"in",
"pkg_resources",
".",
"find_on_path",
"(",
"None",
",",
"source_dir",
")",
"]",
"[",
"0",
"]",
"wheel_data",
"=",
"dist",
".",
"get_metadata",
"(",
"'WHEEL'",
")",
"wheel_data",
"=",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"wheel_data",
")",
"version",
"=",
"wheel_data",
"[",
"'Wheel-Version'",
"]",
".",
"strip",
"(",
")",
"version",
"=",
"tuple",
"(",
"map",
"(",
"int",
",",
"version",
".",
"split",
"(",
"'.'",
")",
")",
")",
"return",
"version",
"except",
"Exception",
":",
"return",
"None"
] | Return the Wheel-Version of an extracted wheel, if possible.
Otherwise, return None if we couldn't parse / extract it. | [
"Return",
"the",
"Wheel",
"-",
"Version",
"of",
"an",
"extracted",
"wheel",
"if",
"possible",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L617-L634 |
24,958 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | _contains_egg_info | def _contains_egg_info(
s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)):
"""Determine whether the string looks like an egg_info.
:param s: The string to parse. E.g. foo-2.1
"""
return bool(_egg_info_re.search(s)) | python | def _contains_egg_info(
s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)):
"""Determine whether the string looks like an egg_info.
:param s: The string to parse. E.g. foo-2.1
"""
return bool(_egg_info_re.search(s)) | [
"def",
"_contains_egg_info",
"(",
"s",
",",
"_egg_info_re",
"=",
"re",
".",
"compile",
"(",
"r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)'",
",",
"re",
".",
"I",
")",
")",
":",
"return",
"bool",
"(",
"_egg_info_re",
".",
"search",
"(",
"s",
")",
")"
] | Determine whether the string looks like an egg_info.
:param s: The string to parse. E.g. foo-2.1 | [
"Determine",
"whether",
"the",
"string",
"looks",
"like",
"an",
"egg_info",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L727-L733 |
24,959 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | should_use_ephemeral_cache | def should_use_ephemeral_cache(
req, # type: InstallRequirement
format_control, # type: FormatControl
autobuilding, # type: bool
cache_available # type: bool
):
# type: (...) -> Optional[bool]
"""
Return whether to build an InstallRequirement object using the
ephemeral cache.
:param cache_available: whether a cache directory is available for the
autobuilding=True case.
:return: True or False to build the requirement with ephem_cache=True
or False, respectively; or None not to build the requirement.
"""
if req.constraint:
return None
if req.is_wheel:
if not autobuilding:
logger.info(
'Skipping %s, due to already being wheel.', req.name,
)
return None
if not autobuilding:
return False
if req.editable or not req.source_dir:
return None
if req.link and not req.link.is_artifact:
# VCS checkout. Build wheel just for this run.
return True
if "binary" not in format_control.get_allowed_formats(
canonicalize_name(req.name)):
logger.info(
"Skipping bdist_wheel for %s, due to binaries "
"being disabled for it.", req.name,
)
return None
link = req.link
base, ext = link.splitext()
if cache_available and _contains_egg_info(base):
return False
# Otherwise, build the wheel just for this run using the ephemeral
# cache since we are either in the case of e.g. a local directory, or
# no cache directory is available to use.
return True | python | def should_use_ephemeral_cache(
req, # type: InstallRequirement
format_control, # type: FormatControl
autobuilding, # type: bool
cache_available # type: bool
):
# type: (...) -> Optional[bool]
"""
Return whether to build an InstallRequirement object using the
ephemeral cache.
:param cache_available: whether a cache directory is available for the
autobuilding=True case.
:return: True or False to build the requirement with ephem_cache=True
or False, respectively; or None not to build the requirement.
"""
if req.constraint:
return None
if req.is_wheel:
if not autobuilding:
logger.info(
'Skipping %s, due to already being wheel.', req.name,
)
return None
if not autobuilding:
return False
if req.editable or not req.source_dir:
return None
if req.link and not req.link.is_artifact:
# VCS checkout. Build wheel just for this run.
return True
if "binary" not in format_control.get_allowed_formats(
canonicalize_name(req.name)):
logger.info(
"Skipping bdist_wheel for %s, due to binaries "
"being disabled for it.", req.name,
)
return None
link = req.link
base, ext = link.splitext()
if cache_available and _contains_egg_info(base):
return False
# Otherwise, build the wheel just for this run using the ephemeral
# cache since we are either in the case of e.g. a local directory, or
# no cache directory is available to use.
return True | [
"def",
"should_use_ephemeral_cache",
"(",
"req",
",",
"# type: InstallRequirement",
"format_control",
",",
"# type: FormatControl",
"autobuilding",
",",
"# type: bool",
"cache_available",
"# type: bool",
")",
":",
"# type: (...) -> Optional[bool]",
"if",
"req",
".",
"constraint",
":",
"return",
"None",
"if",
"req",
".",
"is_wheel",
":",
"if",
"not",
"autobuilding",
":",
"logger",
".",
"info",
"(",
"'Skipping %s, due to already being wheel.'",
",",
"req",
".",
"name",
",",
")",
"return",
"None",
"if",
"not",
"autobuilding",
":",
"return",
"False",
"if",
"req",
".",
"editable",
"or",
"not",
"req",
".",
"source_dir",
":",
"return",
"None",
"if",
"req",
".",
"link",
"and",
"not",
"req",
".",
"link",
".",
"is_artifact",
":",
"# VCS checkout. Build wheel just for this run.",
"return",
"True",
"if",
"\"binary\"",
"not",
"in",
"format_control",
".",
"get_allowed_formats",
"(",
"canonicalize_name",
"(",
"req",
".",
"name",
")",
")",
":",
"logger",
".",
"info",
"(",
"\"Skipping bdist_wheel for %s, due to binaries \"",
"\"being disabled for it.\"",
",",
"req",
".",
"name",
",",
")",
"return",
"None",
"link",
"=",
"req",
".",
"link",
"base",
",",
"ext",
"=",
"link",
".",
"splitext",
"(",
")",
"if",
"cache_available",
"and",
"_contains_egg_info",
"(",
"base",
")",
":",
"return",
"False",
"# Otherwise, build the wheel just for this run using the ephemeral",
"# cache since we are either in the case of e.g. a local directory, or",
"# no cache directory is available to use.",
"return",
"True"
] | Return whether to build an InstallRequirement object using the
ephemeral cache.
:param cache_available: whether a cache directory is available for the
autobuilding=True case.
:return: True or False to build the requirement with ephem_cache=True
or False, respectively; or None not to build the requirement. | [
"Return",
"whether",
"to",
"build",
"an",
"InstallRequirement",
"object",
"using",
"the",
"ephemeral",
"cache",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L736-L787 |
24,960 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | format_command | def format_command(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
"""
Format command information for logging.
"""
text = 'Command arguments: {}\n'.format(command_args)
if not command_output:
text += 'Command output: None'
elif logger.getEffectiveLevel() > logging.DEBUG:
text += 'Command output: [use --verbose to show]'
else:
if not command_output.endswith('\n'):
command_output += '\n'
text += (
'Command output:\n{}'
'-----------------------------------------'
).format(command_output)
return text | python | def format_command(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
"""
Format command information for logging.
"""
text = 'Command arguments: {}\n'.format(command_args)
if not command_output:
text += 'Command output: None'
elif logger.getEffectiveLevel() > logging.DEBUG:
text += 'Command output: [use --verbose to show]'
else:
if not command_output.endswith('\n'):
command_output += '\n'
text += (
'Command output:\n{}'
'-----------------------------------------'
).format(command_output)
return text | [
"def",
"format_command",
"(",
"command_args",
",",
"# type: List[str]",
"command_output",
",",
"# type: str",
")",
":",
"# type: (...) -> str",
"text",
"=",
"'Command arguments: {}\\n'",
".",
"format",
"(",
"command_args",
")",
"if",
"not",
"command_output",
":",
"text",
"+=",
"'Command output: None'",
"elif",
"logger",
".",
"getEffectiveLevel",
"(",
")",
">",
"logging",
".",
"DEBUG",
":",
"text",
"+=",
"'Command output: [use --verbose to show]'",
"else",
":",
"if",
"not",
"command_output",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"command_output",
"+=",
"'\\n'",
"text",
"+=",
"(",
"'Command output:\\n{}'",
"'-----------------------------------------'",
")",
".",
"format",
"(",
"command_output",
")",
"return",
"text"
] | Format command information for logging. | [
"Format",
"command",
"information",
"for",
"logging",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L790-L812 |
24,961 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | get_legacy_build_wheel_path | def get_legacy_build_wheel_path(
names, # type: List[str]
temp_dir, # type: str
req, # type: InstallRequirement
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> Optional[str]
"""
Return the path to the wheel in the temporary build directory.
"""
# Sort for determinism.
names = sorted(names)
if not names:
msg = (
'Legacy build of wheel for {!r} created no files.\n'
).format(req.name)
msg += format_command(command_args, command_output)
logger.warning(msg)
return None
if len(names) > 1:
msg = (
'Legacy build of wheel for {!r} created more than one file.\n'
'Filenames (choosing first): {}\n'
).format(req.name, names)
msg += format_command(command_args, command_output)
logger.warning(msg)
return os.path.join(temp_dir, names[0]) | python | def get_legacy_build_wheel_path(
names, # type: List[str]
temp_dir, # type: str
req, # type: InstallRequirement
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> Optional[str]
"""
Return the path to the wheel in the temporary build directory.
"""
# Sort for determinism.
names = sorted(names)
if not names:
msg = (
'Legacy build of wheel for {!r} created no files.\n'
).format(req.name)
msg += format_command(command_args, command_output)
logger.warning(msg)
return None
if len(names) > 1:
msg = (
'Legacy build of wheel for {!r} created more than one file.\n'
'Filenames (choosing first): {}\n'
).format(req.name, names)
msg += format_command(command_args, command_output)
logger.warning(msg)
return os.path.join(temp_dir, names[0]) | [
"def",
"get_legacy_build_wheel_path",
"(",
"names",
",",
"# type: List[str]",
"temp_dir",
",",
"# type: str",
"req",
",",
"# type: InstallRequirement",
"command_args",
",",
"# type: List[str]",
"command_output",
",",
"# type: str",
")",
":",
"# type: (...) -> Optional[str]",
"# Sort for determinism.",
"names",
"=",
"sorted",
"(",
"names",
")",
"if",
"not",
"names",
":",
"msg",
"=",
"(",
"'Legacy build of wheel for {!r} created no files.\\n'",
")",
".",
"format",
"(",
"req",
".",
"name",
")",
"msg",
"+=",
"format_command",
"(",
"command_args",
",",
"command_output",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"return",
"None",
"if",
"len",
"(",
"names",
")",
">",
"1",
":",
"msg",
"=",
"(",
"'Legacy build of wheel for {!r} created more than one file.\\n'",
"'Filenames (choosing first): {}\\n'",
")",
".",
"format",
"(",
"req",
".",
"name",
",",
"names",
")",
"msg",
"+=",
"format_command",
"(",
"command_args",
",",
"command_output",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"names",
"[",
"0",
"]",
")"
] | Return the path to the wheel in the temporary build directory. | [
"Return",
"the",
"path",
"to",
"the",
"wheel",
"in",
"the",
"temporary",
"build",
"directory",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L815-L844 |
24,962 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | Wheel.supported | def supported(self, tags=None):
# type: (Optional[List[Pep425Tag]]) -> bool
"""Is this wheel supported on this system?"""
if tags is None: # for mock
tags = pep425tags.get_supported()
return bool(set(tags).intersection(self.file_tags)) | python | def supported(self, tags=None):
# type: (Optional[List[Pep425Tag]]) -> bool
"""Is this wheel supported on this system?"""
if tags is None: # for mock
tags = pep425tags.get_supported()
return bool(set(tags).intersection(self.file_tags)) | [
"def",
"supported",
"(",
"self",
",",
"tags",
"=",
"None",
")",
":",
"# type: (Optional[List[Pep425Tag]]) -> bool",
"if",
"tags",
"is",
"None",
":",
"# for mock",
"tags",
"=",
"pep425tags",
".",
"get_supported",
"(",
")",
"return",
"bool",
"(",
"set",
"(",
"tags",
")",
".",
"intersection",
"(",
"self",
".",
"file_tags",
")",
")"
] | Is this wheel supported on this system? | [
"Is",
"this",
"wheel",
"supported",
"on",
"this",
"system?"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L719-L724 |
24,963 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | WheelBuilder._build_one | def _build_one(self, req, output_dir, python_tag=None):
"""Build one wheel.
:return: The filename of the built wheel, or None if the build failed.
"""
# Install build deps into temporary directory (PEP 518)
with req.build_env:
return self._build_one_inside_env(req, output_dir,
python_tag=python_tag) | python | def _build_one(self, req, output_dir, python_tag=None):
"""Build one wheel.
:return: The filename of the built wheel, or None if the build failed.
"""
# Install build deps into temporary directory (PEP 518)
with req.build_env:
return self._build_one_inside_env(req, output_dir,
python_tag=python_tag) | [
"def",
"_build_one",
"(",
"self",
",",
"req",
",",
"output_dir",
",",
"python_tag",
"=",
"None",
")",
":",
"# Install build deps into temporary directory (PEP 518)",
"with",
"req",
".",
"build_env",
":",
"return",
"self",
".",
"_build_one_inside_env",
"(",
"req",
",",
"output_dir",
",",
"python_tag",
"=",
"python_tag",
")"
] | Build one wheel.
:return: The filename of the built wheel, or None if the build failed. | [
"Build",
"one",
"wheel",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L870-L878 |
24,964 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | WheelBuilder._build_one_pep517 | def _build_one_pep517(self, req, tempd, python_tag=None):
"""Build one InstallRequirement using the PEP 517 build process.
Returns path to wheel if successfully built. Otherwise, returns None.
"""
assert req.metadata_directory is not None
try:
req.spin_message = 'Building wheel for %s (PEP 517)' % (req.name,)
logger.debug('Destination directory: %s', tempd)
wheel_name = req.pep517_backend.build_wheel(
tempd,
metadata_directory=req.metadata_directory
)
if python_tag:
# General PEP 517 backends don't necessarily support
# a "--python-tag" option, so we rename the wheel
# file directly.
new_name = replace_python_tag(wheel_name, python_tag)
os.rename(
os.path.join(tempd, wheel_name),
os.path.join(tempd, new_name)
)
# Reassign to simplify the return at the end of function
wheel_name = new_name
except Exception:
logger.error('Failed building wheel for %s', req.name)
return None
return os.path.join(tempd, wheel_name) | python | def _build_one_pep517(self, req, tempd, python_tag=None):
"""Build one InstallRequirement using the PEP 517 build process.
Returns path to wheel if successfully built. Otherwise, returns None.
"""
assert req.metadata_directory is not None
try:
req.spin_message = 'Building wheel for %s (PEP 517)' % (req.name,)
logger.debug('Destination directory: %s', tempd)
wheel_name = req.pep517_backend.build_wheel(
tempd,
metadata_directory=req.metadata_directory
)
if python_tag:
# General PEP 517 backends don't necessarily support
# a "--python-tag" option, so we rename the wheel
# file directly.
new_name = replace_python_tag(wheel_name, python_tag)
os.rename(
os.path.join(tempd, wheel_name),
os.path.join(tempd, new_name)
)
# Reassign to simplify the return at the end of function
wheel_name = new_name
except Exception:
logger.error('Failed building wheel for %s', req.name)
return None
return os.path.join(tempd, wheel_name) | [
"def",
"_build_one_pep517",
"(",
"self",
",",
"req",
",",
"tempd",
",",
"python_tag",
"=",
"None",
")",
":",
"assert",
"req",
".",
"metadata_directory",
"is",
"not",
"None",
"try",
":",
"req",
".",
"spin_message",
"=",
"'Building wheel for %s (PEP 517)'",
"%",
"(",
"req",
".",
"name",
",",
")",
"logger",
".",
"debug",
"(",
"'Destination directory: %s'",
",",
"tempd",
")",
"wheel_name",
"=",
"req",
".",
"pep517_backend",
".",
"build_wheel",
"(",
"tempd",
",",
"metadata_directory",
"=",
"req",
".",
"metadata_directory",
")",
"if",
"python_tag",
":",
"# General PEP 517 backends don't necessarily support",
"# a \"--python-tag\" option, so we rename the wheel",
"# file directly.",
"new_name",
"=",
"replace_python_tag",
"(",
"wheel_name",
",",
"python_tag",
")",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tempd",
",",
"wheel_name",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"tempd",
",",
"new_name",
")",
")",
"# Reassign to simplify the return at the end of function",
"wheel_name",
"=",
"new_name",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"'Failed building wheel for %s'",
",",
"req",
".",
"name",
")",
"return",
"None",
"return",
"os",
".",
"path",
".",
"join",
"(",
"tempd",
",",
"wheel_name",
")"
] | Build one InstallRequirement using the PEP 517 build process.
Returns path to wheel if successfully built. Otherwise, returns None. | [
"Build",
"one",
"InstallRequirement",
"using",
"the",
"PEP",
"517",
"build",
"process",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L911-L938 |
24,965 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | WheelBuilder._build_one_legacy | def _build_one_legacy(self, req, tempd, python_tag=None):
"""Build one InstallRequirement using the "legacy" build process.
Returns path to wheel if successfully built. Otherwise, returns None.
"""
base_args = self._base_setup_args(req)
spin_message = 'Building wheel for %s (setup.py)' % (req.name,)
with open_spinner(spin_message) as spinner:
logger.debug('Destination directory: %s', tempd)
wheel_args = base_args + ['bdist_wheel', '-d', tempd] \
+ self.build_options
if python_tag is not None:
wheel_args += ["--python-tag", python_tag]
try:
output = call_subprocess(wheel_args, cwd=req.setup_py_dir,
show_stdout=False, spinner=spinner)
except Exception:
spinner.finish("error")
logger.error('Failed building wheel for %s', req.name)
return None
names = os.listdir(tempd)
wheel_path = get_legacy_build_wheel_path(
names=names,
temp_dir=tempd,
req=req,
command_args=wheel_args,
command_output=output,
)
return wheel_path | python | def _build_one_legacy(self, req, tempd, python_tag=None):
"""Build one InstallRequirement using the "legacy" build process.
Returns path to wheel if successfully built. Otherwise, returns None.
"""
base_args = self._base_setup_args(req)
spin_message = 'Building wheel for %s (setup.py)' % (req.name,)
with open_spinner(spin_message) as spinner:
logger.debug('Destination directory: %s', tempd)
wheel_args = base_args + ['bdist_wheel', '-d', tempd] \
+ self.build_options
if python_tag is not None:
wheel_args += ["--python-tag", python_tag]
try:
output = call_subprocess(wheel_args, cwd=req.setup_py_dir,
show_stdout=False, spinner=spinner)
except Exception:
spinner.finish("error")
logger.error('Failed building wheel for %s', req.name)
return None
names = os.listdir(tempd)
wheel_path = get_legacy_build_wheel_path(
names=names,
temp_dir=tempd,
req=req,
command_args=wheel_args,
command_output=output,
)
return wheel_path | [
"def",
"_build_one_legacy",
"(",
"self",
",",
"req",
",",
"tempd",
",",
"python_tag",
"=",
"None",
")",
":",
"base_args",
"=",
"self",
".",
"_base_setup_args",
"(",
"req",
")",
"spin_message",
"=",
"'Building wheel for %s (setup.py)'",
"%",
"(",
"req",
".",
"name",
",",
")",
"with",
"open_spinner",
"(",
"spin_message",
")",
"as",
"spinner",
":",
"logger",
".",
"debug",
"(",
"'Destination directory: %s'",
",",
"tempd",
")",
"wheel_args",
"=",
"base_args",
"+",
"[",
"'bdist_wheel'",
",",
"'-d'",
",",
"tempd",
"]",
"+",
"self",
".",
"build_options",
"if",
"python_tag",
"is",
"not",
"None",
":",
"wheel_args",
"+=",
"[",
"\"--python-tag\"",
",",
"python_tag",
"]",
"try",
":",
"output",
"=",
"call_subprocess",
"(",
"wheel_args",
",",
"cwd",
"=",
"req",
".",
"setup_py_dir",
",",
"show_stdout",
"=",
"False",
",",
"spinner",
"=",
"spinner",
")",
"except",
"Exception",
":",
"spinner",
".",
"finish",
"(",
"\"error\"",
")",
"logger",
".",
"error",
"(",
"'Failed building wheel for %s'",
",",
"req",
".",
"name",
")",
"return",
"None",
"names",
"=",
"os",
".",
"listdir",
"(",
"tempd",
")",
"wheel_path",
"=",
"get_legacy_build_wheel_path",
"(",
"names",
"=",
"names",
",",
"temp_dir",
"=",
"tempd",
",",
"req",
"=",
"req",
",",
"command_args",
"=",
"wheel_args",
",",
"command_output",
"=",
"output",
",",
")",
"return",
"wheel_path"
] | Build one InstallRequirement using the "legacy" build process.
Returns path to wheel if successfully built. Otherwise, returns None. | [
"Build",
"one",
"InstallRequirement",
"using",
"the",
"legacy",
"build",
"process",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L940-L971 |
24,966 | pypa/pipenv | pipenv/patched/notpip/_internal/wheel.py | WheelBuilder.build | def build(
self,
requirements, # type: Iterable[InstallRequirement]
session, # type: PipSession
autobuilding=False # type: bool
):
# type: (...) -> List[InstallRequirement]
"""Build wheels.
:param unpack: If True, replace the sdist we built from with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly.
"""
buildset = []
format_control = self.finder.format_control
# Whether a cache directory is available for autobuilding=True.
cache_available = bool(self._wheel_dir or self.wheel_cache.cache_dir)
for req in requirements:
ephem_cache = should_use_ephemeral_cache(
req, format_control=format_control, autobuilding=autobuilding,
cache_available=cache_available,
)
if ephem_cache is None:
continue
buildset.append((req, ephem_cache))
if not buildset:
return []
# Is any wheel build not using the ephemeral cache?
if any(not ephem_cache for _, ephem_cache in buildset):
have_directory_for_build = self._wheel_dir or (
autobuilding and self.wheel_cache.cache_dir
)
assert have_directory_for_build
# TODO by @pradyunsg
# Should break up this method into 2 separate methods.
# Build the wheels.
logger.info(
'Building wheels for collected packages: %s',
', '.join([req.name for (req, _) in buildset]),
)
_cache = self.wheel_cache # shorter name
with indent_log():
build_success, build_failure = [], []
for req, ephem in buildset:
python_tag = None
if autobuilding:
python_tag = pep425tags.implementation_tag
if ephem:
output_dir = _cache.get_ephem_path_for_link(req.link)
else:
output_dir = _cache.get_path_for_link(req.link)
try:
ensure_dir(output_dir)
except OSError as e:
logger.warning("Building wheel for %s failed: %s",
req.name, e)
build_failure.append(req)
continue
else:
output_dir = self._wheel_dir
wheel_file = self._build_one(
req, output_dir,
python_tag=python_tag,
)
if wheel_file:
build_success.append(req)
if autobuilding:
# XXX: This is mildly duplicative with prepare_files,
# but not close enough to pull out to a single common
# method.
# The code below assumes temporary source dirs -
# prevent it doing bad things.
if req.source_dir and not os.path.exists(os.path.join(
req.source_dir, PIP_DELETE_MARKER_FILENAME)):
raise AssertionError(
"bad source dir - missing marker")
# Delete the source we built the wheel from
req.remove_temporary_source()
# set the build directory again - name is known from
# the work prepare_files did.
req.source_dir = req.build_location(
self.preparer.build_dir
)
# Update the link for this.
req.link = Link(path_to_url(wheel_file))
assert req.link.is_wheel
# extract the wheel into the dir
unpack_url(
req.link, req.source_dir, None, False,
session=session,
)
else:
build_failure.append(req)
# notify success/failure
if build_success:
logger.info(
'Successfully built %s',
' '.join([req.name for req in build_success]),
)
if build_failure:
logger.info(
'Failed to build %s',
' '.join([req.name for req in build_failure]),
)
# Return a list of requirements that failed to build
return build_failure | python | def build(
self,
requirements, # type: Iterable[InstallRequirement]
session, # type: PipSession
autobuilding=False # type: bool
):
# type: (...) -> List[InstallRequirement]
"""Build wheels.
:param unpack: If True, replace the sdist we built from with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly.
"""
buildset = []
format_control = self.finder.format_control
# Whether a cache directory is available for autobuilding=True.
cache_available = bool(self._wheel_dir or self.wheel_cache.cache_dir)
for req in requirements:
ephem_cache = should_use_ephemeral_cache(
req, format_control=format_control, autobuilding=autobuilding,
cache_available=cache_available,
)
if ephem_cache is None:
continue
buildset.append((req, ephem_cache))
if not buildset:
return []
# Is any wheel build not using the ephemeral cache?
if any(not ephem_cache for _, ephem_cache in buildset):
have_directory_for_build = self._wheel_dir or (
autobuilding and self.wheel_cache.cache_dir
)
assert have_directory_for_build
# TODO by @pradyunsg
# Should break up this method into 2 separate methods.
# Build the wheels.
logger.info(
'Building wheels for collected packages: %s',
', '.join([req.name for (req, _) in buildset]),
)
_cache = self.wheel_cache # shorter name
with indent_log():
build_success, build_failure = [], []
for req, ephem in buildset:
python_tag = None
if autobuilding:
python_tag = pep425tags.implementation_tag
if ephem:
output_dir = _cache.get_ephem_path_for_link(req.link)
else:
output_dir = _cache.get_path_for_link(req.link)
try:
ensure_dir(output_dir)
except OSError as e:
logger.warning("Building wheel for %s failed: %s",
req.name, e)
build_failure.append(req)
continue
else:
output_dir = self._wheel_dir
wheel_file = self._build_one(
req, output_dir,
python_tag=python_tag,
)
if wheel_file:
build_success.append(req)
if autobuilding:
# XXX: This is mildly duplicative with prepare_files,
# but not close enough to pull out to a single common
# method.
# The code below assumes temporary source dirs -
# prevent it doing bad things.
if req.source_dir and not os.path.exists(os.path.join(
req.source_dir, PIP_DELETE_MARKER_FILENAME)):
raise AssertionError(
"bad source dir - missing marker")
# Delete the source we built the wheel from
req.remove_temporary_source()
# set the build directory again - name is known from
# the work prepare_files did.
req.source_dir = req.build_location(
self.preparer.build_dir
)
# Update the link for this.
req.link = Link(path_to_url(wheel_file))
assert req.link.is_wheel
# extract the wheel into the dir
unpack_url(
req.link, req.source_dir, None, False,
session=session,
)
else:
build_failure.append(req)
# notify success/failure
if build_success:
logger.info(
'Successfully built %s',
' '.join([req.name for req in build_success]),
)
if build_failure:
logger.info(
'Failed to build %s',
' '.join([req.name for req in build_failure]),
)
# Return a list of requirements that failed to build
return build_failure | [
"def",
"build",
"(",
"self",
",",
"requirements",
",",
"# type: Iterable[InstallRequirement]",
"session",
",",
"# type: PipSession",
"autobuilding",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> List[InstallRequirement]",
"buildset",
"=",
"[",
"]",
"format_control",
"=",
"self",
".",
"finder",
".",
"format_control",
"# Whether a cache directory is available for autobuilding=True.",
"cache_available",
"=",
"bool",
"(",
"self",
".",
"_wheel_dir",
"or",
"self",
".",
"wheel_cache",
".",
"cache_dir",
")",
"for",
"req",
"in",
"requirements",
":",
"ephem_cache",
"=",
"should_use_ephemeral_cache",
"(",
"req",
",",
"format_control",
"=",
"format_control",
",",
"autobuilding",
"=",
"autobuilding",
",",
"cache_available",
"=",
"cache_available",
",",
")",
"if",
"ephem_cache",
"is",
"None",
":",
"continue",
"buildset",
".",
"append",
"(",
"(",
"req",
",",
"ephem_cache",
")",
")",
"if",
"not",
"buildset",
":",
"return",
"[",
"]",
"# Is any wheel build not using the ephemeral cache?",
"if",
"any",
"(",
"not",
"ephem_cache",
"for",
"_",
",",
"ephem_cache",
"in",
"buildset",
")",
":",
"have_directory_for_build",
"=",
"self",
".",
"_wheel_dir",
"or",
"(",
"autobuilding",
"and",
"self",
".",
"wheel_cache",
".",
"cache_dir",
")",
"assert",
"have_directory_for_build",
"# TODO by @pradyunsg",
"# Should break up this method into 2 separate methods.",
"# Build the wheels.",
"logger",
".",
"info",
"(",
"'Building wheels for collected packages: %s'",
",",
"', '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"(",
"req",
",",
"_",
")",
"in",
"buildset",
"]",
")",
",",
")",
"_cache",
"=",
"self",
".",
"wheel_cache",
"# shorter name",
"with",
"indent_log",
"(",
")",
":",
"build_success",
",",
"build_failure",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"req",
",",
"ephem",
"in",
"buildset",
":",
"python_tag",
"=",
"None",
"if",
"autobuilding",
":",
"python_tag",
"=",
"pep425tags",
".",
"implementation_tag",
"if",
"ephem",
":",
"output_dir",
"=",
"_cache",
".",
"get_ephem_path_for_link",
"(",
"req",
".",
"link",
")",
"else",
":",
"output_dir",
"=",
"_cache",
".",
"get_path_for_link",
"(",
"req",
".",
"link",
")",
"try",
":",
"ensure_dir",
"(",
"output_dir",
")",
"except",
"OSError",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"Building wheel for %s failed: %s\"",
",",
"req",
".",
"name",
",",
"e",
")",
"build_failure",
".",
"append",
"(",
"req",
")",
"continue",
"else",
":",
"output_dir",
"=",
"self",
".",
"_wheel_dir",
"wheel_file",
"=",
"self",
".",
"_build_one",
"(",
"req",
",",
"output_dir",
",",
"python_tag",
"=",
"python_tag",
",",
")",
"if",
"wheel_file",
":",
"build_success",
".",
"append",
"(",
"req",
")",
"if",
"autobuilding",
":",
"# XXX: This is mildly duplicative with prepare_files,",
"# but not close enough to pull out to a single common",
"# method.",
"# The code below assumes temporary source dirs -",
"# prevent it doing bad things.",
"if",
"req",
".",
"source_dir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"req",
".",
"source_dir",
",",
"PIP_DELETE_MARKER_FILENAME",
")",
")",
":",
"raise",
"AssertionError",
"(",
"\"bad source dir - missing marker\"",
")",
"# Delete the source we built the wheel from",
"req",
".",
"remove_temporary_source",
"(",
")",
"# set the build directory again - name is known from",
"# the work prepare_files did.",
"req",
".",
"source_dir",
"=",
"req",
".",
"build_location",
"(",
"self",
".",
"preparer",
".",
"build_dir",
")",
"# Update the link for this.",
"req",
".",
"link",
"=",
"Link",
"(",
"path_to_url",
"(",
"wheel_file",
")",
")",
"assert",
"req",
".",
"link",
".",
"is_wheel",
"# extract the wheel into the dir",
"unpack_url",
"(",
"req",
".",
"link",
",",
"req",
".",
"source_dir",
",",
"None",
",",
"False",
",",
"session",
"=",
"session",
",",
")",
"else",
":",
"build_failure",
".",
"append",
"(",
"req",
")",
"# notify success/failure",
"if",
"build_success",
":",
"logger",
".",
"info",
"(",
"'Successfully built %s'",
",",
"' '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"build_success",
"]",
")",
",",
")",
"if",
"build_failure",
":",
"logger",
".",
"info",
"(",
"'Failed to build %s'",
",",
"' '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"build_failure",
"]",
")",
",",
")",
"# Return a list of requirements that failed to build",
"return",
"build_failure"
] | Build wheels.
:param unpack: If True, replace the sdist we built from with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly. | [
"Build",
"wheels",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L985-L1097 |
24,967 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.read_configuration | def read_configuration(self):
"""
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
"""
# get distutils to do the work
c = self._get_pypirc_command()
c.repository = self.url
cfg = c._read_pypirc()
self.username = cfg.get('username')
self.password = cfg.get('password')
self.realm = cfg.get('realm', 'pypi')
self.url = cfg.get('repository', self.url) | python | def read_configuration(self):
"""
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
"""
# get distutils to do the work
c = self._get_pypirc_command()
c.repository = self.url
cfg = c._read_pypirc()
self.username = cfg.get('username')
self.password = cfg.get('password')
self.realm = cfg.get('realm', 'pypi')
self.url = cfg.get('repository', self.url) | [
"def",
"read_configuration",
"(",
"self",
")",
":",
"# get distutils to do the work",
"c",
"=",
"self",
".",
"_get_pypirc_command",
"(",
")",
"c",
".",
"repository",
"=",
"self",
".",
"url",
"cfg",
"=",
"c",
".",
"_read_pypirc",
"(",
")",
"self",
".",
"username",
"=",
"cfg",
".",
"get",
"(",
"'username'",
")",
"self",
".",
"password",
"=",
"cfg",
".",
"get",
"(",
"'password'",
")",
"self",
".",
"realm",
"=",
"cfg",
".",
"get",
"(",
"'realm'",
",",
"'pypi'",
")",
"self",
".",
"url",
"=",
"cfg",
".",
"get",
"(",
"'repository'",
",",
"self",
".",
"url",
")"
] | Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration. | [
"Read",
"the",
"PyPI",
"access",
"configuration",
"as",
"supported",
"by",
"distutils",
"getting",
"PyPI",
"to",
"do",
"the",
"actual",
"work",
".",
"This",
"populates",
"username",
"password",
"realm",
"and",
"url",
"attributes",
"from",
"the",
"configuration",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L75-L88 |
24,968 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.save_configuration | def save_configuration(self):
"""
Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method.
Again, distutils is used to do the actual work.
"""
self.check_credentials()
# get distutils to do the work
c = self._get_pypirc_command()
c._store_pypirc(self.username, self.password) | python | def save_configuration(self):
"""
Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method.
Again, distutils is used to do the actual work.
"""
self.check_credentials()
# get distutils to do the work
c = self._get_pypirc_command()
c._store_pypirc(self.username, self.password) | [
"def",
"save_configuration",
"(",
"self",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"# get distutils to do the work",
"c",
"=",
"self",
".",
"_get_pypirc_command",
"(",
")",
"c",
".",
"_store_pypirc",
"(",
"self",
".",
"username",
",",
"self",
".",
"password",
")"
] | Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method.
Again, distutils is used to do the actual work. | [
"Save",
"the",
"PyPI",
"access",
"configuration",
".",
"You",
"must",
"have",
"set",
"username",
"and",
"password",
"attributes",
"before",
"calling",
"this",
"method",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L90-L100 |
24,969 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.check_credentials | def check_credentials(self):
"""
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
"""
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
_, netloc, _, _, _, _ = urlparse(self.url)
pm.add_password(self.realm, netloc, self.username, self.password)
self.password_handler = HTTPBasicAuthHandler(pm) | python | def check_credentials(self):
"""
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
"""
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
_, netloc, _, _, _, _ = urlparse(self.url)
pm.add_password(self.realm, netloc, self.username, self.password)
self.password_handler = HTTPBasicAuthHandler(pm) | [
"def",
"check_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"password",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'username and password must be set'",
")",
"pm",
"=",
"HTTPPasswordMgr",
"(",
")",
"_",
",",
"netloc",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
"=",
"urlparse",
"(",
"self",
".",
"url",
")",
"pm",
".",
"add_password",
"(",
"self",
".",
"realm",
",",
"netloc",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"self",
".",
"password_handler",
"=",
"HTTPBasicAuthHandler",
"(",
"pm",
")"
] | Check that ``username`` and ``password`` have been set, and raise an
exception if not. | [
"Check",
"that",
"username",
"and",
"password",
"have",
"been",
"set",
"and",
"raise",
"an",
"exception",
"if",
"not",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L102-L112 |
24,970 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.register | def register(self, metadata):
"""
Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The HTTP response received from PyPI upon submission of the
request.
"""
self.check_credentials()
metadata.validate()
d = metadata.todict()
d[':action'] = 'verify'
request = self.encode_request(d.items(), [])
response = self.send_request(request)
d[':action'] = 'submit'
request = self.encode_request(d.items(), [])
return self.send_request(request) | python | def register(self, metadata):
"""
Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The HTTP response received from PyPI upon submission of the
request.
"""
self.check_credentials()
metadata.validate()
d = metadata.todict()
d[':action'] = 'verify'
request = self.encode_request(d.items(), [])
response = self.send_request(request)
d[':action'] = 'submit'
request = self.encode_request(d.items(), [])
return self.send_request(request) | [
"def",
"register",
"(",
"self",
",",
"metadata",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"metadata",
".",
"validate",
"(",
")",
"d",
"=",
"metadata",
".",
"todict",
"(",
")",
"d",
"[",
"':action'",
"]",
"=",
"'verify'",
"request",
"=",
"self",
".",
"encode_request",
"(",
"d",
".",
"items",
"(",
")",
",",
"[",
"]",
")",
"response",
"=",
"self",
".",
"send_request",
"(",
"request",
")",
"d",
"[",
"':action'",
"]",
"=",
"'submit'",
"request",
"=",
"self",
".",
"encode_request",
"(",
"d",
".",
"items",
"(",
")",
",",
"[",
"]",
")",
"return",
"self",
".",
"send_request",
"(",
"request",
")"
] | Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The HTTP response received from PyPI upon submission of the
request. | [
"Register",
"a",
"distribution",
"on",
"PyPI",
"using",
"the",
"provided",
"metadata",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L114-L132 |
24,971 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex._reader | def _reader(self, name, stream, outbuf):
"""
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to the output stream of a subprocess.
:param outbuf: The list to append the read lines to.
"""
while True:
s = stream.readline()
if not s:
break
s = s.decode('utf-8').rstrip()
outbuf.append(s)
logger.debug('%s: %s' % (name, s))
stream.close() | python | def _reader(self, name, stream, outbuf):
"""
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to the output stream of a subprocess.
:param outbuf: The list to append the read lines to.
"""
while True:
s = stream.readline()
if not s:
break
s = s.decode('utf-8').rstrip()
outbuf.append(s)
logger.debug('%s: %s' % (name, s))
stream.close() | [
"def",
"_reader",
"(",
"self",
",",
"name",
",",
"stream",
",",
"outbuf",
")",
":",
"while",
"True",
":",
"s",
"=",
"stream",
".",
"readline",
"(",
")",
"if",
"not",
"s",
":",
"break",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
")",
"outbuf",
".",
"append",
"(",
"s",
")",
"logger",
".",
"debug",
"(",
"'%s: %s'",
"%",
"(",
"name",
",",
"s",
")",
")",
"stream",
".",
"close",
"(",
")"
] | Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to the output stream of a subprocess.
:param outbuf: The list to append the read lines to. | [
"Thread",
"runner",
"for",
"reading",
"lines",
"of",
"from",
"a",
"subprocess",
"into",
"a",
"buffer",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L134-L150 |
24,972 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.get_sign_command | def get_sign_command(self, filename, signer, sign_password,
keystore=None):
"""
Return a suitable command for signing a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The signing command as a list suitable to be
passed to :class:`subprocess.Popen`.
"""
cmd = [self.gpg, '--status-fd', '2', '--no-tty']
if keystore is None:
keystore = self.gpg_home
if keystore:
cmd.extend(['--homedir', keystore])
if sign_password is not None:
cmd.extend(['--batch', '--passphrase-fd', '0'])
td = tempfile.mkdtemp()
sf = os.path.join(td, os.path.basename(filename) + '.asc')
cmd.extend(['--detach-sign', '--armor', '--local-user',
signer, '--output', sf, filename])
logger.debug('invoking: %s', ' '.join(cmd))
return cmd, sf | python | def get_sign_command(self, filename, signer, sign_password,
keystore=None):
"""
Return a suitable command for signing a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The signing command as a list suitable to be
passed to :class:`subprocess.Popen`.
"""
cmd = [self.gpg, '--status-fd', '2', '--no-tty']
if keystore is None:
keystore = self.gpg_home
if keystore:
cmd.extend(['--homedir', keystore])
if sign_password is not None:
cmd.extend(['--batch', '--passphrase-fd', '0'])
td = tempfile.mkdtemp()
sf = os.path.join(td, os.path.basename(filename) + '.asc')
cmd.extend(['--detach-sign', '--armor', '--local-user',
signer, '--output', sf, filename])
logger.debug('invoking: %s', ' '.join(cmd))
return cmd, sf | [
"def",
"get_sign_command",
"(",
"self",
",",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"gpg",
",",
"'--status-fd'",
",",
"'2'",
",",
"'--no-tty'",
"]",
"if",
"keystore",
"is",
"None",
":",
"keystore",
"=",
"self",
".",
"gpg_home",
"if",
"keystore",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--homedir'",
",",
"keystore",
"]",
")",
"if",
"sign_password",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--batch'",
",",
"'--passphrase-fd'",
",",
"'0'",
"]",
")",
"td",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"sf",
"=",
"os",
".",
"path",
".",
"join",
"(",
"td",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"+",
"'.asc'",
")",
"cmd",
".",
"extend",
"(",
"[",
"'--detach-sign'",
",",
"'--armor'",
",",
"'--local-user'",
",",
"signer",
",",
"'--output'",
",",
"sf",
",",
"filename",
"]",
")",
"logger",
".",
"debug",
"(",
"'invoking: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"return",
"cmd",
",",
"sf"
] | Return a suitable command for signing a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The signing command as a list suitable to be
passed to :class:`subprocess.Popen`. | [
"Return",
"a",
"suitable",
"command",
"for",
"signing",
"a",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L152-L179 |
24,973 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.run_command | def run_command(self, cmd, input_data=None):
"""
Run a command in a child process , passing it any input data specified.
:param cmd: The command to run.
:param input_data: If specified, this must be a byte string containing
data to be sent to the child process.
:return: A tuple consisting of the subprocess' exit code, a list of
lines read from the subprocess' ``stdout``, and a list of
lines read from the subprocess' ``stderr``.
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
}
if input_data is not None:
kwargs['stdin'] = subprocess.PIPE
stdout = []
stderr = []
p = subprocess.Popen(cmd, **kwargs)
# We don't use communicate() here because we may need to
# get clever with interacting with the command
t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))
t1.start()
t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))
t2.start()
if input_data is not None:
p.stdin.write(input_data)
p.stdin.close()
p.wait()
t1.join()
t2.join()
return p.returncode, stdout, stderr | python | def run_command(self, cmd, input_data=None):
"""
Run a command in a child process , passing it any input data specified.
:param cmd: The command to run.
:param input_data: If specified, this must be a byte string containing
data to be sent to the child process.
:return: A tuple consisting of the subprocess' exit code, a list of
lines read from the subprocess' ``stdout``, and a list of
lines read from the subprocess' ``stderr``.
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
}
if input_data is not None:
kwargs['stdin'] = subprocess.PIPE
stdout = []
stderr = []
p = subprocess.Popen(cmd, **kwargs)
# We don't use communicate() here because we may need to
# get clever with interacting with the command
t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))
t1.start()
t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))
t2.start()
if input_data is not None:
p.stdin.write(input_data)
p.stdin.close()
p.wait()
t1.join()
t2.join()
return p.returncode, stdout, stderr | [
"def",
"run_command",
"(",
"self",
",",
"cmd",
",",
"input_data",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"PIPE",
",",
"}",
"if",
"input_data",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'stdin'",
"]",
"=",
"subprocess",
".",
"PIPE",
"stdout",
"=",
"[",
"]",
"stderr",
"=",
"[",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
"# We don't use communicate() here because we may need to",
"# get clever with interacting with the command",
"t1",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_reader",
",",
"args",
"=",
"(",
"'stdout'",
",",
"p",
".",
"stdout",
",",
"stdout",
")",
")",
"t1",
".",
"start",
"(",
")",
"t2",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_reader",
",",
"args",
"=",
"(",
"'stderr'",
",",
"p",
".",
"stderr",
",",
"stderr",
")",
")",
"t2",
".",
"start",
"(",
")",
"if",
"input_data",
"is",
"not",
"None",
":",
"p",
".",
"stdin",
".",
"write",
"(",
"input_data",
")",
"p",
".",
"stdin",
".",
"close",
"(",
")",
"p",
".",
"wait",
"(",
")",
"t1",
".",
"join",
"(",
")",
"t2",
".",
"join",
"(",
")",
"return",
"p",
".",
"returncode",
",",
"stdout",
",",
"stderr"
] | Run a command in a child process , passing it any input data specified.
:param cmd: The command to run.
:param input_data: If specified, this must be a byte string containing
data to be sent to the child process.
:return: A tuple consisting of the subprocess' exit code, a list of
lines read from the subprocess' ``stdout``, and a list of
lines read from the subprocess' ``stderr``. | [
"Run",
"a",
"command",
"in",
"a",
"child",
"process",
"passing",
"it",
"any",
"input",
"data",
"specified",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L181-L214 |
24,974 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.sign_file | def sign_file(self, filename, signer, sign_password, keystore=None):
"""
Sign a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in signing. If not specified, the instance's
``gpg_home`` attribute is used instead.
:return: The absolute pathname of the file where the signature is
stored.
"""
cmd, sig_file = self.get_sign_command(filename, signer, sign_password,
keystore)
rc, stdout, stderr = self.run_command(cmd,
sign_password.encode('utf-8'))
if rc != 0:
raise DistlibException('sign command failed with error '
'code %s' % rc)
return sig_file | python | def sign_file(self, filename, signer, sign_password, keystore=None):
"""
Sign a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in signing. If not specified, the instance's
``gpg_home`` attribute is used instead.
:return: The absolute pathname of the file where the signature is
stored.
"""
cmd, sig_file = self.get_sign_command(filename, signer, sign_password,
keystore)
rc, stdout, stderr = self.run_command(cmd,
sign_password.encode('utf-8'))
if rc != 0:
raise DistlibException('sign command failed with error '
'code %s' % rc)
return sig_file | [
"def",
"sign_file",
"(",
"self",
",",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
",",
"sig_file",
"=",
"self",
".",
"get_sign_command",
"(",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystore",
")",
"rc",
",",
"stdout",
",",
"stderr",
"=",
"self",
".",
"run_command",
"(",
"cmd",
",",
"sign_password",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"rc",
"!=",
"0",
":",
"raise",
"DistlibException",
"(",
"'sign command failed with error '",
"'code %s'",
"%",
"rc",
")",
"return",
"sig_file"
] | Sign a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directory which contains the keys
used in signing. If not specified, the instance's
``gpg_home`` attribute is used instead.
:return: The absolute pathname of the file where the signature is
stored. | [
"Sign",
"a",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L216-L237 |
24,975 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.upload_documentation | def upload_documentation(self, metadata, doc_dir):
"""
Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
documentation. This should be the directory that
contains the ``index.html`` for the documentation.
:return: The HTTP response received from PyPI upon submission of the
request.
"""
self.check_credentials()
if not os.path.isdir(doc_dir):
raise DistlibException('not a directory: %r' % doc_dir)
fn = os.path.join(doc_dir, 'index.html')
if not os.path.exists(fn):
raise DistlibException('not found: %r' % fn)
metadata.validate()
name, version = metadata.name, metadata.version
zip_data = zip_dir(doc_dir).getvalue()
fields = [(':action', 'doc_upload'),
('name', name), ('version', version)]
files = [('content', name, zip_data)]
request = self.encode_request(fields, files)
return self.send_request(request) | python | def upload_documentation(self, metadata, doc_dir):
"""
Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
documentation. This should be the directory that
contains the ``index.html`` for the documentation.
:return: The HTTP response received from PyPI upon submission of the
request.
"""
self.check_credentials()
if not os.path.isdir(doc_dir):
raise DistlibException('not a directory: %r' % doc_dir)
fn = os.path.join(doc_dir, 'index.html')
if not os.path.exists(fn):
raise DistlibException('not found: %r' % fn)
metadata.validate()
name, version = metadata.name, metadata.version
zip_data = zip_dir(doc_dir).getvalue()
fields = [(':action', 'doc_upload'),
('name', name), ('version', version)]
files = [('content', name, zip_data)]
request = self.encode_request(fields, files)
return self.send_request(request) | [
"def",
"upload_documentation",
"(",
"self",
",",
"metadata",
",",
"doc_dir",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"doc_dir",
")",
":",
"raise",
"DistlibException",
"(",
"'not a directory: %r'",
"%",
"doc_dir",
")",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"doc_dir",
",",
"'index.html'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"raise",
"DistlibException",
"(",
"'not found: %r'",
"%",
"fn",
")",
"metadata",
".",
"validate",
"(",
")",
"name",
",",
"version",
"=",
"metadata",
".",
"name",
",",
"metadata",
".",
"version",
"zip_data",
"=",
"zip_dir",
"(",
"doc_dir",
")",
".",
"getvalue",
"(",
")",
"fields",
"=",
"[",
"(",
"':action'",
",",
"'doc_upload'",
")",
",",
"(",
"'name'",
",",
"name",
")",
",",
"(",
"'version'",
",",
"version",
")",
"]",
"files",
"=",
"[",
"(",
"'content'",
",",
"name",
",",
"zip_data",
")",
"]",
"request",
"=",
"self",
".",
"encode_request",
"(",
"fields",
",",
"files",
")",
"return",
"self",
".",
"send_request",
"(",
"request",
")"
] | Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
documentation. This should be the directory that
contains the ``index.html`` for the documentation.
:return: The HTTP response received from PyPI upon submission of the
request. | [
"Upload",
"documentation",
"to",
"the",
"index",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L296-L322 |
24,976 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.get_verify_command | def get_verify_command(self, signature_filename, data_filename,
keystore=None):
"""
Return a suitable command for verifying a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The verifying command as a list suitable to be
passed to :class:`subprocess.Popen`.
"""
cmd = [self.gpg, '--status-fd', '2', '--no-tty']
if keystore is None:
keystore = self.gpg_home
if keystore:
cmd.extend(['--homedir', keystore])
cmd.extend(['--verify', signature_filename, data_filename])
logger.debug('invoking: %s', ' '.join(cmd))
return cmd | python | def get_verify_command(self, signature_filename, data_filename,
keystore=None):
"""
Return a suitable command for verifying a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The verifying command as a list suitable to be
passed to :class:`subprocess.Popen`.
"""
cmd = [self.gpg, '--status-fd', '2', '--no-tty']
if keystore is None:
keystore = self.gpg_home
if keystore:
cmd.extend(['--homedir', keystore])
cmd.extend(['--verify', signature_filename, data_filename])
logger.debug('invoking: %s', ' '.join(cmd))
return cmd | [
"def",
"get_verify_command",
"(",
"self",
",",
"signature_filename",
",",
"data_filename",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"gpg",
",",
"'--status-fd'",
",",
"'2'",
",",
"'--no-tty'",
"]",
"if",
"keystore",
"is",
"None",
":",
"keystore",
"=",
"self",
".",
"gpg_home",
"if",
"keystore",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--homedir'",
",",
"keystore",
"]",
")",
"cmd",
".",
"extend",
"(",
"[",
"'--verify'",
",",
"signature_filename",
",",
"data_filename",
"]",
")",
"logger",
".",
"debug",
"(",
"'invoking: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"return",
"cmd"
] | Return a suitable command for verifying a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: The verifying command as a list suitable to be
passed to :class:`subprocess.Popen`. | [
"Return",
"a",
"suitable",
"command",
"for",
"verifying",
"a",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L324-L346 |
24,977 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.verify_signature | def verify_signature(self, signature_filename, data_filename,
keystore=None):
"""
Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: True if the signature was verified, else False.
"""
if not self.gpg:
raise DistlibException('verification unavailable because gpg '
'unavailable')
cmd = self.get_verify_command(signature_filename, data_filename,
keystore)
rc, stdout, stderr = self.run_command(cmd)
if rc not in (0, 1):
raise DistlibException('verify command failed with error '
'code %s' % rc)
return rc == 0 | python | def verify_signature(self, signature_filename, data_filename,
keystore=None):
"""
Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: True if the signature was verified, else False.
"""
if not self.gpg:
raise DistlibException('verification unavailable because gpg '
'unavailable')
cmd = self.get_verify_command(signature_filename, data_filename,
keystore)
rc, stdout, stderr = self.run_command(cmd)
if rc not in (0, 1):
raise DistlibException('verify command failed with error '
'code %s' % rc)
return rc == 0 | [
"def",
"verify_signature",
"(",
"self",
",",
"signature_filename",
",",
"data_filename",
",",
"keystore",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"gpg",
":",
"raise",
"DistlibException",
"(",
"'verification unavailable because gpg '",
"'unavailable'",
")",
"cmd",
"=",
"self",
".",
"get_verify_command",
"(",
"signature_filename",
",",
"data_filename",
",",
"keystore",
")",
"rc",
",",
"stdout",
",",
"stderr",
"=",
"self",
".",
"run_command",
"(",
"cmd",
")",
"if",
"rc",
"not",
"in",
"(",
"0",
",",
"1",
")",
":",
"raise",
"DistlibException",
"(",
"'verify command failed with error '",
"'code %s'",
"%",
"rc",
")",
"return",
"rc",
"==",
"0"
] | Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which contains the keys
used in verification. If not specified, the
instance's ``gpg_home`` attribute is used instead.
:return: True if the signature was verified, else False. | [
"Verify",
"a",
"signature",
"for",
"a",
"file",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L348-L371 |
24,978 | pypa/pipenv | pipenv/vendor/distlib/index.py | PackageIndex.encode_request | def encode_request(self, fields, files):
"""
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
file_bytes) tuple.
"""
# Adapted from packaging, which in turn was adapted from
# http://code.activestate.com/recipes/146306
parts = []
boundary = self.boundary
for k, values in fields:
if not isinstance(values, (list, tuple)):
values = [values]
for v in values:
parts.extend((
b'--' + boundary,
('Content-Disposition: form-data; name="%s"' %
k).encode('utf-8'),
b'',
v.encode('utf-8')))
for key, filename, value in files:
parts.extend((
b'--' + boundary,
('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, filename)).encode('utf-8'),
b'',
value))
parts.extend((b'--' + boundary + b'--', b''))
body = b'\r\n'.join(parts)
ct = b'multipart/form-data; boundary=' + boundary
headers = {
'Content-type': ct,
'Content-length': str(len(body))
}
return Request(self.url, body, headers) | python | def encode_request(self, fields, files):
"""
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
file_bytes) tuple.
"""
# Adapted from packaging, which in turn was adapted from
# http://code.activestate.com/recipes/146306
parts = []
boundary = self.boundary
for k, values in fields:
if not isinstance(values, (list, tuple)):
values = [values]
for v in values:
parts.extend((
b'--' + boundary,
('Content-Disposition: form-data; name="%s"' %
k).encode('utf-8'),
b'',
v.encode('utf-8')))
for key, filename, value in files:
parts.extend((
b'--' + boundary,
('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, filename)).encode('utf-8'),
b'',
value))
parts.extend((b'--' + boundary + b'--', b''))
body = b'\r\n'.join(parts)
ct = b'multipart/form-data; boundary=' + boundary
headers = {
'Content-type': ct,
'Content-length': str(len(body))
}
return Request(self.url, body, headers) | [
"def",
"encode_request",
"(",
"self",
",",
"fields",
",",
"files",
")",
":",
"# Adapted from packaging, which in turn was adapted from",
"# http://code.activestate.com/recipes/146306",
"parts",
"=",
"[",
"]",
"boundary",
"=",
"self",
".",
"boundary",
"for",
"k",
",",
"values",
"in",
"fields",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"values",
"=",
"[",
"values",
"]",
"for",
"v",
"in",
"values",
":",
"parts",
".",
"extend",
"(",
"(",
"b'--'",
"+",
"boundary",
",",
"(",
"'Content-Disposition: form-data; name=\"%s\"'",
"%",
"k",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"b''",
",",
"v",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
"for",
"key",
",",
"filename",
",",
"value",
"in",
"files",
":",
"parts",
".",
"extend",
"(",
"(",
"b'--'",
"+",
"boundary",
",",
"(",
"'Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"'",
"%",
"(",
"key",
",",
"filename",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"b''",
",",
"value",
")",
")",
"parts",
".",
"extend",
"(",
"(",
"b'--'",
"+",
"boundary",
"+",
"b'--'",
",",
"b''",
")",
")",
"body",
"=",
"b'\\r\\n'",
".",
"join",
"(",
"parts",
")",
"ct",
"=",
"b'multipart/form-data; boundary='",
"+",
"boundary",
"headers",
"=",
"{",
"'Content-type'",
":",
"ct",
",",
"'Content-length'",
":",
"str",
"(",
"len",
"(",
"body",
")",
")",
"}",
"return",
"Request",
"(",
"self",
".",
"url",
",",
"body",
",",
"headers",
")"
] | Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
file_bytes) tuple. | [
"Encode",
"fields",
"and",
"files",
"for",
"posting",
"to",
"an",
"HTTP",
"server",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/index.py#L466-L507 |
24,979 | pypa/pipenv | pipenv/vendor/click_completion/core.py | do_bash_complete | def do_bash_complete(cli, prog_name):
"""Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
comp_words = os.environ['COMP_WORDS']
try:
cwords = shlex.split(comp_words)
quoted = False
except ValueError: # No closing quotation
cwords = split_args(comp_words)
quoted = True
cword = int(os.environ['COMP_CWORD'])
args = cwords[1:cword]
try:
incomplete = cwords[cword]
except IndexError:
incomplete = ''
choices = get_choices(cli, prog_name, args, incomplete)
if quoted:
echo('\t'.join(opt for opt, _ in choices), nl=False)
else:
echo('\t'.join(re.sub(r"""([\s\\"'()])""", r'\\\1', opt) for opt, _ in choices), nl=False)
return True | python | def do_bash_complete(cli, prog_name):
"""Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
comp_words = os.environ['COMP_WORDS']
try:
cwords = shlex.split(comp_words)
quoted = False
except ValueError: # No closing quotation
cwords = split_args(comp_words)
quoted = True
cword = int(os.environ['COMP_CWORD'])
args = cwords[1:cword]
try:
incomplete = cwords[cword]
except IndexError:
incomplete = ''
choices = get_choices(cli, prog_name, args, incomplete)
if quoted:
echo('\t'.join(opt for opt, _ in choices), nl=False)
else:
echo('\t'.join(re.sub(r"""([\s\\"'()])""", r'\\\1', opt) for opt, _ in choices), nl=False)
return True | [
"def",
"do_bash_complete",
"(",
"cli",
",",
"prog_name",
")",
":",
"comp_words",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
"try",
":",
"cwords",
"=",
"shlex",
".",
"split",
"(",
"comp_words",
")",
"quoted",
"=",
"False",
"except",
"ValueError",
":",
"# No closing quotation",
"cwords",
"=",
"split_args",
"(",
"comp_words",
")",
"quoted",
"=",
"True",
"cword",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'COMP_CWORD'",
"]",
")",
"args",
"=",
"cwords",
"[",
"1",
":",
"cword",
"]",
"try",
":",
"incomplete",
"=",
"cwords",
"[",
"cword",
"]",
"except",
"IndexError",
":",
"incomplete",
"=",
"''",
"choices",
"=",
"get_choices",
"(",
"cli",
",",
"prog_name",
",",
"args",
",",
"incomplete",
")",
"if",
"quoted",
":",
"echo",
"(",
"'\\t'",
".",
"join",
"(",
"opt",
"for",
"opt",
",",
"_",
"in",
"choices",
")",
",",
"nl",
"=",
"False",
")",
"else",
":",
"echo",
"(",
"'\\t'",
".",
"join",
"(",
"re",
".",
"sub",
"(",
"r\"\"\"([\\s\\\\\"'()])\"\"\"",
",",
"r'\\\\\\1'",
",",
"opt",
")",
"for",
"opt",
",",
"_",
"in",
"choices",
")",
",",
"nl",
"=",
"False",
")",
"return",
"True"
] | Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise | [
"Do",
"the",
"completion",
"for",
"bash"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/core.py#L141-L176 |
24,980 | pypa/pipenv | pipenv/vendor/click_completion/core.py | do_fish_complete | def do_fish_complete(cli, prog_name):
"""Do the fish completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
else:
incomplete = ''
for item, help in get_choices(cli, prog_name, args, incomplete):
if help:
echo("%s\t%s" % (item, re.sub('\s', ' ', help)))
else:
echo(item)
return True | python | def do_fish_complete(cli, prog_name):
"""Do the fish completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
else:
incomplete = ''
for item, help in get_choices(cli, prog_name, args, incomplete):
if help:
echo("%s\t%s" % (item, re.sub('\s', ' ', help)))
else:
echo(item)
return True | [
"def",
"do_fish_complete",
"(",
"cli",
",",
"prog_name",
")",
":",
"commandline",
"=",
"os",
".",
"environ",
"[",
"'COMMANDLINE'",
"]",
"args",
"=",
"split_args",
"(",
"commandline",
")",
"[",
"1",
":",
"]",
"if",
"args",
"and",
"not",
"commandline",
".",
"endswith",
"(",
"' '",
")",
":",
"incomplete",
"=",
"args",
"[",
"-",
"1",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"else",
":",
"incomplete",
"=",
"''",
"for",
"item",
",",
"help",
"in",
"get_choices",
"(",
"cli",
",",
"prog_name",
",",
"args",
",",
"incomplete",
")",
":",
"if",
"help",
":",
"echo",
"(",
"\"%s\\t%s\"",
"%",
"(",
"item",
",",
"re",
".",
"sub",
"(",
"'\\s'",
",",
"' '",
",",
"help",
")",
")",
")",
"else",
":",
"echo",
"(",
"item",
")",
"return",
"True"
] | Do the fish completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise | [
"Do",
"the",
"fish",
"completion"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/core.py#L179-L208 |
24,981 | pypa/pipenv | pipenv/vendor/click_completion/core.py | do_powershell_complete | def do_powershell_complete(cli, prog_name):
"""Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
quote = single_quote
incomplete = ''
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
quote_pos = commandline.rfind(incomplete) - 1
if quote_pos >= 0 and commandline[quote_pos] == '"':
quote = double_quote
for item, help in get_choices(cli, prog_name, args, incomplete):
echo(quote(item))
return True | python | def do_powershell_complete(cli, prog_name):
"""Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise
"""
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
quote = single_quote
incomplete = ''
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
quote_pos = commandline.rfind(incomplete) - 1
if quote_pos >= 0 and commandline[quote_pos] == '"':
quote = double_quote
for item, help in get_choices(cli, prog_name, args, incomplete):
echo(quote(item))
return True | [
"def",
"do_powershell_complete",
"(",
"cli",
",",
"prog_name",
")",
":",
"commandline",
"=",
"os",
".",
"environ",
"[",
"'COMMANDLINE'",
"]",
"args",
"=",
"split_args",
"(",
"commandline",
")",
"[",
"1",
":",
"]",
"quote",
"=",
"single_quote",
"incomplete",
"=",
"''",
"if",
"args",
"and",
"not",
"commandline",
".",
"endswith",
"(",
"' '",
")",
":",
"incomplete",
"=",
"args",
"[",
"-",
"1",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"quote_pos",
"=",
"commandline",
".",
"rfind",
"(",
"incomplete",
")",
"-",
"1",
"if",
"quote_pos",
">=",
"0",
"and",
"commandline",
"[",
"quote_pos",
"]",
"==",
"'\"'",
":",
"quote",
"=",
"double_quote",
"for",
"item",
",",
"help",
"in",
"get_choices",
"(",
"cli",
",",
"prog_name",
",",
"args",
",",
"incomplete",
")",
":",
"echo",
"(",
"quote",
"(",
"item",
")",
")",
"return",
"True"
] | Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise | [
"Do",
"the",
"powershell",
"completion"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/core.py#L250-L279 |
24,982 | pypa/pipenv | pipenv/vendor/click_completion/core.py | get_code | def get_code(shell=None, prog_name=None, env_name=None, extra_env=None):
"""Returns the completion code to be evaluated by the shell
Parameters
----------
shell : Shell
The shell type (Default value = None)
prog_name : str
The program name on the command line (Default value = None)
env_name : str
The environment variable used to control the completion (Default value = None)
extra_env : dict
Some extra environment variables to be added to the generated code (Default value = None)
Returns
-------
str
The code to be evaluated by the shell
"""
from jinja2 import Environment, FileSystemLoader
if shell in [None, 'auto']:
shell = get_auto_shell()
if not isinstance(shell, Shell):
shell = Shell[shell]
prog_name = prog_name or click.get_current_context().find_root().info_name
env_name = env_name or '_%s_COMPLETE' % prog_name.upper().replace('-', '_')
extra_env = extra_env if extra_env else {}
env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)))
template = env.get_template('%s.j2' % shell.name)
return template.render(prog_name=prog_name, complete_var=env_name, extra_env=extra_env) | python | def get_code(shell=None, prog_name=None, env_name=None, extra_env=None):
"""Returns the completion code to be evaluated by the shell
Parameters
----------
shell : Shell
The shell type (Default value = None)
prog_name : str
The program name on the command line (Default value = None)
env_name : str
The environment variable used to control the completion (Default value = None)
extra_env : dict
Some extra environment variables to be added to the generated code (Default value = None)
Returns
-------
str
The code to be evaluated by the shell
"""
from jinja2 import Environment, FileSystemLoader
if shell in [None, 'auto']:
shell = get_auto_shell()
if not isinstance(shell, Shell):
shell = Shell[shell]
prog_name = prog_name or click.get_current_context().find_root().info_name
env_name = env_name or '_%s_COMPLETE' % prog_name.upper().replace('-', '_')
extra_env = extra_env if extra_env else {}
env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)))
template = env.get_template('%s.j2' % shell.name)
return template.render(prog_name=prog_name, complete_var=env_name, extra_env=extra_env) | [
"def",
"get_code",
"(",
"shell",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"env_name",
"=",
"None",
",",
"extra_env",
"=",
"None",
")",
":",
"from",
"jinja2",
"import",
"Environment",
",",
"FileSystemLoader",
"if",
"shell",
"in",
"[",
"None",
",",
"'auto'",
"]",
":",
"shell",
"=",
"get_auto_shell",
"(",
")",
"if",
"not",
"isinstance",
"(",
"shell",
",",
"Shell",
")",
":",
"shell",
"=",
"Shell",
"[",
"shell",
"]",
"prog_name",
"=",
"prog_name",
"or",
"click",
".",
"get_current_context",
"(",
")",
".",
"find_root",
"(",
")",
".",
"info_name",
"env_name",
"=",
"env_name",
"or",
"'_%s_COMPLETE'",
"%",
"prog_name",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"extra_env",
"=",
"extra_env",
"if",
"extra_env",
"else",
"{",
"}",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"template",
"=",
"env",
".",
"get_template",
"(",
"'%s.j2'",
"%",
"shell",
".",
"name",
")",
"return",
"template",
".",
"render",
"(",
"prog_name",
"=",
"prog_name",
",",
"complete_var",
"=",
"env_name",
",",
"extra_env",
"=",
"extra_env",
")"
] | Returns the completion code to be evaluated by the shell
Parameters
----------
shell : Shell
The shell type (Default value = None)
prog_name : str
The program name on the command line (Default value = None)
env_name : str
The environment variable used to control the completion (Default value = None)
extra_env : dict
Some extra environment variables to be added to the generated code (Default value = None)
Returns
-------
str
The code to be evaluated by the shell | [
"Returns",
"the",
"completion",
"code",
"to",
"be",
"evaluated",
"by",
"the",
"shell"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/core.py#L282-L311 |
24,983 | pypa/pipenv | pipenv/vendor/click_completion/core.py | install | def install(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None):
"""Install the completion
Parameters
----------
shell : Shell
The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None)
prog_name : str
The program name on the command line. It will be automatically computed if the value is None
(Default value = None)
env_name : str
The environment variable name used to control the completion. It will be automatically computed if the value is
None (Default value = None)
path : str
The installation path of the code to be evaluated by the shell. The standard installation path is used if the
value is None (Default value = None)
append : bool
Whether to append the content to the file or to override it. The default behavior depends on the shell type
(Default value = None)
extra_env : dict
A set of environment variables and their values to be added to the generated code (Default value = None)
"""
prog_name = prog_name or click.get_current_context().find_root().info_name
shell = shell or get_auto_shell()
if append is None and path is not None:
append = True
if append is not None:
mode = 'a' if append else 'w'
else:
mode = None
if shell == 'fish':
path = path or os.path.expanduser('~') + '/.config/fish/completions/%s.fish' % prog_name
mode = mode or 'w'
elif shell == 'bash':
path = path or os.path.expanduser('~') + '/.bash_completion'
mode = mode or 'a'
elif shell == 'zsh':
ohmyzsh = os.path.expanduser('~') + '/.oh-my-zsh'
if os.path.exists(ohmyzsh):
path = path or ohmyzsh + '/completions/_%s' % prog_name
mode = mode or 'w'
else:
path = path or os.path.expanduser('~') + '/.zshrc'
mode = mode or 'a'
elif shell == 'powershell':
subprocess.check_call(['powershell', 'Set-ExecutionPolicy Unrestricted -Scope CurrentUser'])
path = path or subprocess.check_output(['powershell', '-NoProfile', 'echo $profile']).strip() if install else ''
mode = mode or 'a'
else:
raise click.ClickException('%s is not supported.' % shell)
if append is not None:
mode = 'a' if append else 'w'
else:
mode = mode
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
f = open(path, mode)
f.write(get_code(shell, prog_name, env_name, extra_env))
f.write("\n")
f.close()
return shell, path | python | def install(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None):
"""Install the completion
Parameters
----------
shell : Shell
The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None)
prog_name : str
The program name on the command line. It will be automatically computed if the value is None
(Default value = None)
env_name : str
The environment variable name used to control the completion. It will be automatically computed if the value is
None (Default value = None)
path : str
The installation path of the code to be evaluated by the shell. The standard installation path is used if the
value is None (Default value = None)
append : bool
Whether to append the content to the file or to override it. The default behavior depends on the shell type
(Default value = None)
extra_env : dict
A set of environment variables and their values to be added to the generated code (Default value = None)
"""
prog_name = prog_name or click.get_current_context().find_root().info_name
shell = shell or get_auto_shell()
if append is None and path is not None:
append = True
if append is not None:
mode = 'a' if append else 'w'
else:
mode = None
if shell == 'fish':
path = path or os.path.expanduser('~') + '/.config/fish/completions/%s.fish' % prog_name
mode = mode or 'w'
elif shell == 'bash':
path = path or os.path.expanduser('~') + '/.bash_completion'
mode = mode or 'a'
elif shell == 'zsh':
ohmyzsh = os.path.expanduser('~') + '/.oh-my-zsh'
if os.path.exists(ohmyzsh):
path = path or ohmyzsh + '/completions/_%s' % prog_name
mode = mode or 'w'
else:
path = path or os.path.expanduser('~') + '/.zshrc'
mode = mode or 'a'
elif shell == 'powershell':
subprocess.check_call(['powershell', 'Set-ExecutionPolicy Unrestricted -Scope CurrentUser'])
path = path or subprocess.check_output(['powershell', '-NoProfile', 'echo $profile']).strip() if install else ''
mode = mode or 'a'
else:
raise click.ClickException('%s is not supported.' % shell)
if append is not None:
mode = 'a' if append else 'w'
else:
mode = mode
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
f = open(path, mode)
f.write(get_code(shell, prog_name, env_name, extra_env))
f.write("\n")
f.close()
return shell, path | [
"def",
"install",
"(",
"shell",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"env_name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"append",
"=",
"None",
",",
"extra_env",
"=",
"None",
")",
":",
"prog_name",
"=",
"prog_name",
"or",
"click",
".",
"get_current_context",
"(",
")",
".",
"find_root",
"(",
")",
".",
"info_name",
"shell",
"=",
"shell",
"or",
"get_auto_shell",
"(",
")",
"if",
"append",
"is",
"None",
"and",
"path",
"is",
"not",
"None",
":",
"append",
"=",
"True",
"if",
"append",
"is",
"not",
"None",
":",
"mode",
"=",
"'a'",
"if",
"append",
"else",
"'w'",
"else",
":",
"mode",
"=",
"None",
"if",
"shell",
"==",
"'fish'",
":",
"path",
"=",
"path",
"or",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"+",
"'/.config/fish/completions/%s.fish'",
"%",
"prog_name",
"mode",
"=",
"mode",
"or",
"'w'",
"elif",
"shell",
"==",
"'bash'",
":",
"path",
"=",
"path",
"or",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"+",
"'/.bash_completion'",
"mode",
"=",
"mode",
"or",
"'a'",
"elif",
"shell",
"==",
"'zsh'",
":",
"ohmyzsh",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"+",
"'/.oh-my-zsh'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ohmyzsh",
")",
":",
"path",
"=",
"path",
"or",
"ohmyzsh",
"+",
"'/completions/_%s'",
"%",
"prog_name",
"mode",
"=",
"mode",
"or",
"'w'",
"else",
":",
"path",
"=",
"path",
"or",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"+",
"'/.zshrc'",
"mode",
"=",
"mode",
"or",
"'a'",
"elif",
"shell",
"==",
"'powershell'",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'powershell'",
",",
"'Set-ExecutionPolicy Unrestricted -Scope CurrentUser'",
"]",
")",
"path",
"=",
"path",
"or",
"subprocess",
".",
"check_output",
"(",
"[",
"'powershell'",
",",
"'-NoProfile'",
",",
"'echo $profile'",
"]",
")",
".",
"strip",
"(",
")",
"if",
"install",
"else",
"''",
"mode",
"=",
"mode",
"or",
"'a'",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'%s is not supported.'",
"%",
"shell",
")",
"if",
"append",
"is",
"not",
"None",
":",
"mode",
"=",
"'a'",
"if",
"append",
"else",
"'w'",
"else",
":",
"mode",
"=",
"mode",
"d",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
":",
"os",
".",
"makedirs",
"(",
"d",
")",
"f",
"=",
"open",
"(",
"path",
",",
"mode",
")",
"f",
".",
"write",
"(",
"get_code",
"(",
"shell",
",",
"prog_name",
",",
"env_name",
",",
"extra_env",
")",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")",
"f",
".",
"close",
"(",
")",
"return",
"shell",
",",
"path"
] | Install the completion
Parameters
----------
shell : Shell
The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None)
prog_name : str
The program name on the command line. It will be automatically computed if the value is None
(Default value = None)
env_name : str
The environment variable name used to control the completion. It will be automatically computed if the value is
None (Default value = None)
path : str
The installation path of the code to be evaluated by the shell. The standard installation path is used if the
value is None (Default value = None)
append : bool
Whether to append the content to the file or to override it. The default behavior depends on the shell type
(Default value = None)
extra_env : dict
A set of environment variables and their values to be added to the generated code (Default value = None) | [
"Install",
"the",
"completion"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/core.py#L314-L377 |
24,984 | pypa/pipenv | pipenv/vendor/urllib3/filepost.py | choose_boundary | def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_boundary.
"""
boundary = binascii.hexlify(os.urandom(16))
if six.PY3:
boundary = boundary.decode('ascii')
return boundary | python | def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_boundary.
"""
boundary = binascii.hexlify(os.urandom(16))
if six.PY3:
boundary = boundary.decode('ascii')
return boundary | [
"def",
"choose_boundary",
"(",
")",
":",
"boundary",
"=",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"16",
")",
")",
"if",
"six",
".",
"PY3",
":",
"boundary",
"=",
"boundary",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"boundary"
] | Our embarrassingly-simple replacement for mimetools.choose_boundary. | [
"Our",
"embarrassingly",
"-",
"simple",
"replacement",
"for",
"mimetools",
".",
"choose_boundary",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/filepost.py#L15-L22 |
24,985 | pypa/pipenv | pipenv/vendor/urllib3/filepost.py | iter_field_objects | def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field) | python | def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field) | [
"def",
"iter_field_objects",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"i",
"=",
"six",
".",
"iteritems",
"(",
"fields",
")",
"else",
":",
"i",
"=",
"iter",
"(",
"fields",
")",
"for",
"field",
"in",
"i",
":",
"if",
"isinstance",
"(",
"field",
",",
"RequestField",
")",
":",
"yield",
"field",
"else",
":",
"yield",
"RequestField",
".",
"from_tuples",
"(",
"*",
"field",
")"
] | Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`. | [
"Iterate",
"over",
"fields",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/filepost.py#L25-L42 |
24,986 | pypa/pipenv | pipenv/vendor/distlib/resources.py | finder_for_path | def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, '')
module.__loader__ = loader
result = finder(module)
return result | python | def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, '')
module.__loader__ = loader
result = finder(module)
return result | [
"def",
"finder_for_path",
"(",
"path",
")",
":",
"result",
"=",
"None",
"# calls any path hooks, gets importer into cache",
"pkgutil",
".",
"get_importer",
"(",
"path",
")",
"loader",
"=",
"sys",
".",
"path_importer_cache",
".",
"get",
"(",
"path",
")",
"finder",
"=",
"_finder_registry",
".",
"get",
"(",
"type",
"(",
"loader",
")",
")",
"if",
"finder",
":",
"module",
"=",
"_dummy_module",
"module",
".",
"__file__",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"''",
")",
"module",
".",
"__loader__",
"=",
"loader",
"result",
"=",
"finder",
"(",
"module",
")",
"return",
"result"
] | Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path. | [
"Return",
"a",
"resource",
"finder",
"for",
"a",
"path",
"which",
"should",
"represent",
"a",
"container",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/resources.py#L338-L355 |
24,987 | pypa/pipenv | pipenv/vendor/distlib/resources.py | ResourceCache.get | def get(self, resource):
"""
Get a resource into the cache,
:param resource: A :class:`Resource` instance.
:return: The pathname of the resource in the cache.
"""
prefix, path = resource.finder.get_cache_info(resource)
if prefix is None:
result = path
else:
result = os.path.join(self.base, self.prefix_to_dir(prefix), path)
dirname = os.path.dirname(result)
if not os.path.isdir(dirname):
os.makedirs(dirname)
if not os.path.exists(result):
stale = True
else:
stale = self.is_stale(resource, path)
if stale:
# write the bytes of the resource to the cache location
with open(result, 'wb') as f:
f.write(resource.bytes)
return result | python | def get(self, resource):
"""
Get a resource into the cache,
:param resource: A :class:`Resource` instance.
:return: The pathname of the resource in the cache.
"""
prefix, path = resource.finder.get_cache_info(resource)
if prefix is None:
result = path
else:
result = os.path.join(self.base, self.prefix_to_dir(prefix), path)
dirname = os.path.dirname(result)
if not os.path.isdir(dirname):
os.makedirs(dirname)
if not os.path.exists(result):
stale = True
else:
stale = self.is_stale(resource, path)
if stale:
# write the bytes of the resource to the cache location
with open(result, 'wb') as f:
f.write(resource.bytes)
return result | [
"def",
"get",
"(",
"self",
",",
"resource",
")",
":",
"prefix",
",",
"path",
"=",
"resource",
".",
"finder",
".",
"get_cache_info",
"(",
"resource",
")",
"if",
"prefix",
"is",
"None",
":",
"result",
"=",
"path",
"else",
":",
"result",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base",
",",
"self",
".",
"prefix_to_dir",
"(",
"prefix",
")",
",",
"path",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"result",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"result",
")",
":",
"stale",
"=",
"True",
"else",
":",
"stale",
"=",
"self",
".",
"is_stale",
"(",
"resource",
",",
"path",
")",
"if",
"stale",
":",
"# write the bytes of the resource to the cache location",
"with",
"open",
"(",
"result",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"resource",
".",
"bytes",
")",
"return",
"result"
] | Get a resource into the cache,
:param resource: A :class:`Resource` instance.
:return: The pathname of the resource in the cache. | [
"Get",
"a",
"resource",
"into",
"the",
"cache"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/resources.py#L46-L69 |
24,988 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/treeadapters/sax.py | to_sax | def to_sax(walker, handler):
"""Call SAX-like content handler based on treewalker walker
:arg walker: the treewalker to use to walk the tree to convert it
:arg handler: SAX handler to use
"""
handler.startDocument()
for prefix, namespace in prefix_mapping.items():
handler.startPrefixMapping(prefix, namespace)
for token in walker:
type = token["type"]
if type == "Doctype":
continue
elif type in ("StartTag", "EmptyTag"):
attrs = AttributesNSImpl(token["data"],
unadjustForeignAttributes)
handler.startElementNS((token["namespace"], token["name"]),
token["name"],
attrs)
if type == "EmptyTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type == "EndTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type in ("Characters", "SpaceCharacters"):
handler.characters(token["data"])
elif type == "Comment":
pass
else:
assert False, "Unknown token type"
for prefix, namespace in prefix_mapping.items():
handler.endPrefixMapping(prefix)
handler.endDocument() | python | def to_sax(walker, handler):
"""Call SAX-like content handler based on treewalker walker
:arg walker: the treewalker to use to walk the tree to convert it
:arg handler: SAX handler to use
"""
handler.startDocument()
for prefix, namespace in prefix_mapping.items():
handler.startPrefixMapping(prefix, namespace)
for token in walker:
type = token["type"]
if type == "Doctype":
continue
elif type in ("StartTag", "EmptyTag"):
attrs = AttributesNSImpl(token["data"],
unadjustForeignAttributes)
handler.startElementNS((token["namespace"], token["name"]),
token["name"],
attrs)
if type == "EmptyTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type == "EndTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type in ("Characters", "SpaceCharacters"):
handler.characters(token["data"])
elif type == "Comment":
pass
else:
assert False, "Unknown token type"
for prefix, namespace in prefix_mapping.items():
handler.endPrefixMapping(prefix)
handler.endDocument() | [
"def",
"to_sax",
"(",
"walker",
",",
"handler",
")",
":",
"handler",
".",
"startDocument",
"(",
")",
"for",
"prefix",
",",
"namespace",
"in",
"prefix_mapping",
".",
"items",
"(",
")",
":",
"handler",
".",
"startPrefixMapping",
"(",
"prefix",
",",
"namespace",
")",
"for",
"token",
"in",
"walker",
":",
"type",
"=",
"token",
"[",
"\"type\"",
"]",
"if",
"type",
"==",
"\"Doctype\"",
":",
"continue",
"elif",
"type",
"in",
"(",
"\"StartTag\"",
",",
"\"EmptyTag\"",
")",
":",
"attrs",
"=",
"AttributesNSImpl",
"(",
"token",
"[",
"\"data\"",
"]",
",",
"unadjustForeignAttributes",
")",
"handler",
".",
"startElementNS",
"(",
"(",
"token",
"[",
"\"namespace\"",
"]",
",",
"token",
"[",
"\"name\"",
"]",
")",
",",
"token",
"[",
"\"name\"",
"]",
",",
"attrs",
")",
"if",
"type",
"==",
"\"EmptyTag\"",
":",
"handler",
".",
"endElementNS",
"(",
"(",
"token",
"[",
"\"namespace\"",
"]",
",",
"token",
"[",
"\"name\"",
"]",
")",
",",
"token",
"[",
"\"name\"",
"]",
")",
"elif",
"type",
"==",
"\"EndTag\"",
":",
"handler",
".",
"endElementNS",
"(",
"(",
"token",
"[",
"\"namespace\"",
"]",
",",
"token",
"[",
"\"name\"",
"]",
")",
",",
"token",
"[",
"\"name\"",
"]",
")",
"elif",
"type",
"in",
"(",
"\"Characters\"",
",",
"\"SpaceCharacters\"",
")",
":",
"handler",
".",
"characters",
"(",
"token",
"[",
"\"data\"",
"]",
")",
"elif",
"type",
"==",
"\"Comment\"",
":",
"pass",
"else",
":",
"assert",
"False",
",",
"\"Unknown token type\"",
"for",
"prefix",
",",
"namespace",
"in",
"prefix_mapping",
".",
"items",
"(",
")",
":",
"handler",
".",
"endPrefixMapping",
"(",
"prefix",
")",
"handler",
".",
"endDocument",
"(",
")"
] | Call SAX-like content handler based on treewalker walker
:arg walker: the treewalker to use to walk the tree to convert it
:arg handler: SAX handler to use | [
"Call",
"SAX",
"-",
"like",
"content",
"handler",
"based",
"on",
"treewalker",
"walker"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treeadapters/sax.py#L13-L50 |
24,989 | pypa/pipenv | pipenv/patched/notpip/_vendor/retrying.py | retry | def retry(*dargs, **dkw):
"""
Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
def wrap_simple(f):
@six.wraps(f)
def wrapped_f(*args, **kw):
return Retrying().call(f, *args, **kw)
return wrapped_f
return wrap_simple(dargs[0])
else:
def wrap(f):
@six.wraps(f)
def wrapped_f(*args, **kw):
return Retrying(*dargs, **dkw).call(f, *args, **kw)
return wrapped_f
return wrap | python | def retry(*dargs, **dkw):
"""
Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
def wrap_simple(f):
@six.wraps(f)
def wrapped_f(*args, **kw):
return Retrying().call(f, *args, **kw)
return wrapped_f
return wrap_simple(dargs[0])
else:
def wrap(f):
@six.wraps(f)
def wrapped_f(*args, **kw):
return Retrying(*dargs, **dkw).call(f, *args, **kw)
return wrapped_f
return wrap | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"def",
"wrap_simple",
"(",
"f",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"Retrying",
"(",
")",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"wrapped_f",
"return",
"wrap_simple",
"(",
"dargs",
"[",
"0",
"]",
")",
"else",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"Retrying",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"wrapped_f",
"return",
"wrap"
] | Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object | [
"Decorator",
"function",
"that",
"instantiates",
"the",
"Retrying",
"object"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/retrying.py#L26-L53 |
24,990 | pypa/pipenv | pipenv/patched/notpip/_vendor/retrying.py | Retrying.random_sleep | def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Sleep a random amount of time between wait_random_min and wait_random_max"""
return random.randint(self._wait_random_min, self._wait_random_max) | python | def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Sleep a random amount of time between wait_random_min and wait_random_max"""
return random.randint(self._wait_random_min, self._wait_random_max) | [
"def",
"random_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"random",
".",
"randint",
"(",
"self",
".",
"_wait_random_min",
",",
"self",
".",
"_wait_random_max",
")"
] | Sleep a random amount of time between wait_random_min and wait_random_max | [
"Sleep",
"a",
"random",
"amount",
"of",
"time",
"between",
"wait_random_min",
"and",
"wait_random_max"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/retrying.py#L157-L159 |
24,991 | pypa/pipenv | pipenv/patched/notpip/_vendor/retrying.py | Attempt.get | def get(self, wrap_exception=False):
"""
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
"""
if self.has_exception:
if wrap_exception:
raise RetryError(self)
else:
six.reraise(self.value[0], self.value[1], self.value[2])
else:
return self.value | python | def get(self, wrap_exception=False):
"""
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
"""
if self.has_exception:
if wrap_exception:
raise RetryError(self)
else:
six.reraise(self.value[0], self.value[1], self.value[2])
else:
return self.value | [
"def",
"get",
"(",
"self",
",",
"wrap_exception",
"=",
"False",
")",
":",
"if",
"self",
".",
"has_exception",
":",
"if",
"wrap_exception",
":",
"raise",
"RetryError",
"(",
"self",
")",
"else",
":",
"six",
".",
"reraise",
"(",
"self",
".",
"value",
"[",
"0",
"]",
",",
"self",
".",
"value",
"[",
"1",
"]",
",",
"self",
".",
"value",
"[",
"2",
"]",
")",
"else",
":",
"return",
"self",
".",
"value"
] | Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised. | [
"Return",
"the",
"return",
"value",
"of",
"this",
"Attempt",
"instance",
"or",
"raise",
"an",
"Exception",
".",
"If",
"wrap_exception",
"is",
"true",
"this",
"Attempt",
"is",
"wrapped",
"inside",
"of",
"a",
"RetryError",
"before",
"being",
"raised",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/retrying.py#L237-L249 |
24,992 | pypa/pipenv | pipenv/vendor/jinja2/sandbox.py | SandboxedEnvironment.unsafe_undefined | def unsafe_undefined(self, obj, attribute):
"""Return an undefined object for unsafe attributes."""
return self.undefined('access to attribute %r of %r '
'object is unsafe.' % (
attribute,
obj.__class__.__name__
), name=attribute, obj=obj, exc=SecurityError) | python | def unsafe_undefined(self, obj, attribute):
"""Return an undefined object for unsafe attributes."""
return self.undefined('access to attribute %r of %r '
'object is unsafe.' % (
attribute,
obj.__class__.__name__
), name=attribute, obj=obj, exc=SecurityError) | [
"def",
"unsafe_undefined",
"(",
"self",
",",
"obj",
",",
"attribute",
")",
":",
"return",
"self",
".",
"undefined",
"(",
"'access to attribute %r of %r '",
"'object is unsafe.'",
"%",
"(",
"attribute",
",",
"obj",
".",
"__class__",
".",
"__name__",
")",
",",
"name",
"=",
"attribute",
",",
"obj",
"=",
"obj",
",",
"exc",
"=",
"SecurityError",
")"
] | Return an undefined object for unsafe attributes. | [
"Return",
"an",
"undefined",
"object",
"for",
"unsafe",
"attributes",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/sandbox.py#L397-L403 |
24,993 | pypa/pipenv | pipenv/vendor/jinja2/sandbox.py | SandboxedEnvironment.format_string | def format_string(self, s, args, kwargs):
"""If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
"""
if isinstance(s, Markup):
formatter = SandboxedEscapeFormatter(self, s.escape)
else:
formatter = SandboxedFormatter(self)
kwargs = _MagicFormatMapping(args, kwargs)
rv = formatter.vformat(s, args, kwargs)
return type(s)(rv) | python | def format_string(self, s, args, kwargs):
"""If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
"""
if isinstance(s, Markup):
formatter = SandboxedEscapeFormatter(self, s.escape)
else:
formatter = SandboxedFormatter(self)
kwargs = _MagicFormatMapping(args, kwargs)
rv = formatter.vformat(s, args, kwargs)
return type(s)(rv) | [
"def",
"format_string",
"(",
"self",
",",
"s",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Markup",
")",
":",
"formatter",
"=",
"SandboxedEscapeFormatter",
"(",
"self",
",",
"s",
".",
"escape",
")",
"else",
":",
"formatter",
"=",
"SandboxedFormatter",
"(",
"self",
")",
"kwargs",
"=",
"_MagicFormatMapping",
"(",
"args",
",",
"kwargs",
")",
"rv",
"=",
"formatter",
".",
"vformat",
"(",
"s",
",",
"args",
",",
"kwargs",
")",
"return",
"type",
"(",
"s",
")",
"(",
"rv",
")"
] | If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it. | [
"If",
"a",
"format",
"call",
"is",
"detected",
"then",
"this",
"is",
"routed",
"through",
"this",
"method",
"so",
"that",
"our",
"safety",
"sandbox",
"can",
"be",
"used",
"for",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/sandbox.py#L405-L415 |
24,994 | pypa/pipenv | pipenv/vendor/attr/_make.py | attrib | def attrib(
default=NOTHING,
validator=None,
repr=True,
cmp=True,
hash=None,
init=True,
convert=None,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=False,
):
"""
Create a new attribute on a class.
.. warning::
Does *not* do anything unless the class is also decorated with
:func:`attr.s`!
:param default: A value that is used if an ``attrs``-generated ``__init__``
is used and no value is passed while instantiating or the attribute is
excluded using ``init=False``.
If the value is an instance of :class:`Factory`, its callable will be
used to construct a new value (useful for mutable data types like lists
or dicts).
If a default is not set (or set manually to ``attr.NOTHING``), a value
*must* be supplied when instantiating; otherwise a :exc:`TypeError`
will be raised.
The default can also be set using decorator notation as shown below.
:type default: Any value.
:param callable factory: Syntactic sugar for
``default=attr.Factory(callable)``.
:param validator: :func:`callable` that is called by ``attrs``-generated
``__init__`` methods after the instance has been initialized. They
receive the initialized instance, the :class:`Attribute`, and the
passed value.
The return value is *not* inspected so the validator has to throw an
exception itself.
If a ``list`` is passed, its items are treated as validators and must
all pass.
Validators can be globally disabled and re-enabled using
:func:`get_run_validators`.
The validator can also be set using decorator notation as shown below.
:type validator: ``callable`` or a ``list`` of ``callable``\\ s.
:param bool repr: Include this attribute in the generated ``__repr__``
method.
:param bool cmp: Include this attribute in the generated comparison methods
(``__eq__`` et al).
:param hash: Include this attribute in the generated ``__hash__``
method. If ``None`` (default), mirror *cmp*'s value. This is the
correct behavior according the Python spec. Setting this value to
anything else than ``None`` is *discouraged*.
:type hash: ``bool`` or ``None``
:param bool init: Include this attribute in the generated ``__init__``
method. It is possible to set this to ``False`` and set a default
value. In that case this attributed is unconditionally initialized
with the specified default value or factory.
:param callable converter: :func:`callable` that is called by
``attrs``-generated ``__init__`` methods to converter attribute's value
to the desired format. It is given the passed-in value, and the
returned value will be used as the new value of the attribute. The
value is converted before being passed to the validator, if any.
:param metadata: An arbitrary mapping, to be used by third-party
components. See :ref:`extending_metadata`.
:param type: The type of the attribute. In Python 3.6 or greater, the
preferred method to specify the type is using a variable annotation
(see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_).
This argument is provided for backward compatibility.
Regardless of the approach used, the type will be stored on
``Attribute.type``.
Please note that ``attrs`` doesn't do anything with this metadata by
itself. You can use it as part of your own code or for
:doc:`static type checking <types>`.
:param kw_only: Make this attribute keyword-only (Python 3+)
in the generated ``__init__`` (if ``init`` is ``False``, this
parameter is ignored).
.. versionadded:: 15.2.0 *convert*
.. versionadded:: 16.3.0 *metadata*
.. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
.. versionchanged:: 17.1.0
*hash* is ``None`` and therefore mirrors *cmp* by default.
.. versionadded:: 17.3.0 *type*
.. deprecated:: 17.4.0 *convert*
.. versionadded:: 17.4.0 *converter* as a replacement for the deprecated
*convert* to achieve consistency with other noun-based arguments.
.. versionadded:: 18.1.0
``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
.. versionadded:: 18.2.0 *kw_only*
"""
if hash is not None and hash is not True and hash is not False:
raise TypeError(
"Invalid value for hash. Must be True, False, or None."
)
if convert is not None:
if converter is not None:
raise RuntimeError(
"Can't pass both `convert` and `converter`. "
"Please use `converter` only."
)
warnings.warn(
"The `convert` argument is deprecated in favor of `converter`. "
"It will be removed after 2019/01.",
DeprecationWarning,
stacklevel=2,
)
converter = convert
if factory is not None:
if default is not NOTHING:
raise ValueError(
"The `default` and `factory` arguments are mutually "
"exclusive."
)
if not callable(factory):
raise ValueError("The `factory` argument must be a callable.")
default = Factory(factory)
if metadata is None:
metadata = {}
return _CountingAttr(
default=default,
validator=validator,
repr=repr,
cmp=cmp,
hash=hash,
init=init,
converter=converter,
metadata=metadata,
type=type,
kw_only=kw_only,
) | python | def attrib(
default=NOTHING,
validator=None,
repr=True,
cmp=True,
hash=None,
init=True,
convert=None,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=False,
):
"""
Create a new attribute on a class.
.. warning::
Does *not* do anything unless the class is also decorated with
:func:`attr.s`!
:param default: A value that is used if an ``attrs``-generated ``__init__``
is used and no value is passed while instantiating or the attribute is
excluded using ``init=False``.
If the value is an instance of :class:`Factory`, its callable will be
used to construct a new value (useful for mutable data types like lists
or dicts).
If a default is not set (or set manually to ``attr.NOTHING``), a value
*must* be supplied when instantiating; otherwise a :exc:`TypeError`
will be raised.
The default can also be set using decorator notation as shown below.
:type default: Any value.
:param callable factory: Syntactic sugar for
``default=attr.Factory(callable)``.
:param validator: :func:`callable` that is called by ``attrs``-generated
``__init__`` methods after the instance has been initialized. They
receive the initialized instance, the :class:`Attribute`, and the
passed value.
The return value is *not* inspected so the validator has to throw an
exception itself.
If a ``list`` is passed, its items are treated as validators and must
all pass.
Validators can be globally disabled and re-enabled using
:func:`get_run_validators`.
The validator can also be set using decorator notation as shown below.
:type validator: ``callable`` or a ``list`` of ``callable``\\ s.
:param bool repr: Include this attribute in the generated ``__repr__``
method.
:param bool cmp: Include this attribute in the generated comparison methods
(``__eq__`` et al).
:param hash: Include this attribute in the generated ``__hash__``
method. If ``None`` (default), mirror *cmp*'s value. This is the
correct behavior according the Python spec. Setting this value to
anything else than ``None`` is *discouraged*.
:type hash: ``bool`` or ``None``
:param bool init: Include this attribute in the generated ``__init__``
method. It is possible to set this to ``False`` and set a default
value. In that case this attributed is unconditionally initialized
with the specified default value or factory.
:param callable converter: :func:`callable` that is called by
``attrs``-generated ``__init__`` methods to converter attribute's value
to the desired format. It is given the passed-in value, and the
returned value will be used as the new value of the attribute. The
value is converted before being passed to the validator, if any.
:param metadata: An arbitrary mapping, to be used by third-party
components. See :ref:`extending_metadata`.
:param type: The type of the attribute. In Python 3.6 or greater, the
preferred method to specify the type is using a variable annotation
(see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_).
This argument is provided for backward compatibility.
Regardless of the approach used, the type will be stored on
``Attribute.type``.
Please note that ``attrs`` doesn't do anything with this metadata by
itself. You can use it as part of your own code or for
:doc:`static type checking <types>`.
:param kw_only: Make this attribute keyword-only (Python 3+)
in the generated ``__init__`` (if ``init`` is ``False``, this
parameter is ignored).
.. versionadded:: 15.2.0 *convert*
.. versionadded:: 16.3.0 *metadata*
.. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
.. versionchanged:: 17.1.0
*hash* is ``None`` and therefore mirrors *cmp* by default.
.. versionadded:: 17.3.0 *type*
.. deprecated:: 17.4.0 *convert*
.. versionadded:: 17.4.0 *converter* as a replacement for the deprecated
*convert* to achieve consistency with other noun-based arguments.
.. versionadded:: 18.1.0
``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
.. versionadded:: 18.2.0 *kw_only*
"""
if hash is not None and hash is not True and hash is not False:
raise TypeError(
"Invalid value for hash. Must be True, False, or None."
)
if convert is not None:
if converter is not None:
raise RuntimeError(
"Can't pass both `convert` and `converter`. "
"Please use `converter` only."
)
warnings.warn(
"The `convert` argument is deprecated in favor of `converter`. "
"It will be removed after 2019/01.",
DeprecationWarning,
stacklevel=2,
)
converter = convert
if factory is not None:
if default is not NOTHING:
raise ValueError(
"The `default` and `factory` arguments are mutually "
"exclusive."
)
if not callable(factory):
raise ValueError("The `factory` argument must be a callable.")
default = Factory(factory)
if metadata is None:
metadata = {}
return _CountingAttr(
default=default,
validator=validator,
repr=repr,
cmp=cmp,
hash=hash,
init=init,
converter=converter,
metadata=metadata,
type=type,
kw_only=kw_only,
) | [
"def",
"attrib",
"(",
"default",
"=",
"NOTHING",
",",
"validator",
"=",
"None",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"hash",
"=",
"None",
",",
"init",
"=",
"True",
",",
"convert",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"type",
"=",
"None",
",",
"converter",
"=",
"None",
",",
"factory",
"=",
"None",
",",
"kw_only",
"=",
"False",
",",
")",
":",
"if",
"hash",
"is",
"not",
"None",
"and",
"hash",
"is",
"not",
"True",
"and",
"hash",
"is",
"not",
"False",
":",
"raise",
"TypeError",
"(",
"\"Invalid value for hash. Must be True, False, or None.\"",
")",
"if",
"convert",
"is",
"not",
"None",
":",
"if",
"converter",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Can't pass both `convert` and `converter`. \"",
"\"Please use `converter` only.\"",
")",
"warnings",
".",
"warn",
"(",
"\"The `convert` argument is deprecated in favor of `converter`. \"",
"\"It will be removed after 2019/01.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"converter",
"=",
"convert",
"if",
"factory",
"is",
"not",
"None",
":",
"if",
"default",
"is",
"not",
"NOTHING",
":",
"raise",
"ValueError",
"(",
"\"The `default` and `factory` arguments are mutually \"",
"\"exclusive.\"",
")",
"if",
"not",
"callable",
"(",
"factory",
")",
":",
"raise",
"ValueError",
"(",
"\"The `factory` argument must be a callable.\"",
")",
"default",
"=",
"Factory",
"(",
"factory",
")",
"if",
"metadata",
"is",
"None",
":",
"metadata",
"=",
"{",
"}",
"return",
"_CountingAttr",
"(",
"default",
"=",
"default",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"hash",
"=",
"hash",
",",
"init",
"=",
"init",
",",
"converter",
"=",
"converter",
",",
"metadata",
"=",
"metadata",
",",
"type",
"=",
"type",
",",
"kw_only",
"=",
"kw_only",
",",
")"
] | Create a new attribute on a class.
.. warning::
Does *not* do anything unless the class is also decorated with
:func:`attr.s`!
:param default: A value that is used if an ``attrs``-generated ``__init__``
is used and no value is passed while instantiating or the attribute is
excluded using ``init=False``.
If the value is an instance of :class:`Factory`, its callable will be
used to construct a new value (useful for mutable data types like lists
or dicts).
If a default is not set (or set manually to ``attr.NOTHING``), a value
*must* be supplied when instantiating; otherwise a :exc:`TypeError`
will be raised.
The default can also be set using decorator notation as shown below.
:type default: Any value.
:param callable factory: Syntactic sugar for
``default=attr.Factory(callable)``.
:param validator: :func:`callable` that is called by ``attrs``-generated
``__init__`` methods after the instance has been initialized. They
receive the initialized instance, the :class:`Attribute`, and the
passed value.
The return value is *not* inspected so the validator has to throw an
exception itself.
If a ``list`` is passed, its items are treated as validators and must
all pass.
Validators can be globally disabled and re-enabled using
:func:`get_run_validators`.
The validator can also be set using decorator notation as shown below.
:type validator: ``callable`` or a ``list`` of ``callable``\\ s.
:param bool repr: Include this attribute in the generated ``__repr__``
method.
:param bool cmp: Include this attribute in the generated comparison methods
(``__eq__`` et al).
:param hash: Include this attribute in the generated ``__hash__``
method. If ``None`` (default), mirror *cmp*'s value. This is the
correct behavior according the Python spec. Setting this value to
anything else than ``None`` is *discouraged*.
:type hash: ``bool`` or ``None``
:param bool init: Include this attribute in the generated ``__init__``
method. It is possible to set this to ``False`` and set a default
value. In that case this attributed is unconditionally initialized
with the specified default value or factory.
:param callable converter: :func:`callable` that is called by
``attrs``-generated ``__init__`` methods to converter attribute's value
to the desired format. It is given the passed-in value, and the
returned value will be used as the new value of the attribute. The
value is converted before being passed to the validator, if any.
:param metadata: An arbitrary mapping, to be used by third-party
components. See :ref:`extending_metadata`.
:param type: The type of the attribute. In Python 3.6 or greater, the
preferred method to specify the type is using a variable annotation
(see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_).
This argument is provided for backward compatibility.
Regardless of the approach used, the type will be stored on
``Attribute.type``.
Please note that ``attrs`` doesn't do anything with this metadata by
itself. You can use it as part of your own code or for
:doc:`static type checking <types>`.
:param kw_only: Make this attribute keyword-only (Python 3+)
in the generated ``__init__`` (if ``init`` is ``False``, this
parameter is ignored).
.. versionadded:: 15.2.0 *convert*
.. versionadded:: 16.3.0 *metadata*
.. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
.. versionchanged:: 17.1.0
*hash* is ``None`` and therefore mirrors *cmp* by default.
.. versionadded:: 17.3.0 *type*
.. deprecated:: 17.4.0 *convert*
.. versionadded:: 17.4.0 *converter* as a replacement for the deprecated
*convert* to achieve consistency with other noun-based arguments.
.. versionadded:: 18.1.0
``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
.. versionadded:: 18.2.0 *kw_only* | [
"Create",
"a",
"new",
"attribute",
"on",
"a",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L70-L219 |
24,995 | pypa/pipenv | pipenv/vendor/attr/_make.py | _make_attr_tuple_class | def _make_attr_tuple_class(cls_name, attr_names):
"""
Create a tuple subclass to hold `Attribute`s for an `attrs` class.
The subclass is a bare tuple with properties for names.
class MyClassAttributes(tuple):
__slots__ = ()
x = property(itemgetter(0))
"""
attr_class_name = "{}Attributes".format(cls_name)
attr_class_template = [
"class {}(tuple):".format(attr_class_name),
" __slots__ = ()",
]
if attr_names:
for i, attr_name in enumerate(attr_names):
attr_class_template.append(
_tuple_property_pat.format(index=i, attr_name=attr_name)
)
else:
attr_class_template.append(" pass")
globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property}
eval(compile("\n".join(attr_class_template), "", "exec"), globs)
return globs[attr_class_name] | python | def _make_attr_tuple_class(cls_name, attr_names):
"""
Create a tuple subclass to hold `Attribute`s for an `attrs` class.
The subclass is a bare tuple with properties for names.
class MyClassAttributes(tuple):
__slots__ = ()
x = property(itemgetter(0))
"""
attr_class_name = "{}Attributes".format(cls_name)
attr_class_template = [
"class {}(tuple):".format(attr_class_name),
" __slots__ = ()",
]
if attr_names:
for i, attr_name in enumerate(attr_names):
attr_class_template.append(
_tuple_property_pat.format(index=i, attr_name=attr_name)
)
else:
attr_class_template.append(" pass")
globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property}
eval(compile("\n".join(attr_class_template), "", "exec"), globs)
return globs[attr_class_name] | [
"def",
"_make_attr_tuple_class",
"(",
"cls_name",
",",
"attr_names",
")",
":",
"attr_class_name",
"=",
"\"{}Attributes\"",
".",
"format",
"(",
"cls_name",
")",
"attr_class_template",
"=",
"[",
"\"class {}(tuple):\"",
".",
"format",
"(",
"attr_class_name",
")",
",",
"\" __slots__ = ()\"",
",",
"]",
"if",
"attr_names",
":",
"for",
"i",
",",
"attr_name",
"in",
"enumerate",
"(",
"attr_names",
")",
":",
"attr_class_template",
".",
"append",
"(",
"_tuple_property_pat",
".",
"format",
"(",
"index",
"=",
"i",
",",
"attr_name",
"=",
"attr_name",
")",
")",
"else",
":",
"attr_class_template",
".",
"append",
"(",
"\" pass\"",
")",
"globs",
"=",
"{",
"\"_attrs_itemgetter\"",
":",
"itemgetter",
",",
"\"_attrs_property\"",
":",
"property",
"}",
"eval",
"(",
"compile",
"(",
"\"\\n\"",
".",
"join",
"(",
"attr_class_template",
")",
",",
"\"\"",
",",
"\"exec\"",
")",
",",
"globs",
")",
"return",
"globs",
"[",
"attr_class_name",
"]"
] | Create a tuple subclass to hold `Attribute`s for an `attrs` class.
The subclass is a bare tuple with properties for names.
class MyClassAttributes(tuple):
__slots__ = ()
x = property(itemgetter(0)) | [
"Create",
"a",
"tuple",
"subclass",
"to",
"hold",
"Attribute",
"s",
"for",
"an",
"attrs",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L222-L247 |
24,996 | pypa/pipenv | pipenv/vendor/attr/_make.py | fields | def fields(cls):
"""
Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: tuple (with name accessors) of :class:`attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name.
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return attrs | python | def fields(cls):
"""
Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: tuple (with name accessors) of :class:`attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name.
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return attrs | [
"def",
"fields",
"(",
"cls",
")",
":",
"if",
"not",
"isclass",
"(",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Passed object must be a class.\"",
")",
"attrs",
"=",
"getattr",
"(",
"cls",
",",
"\"__attrs_attrs__\"",
",",
"None",
")",
"if",
"attrs",
"is",
"None",
":",
"raise",
"NotAnAttrsClassError",
"(",
"\"{cls!r} is not an attrs-decorated class.\"",
".",
"format",
"(",
"cls",
"=",
"cls",
")",
")",
"return",
"attrs"
] | Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: tuple (with name accessors) of :class:`attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name. | [
"Return",
"the",
"tuple",
"of",
"attrs",
"attributes",
"for",
"a",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L1311-L1336 |
24,997 | pypa/pipenv | pipenv/vendor/attr/_make.py | fields_dict | def fields_dict(cls):
"""
Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: an ordered dict where keys are attribute names and values are
:class:`attr.Attribute`\\ s. This will be a :class:`dict` if it's
naturally ordered like on Python 3.6+ or an
:class:`~collections.OrderedDict` otherwise.
.. versionadded:: 18.1.0
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return ordered_dict(((a.name, a) for a in attrs)) | python | def fields_dict(cls):
"""
Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: an ordered dict where keys are attribute names and values are
:class:`attr.Attribute`\\ s. This will be a :class:`dict` if it's
naturally ordered like on Python 3.6+ or an
:class:`~collections.OrderedDict` otherwise.
.. versionadded:: 18.1.0
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return ordered_dict(((a.name, a) for a in attrs)) | [
"def",
"fields_dict",
"(",
"cls",
")",
":",
"if",
"not",
"isclass",
"(",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Passed object must be a class.\"",
")",
"attrs",
"=",
"getattr",
"(",
"cls",
",",
"\"__attrs_attrs__\"",
",",
"None",
")",
"if",
"attrs",
"is",
"None",
":",
"raise",
"NotAnAttrsClassError",
"(",
"\"{cls!r} is not an attrs-decorated class.\"",
".",
"format",
"(",
"cls",
"=",
"cls",
")",
")",
"return",
"ordered_dict",
"(",
"(",
"(",
"a",
".",
"name",
",",
"a",
")",
"for",
"a",
"in",
"attrs",
")",
")"
] | Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: an ordered dict where keys are attribute names and values are
:class:`attr.Attribute`\\ s. This will be a :class:`dict` if it's
naturally ordered like on Python 3.6+ or an
:class:`~collections.OrderedDict` otherwise.
.. versionadded:: 18.1.0 | [
"Return",
"an",
"ordered",
"dictionary",
"of",
"attrs",
"attributes",
"for",
"a",
"class",
"whose",
"keys",
"are",
"the",
"attribute",
"names",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L1339-L1364 |
24,998 | pypa/pipenv | pipenv/vendor/attr/_make.py | and_ | def and_(*validators):
"""
A validator that composes multiple validators into one.
When called on a value, it runs all wrapped validators.
:param validators: Arbitrary number of validators.
:type validators: callables
.. versionadded:: 17.1.0
"""
vals = []
for validator in validators:
vals.extend(
validator._validators
if isinstance(validator, _AndValidator)
else [validator]
)
return _AndValidator(tuple(vals)) | python | def and_(*validators):
"""
A validator that composes multiple validators into one.
When called on a value, it runs all wrapped validators.
:param validators: Arbitrary number of validators.
:type validators: callables
.. versionadded:: 17.1.0
"""
vals = []
for validator in validators:
vals.extend(
validator._validators
if isinstance(validator, _AndValidator)
else [validator]
)
return _AndValidator(tuple(vals)) | [
"def",
"and_",
"(",
"*",
"validators",
")",
":",
"vals",
"=",
"[",
"]",
"for",
"validator",
"in",
"validators",
":",
"vals",
".",
"extend",
"(",
"validator",
".",
"_validators",
"if",
"isinstance",
"(",
"validator",
",",
"_AndValidator",
")",
"else",
"[",
"validator",
"]",
")",
"return",
"_AndValidator",
"(",
"tuple",
"(",
"vals",
")",
")"
] | A validator that composes multiple validators into one.
When called on a value, it runs all wrapped validators.
:param validators: Arbitrary number of validators.
:type validators: callables
.. versionadded:: 17.1.0 | [
"A",
"validator",
"that",
"composes",
"multiple",
"validators",
"into",
"one",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L2067-L2086 |
24,999 | pypa/pipenv | pipenv/vendor/attr/_make.py | _ClassBuilder._patch_original_class | def _patch_original_class(self):
"""
Apply accumulated methods and return the class.
"""
cls = self._cls
base_names = self._base_names
# Clean class of attribute definitions (`attr.ib()`s).
if self._delete_attribs:
for name in self._attr_names:
if (
name not in base_names
and getattr(cls, name, None) is not None
):
try:
delattr(cls, name)
except AttributeError:
# This can happen if a base class defines a class
# variable and we want to set an attribute with the
# same name by using only a type annotation.
pass
# Attach our dunder methods.
for name, value in self._cls_dict.items():
setattr(cls, name, value)
# Attach __setstate__. This is necessary to clear the hash code
# cache on deserialization. See issue
# https://github.com/python-attrs/attrs/issues/482 .
# Note that this code only handles setstate for dict classes.
# For slotted classes, see similar code in _create_slots_class .
if self._cache_hash:
existing_set_state_method = getattr(cls, "__setstate__", None)
if existing_set_state_method:
raise NotImplementedError(
"Currently you cannot use hash caching if "
"you specify your own __setstate__ method."
"See https://github.com/python-attrs/attrs/issues/494 ."
)
def cache_hash_set_state(chss_self, _):
# clear hash code cache
setattr(chss_self, _hash_cache_field, None)
setattr(cls, "__setstate__", cache_hash_set_state)
return cls | python | def _patch_original_class(self):
"""
Apply accumulated methods and return the class.
"""
cls = self._cls
base_names = self._base_names
# Clean class of attribute definitions (`attr.ib()`s).
if self._delete_attribs:
for name in self._attr_names:
if (
name not in base_names
and getattr(cls, name, None) is not None
):
try:
delattr(cls, name)
except AttributeError:
# This can happen if a base class defines a class
# variable and we want to set an attribute with the
# same name by using only a type annotation.
pass
# Attach our dunder methods.
for name, value in self._cls_dict.items():
setattr(cls, name, value)
# Attach __setstate__. This is necessary to clear the hash code
# cache on deserialization. See issue
# https://github.com/python-attrs/attrs/issues/482 .
# Note that this code only handles setstate for dict classes.
# For slotted classes, see similar code in _create_slots_class .
if self._cache_hash:
existing_set_state_method = getattr(cls, "__setstate__", None)
if existing_set_state_method:
raise NotImplementedError(
"Currently you cannot use hash caching if "
"you specify your own __setstate__ method."
"See https://github.com/python-attrs/attrs/issues/494 ."
)
def cache_hash_set_state(chss_self, _):
# clear hash code cache
setattr(chss_self, _hash_cache_field, None)
setattr(cls, "__setstate__", cache_hash_set_state)
return cls | [
"def",
"_patch_original_class",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"_cls",
"base_names",
"=",
"self",
".",
"_base_names",
"# Clean class of attribute definitions (`attr.ib()`s).",
"if",
"self",
".",
"_delete_attribs",
":",
"for",
"name",
"in",
"self",
".",
"_attr_names",
":",
"if",
"(",
"name",
"not",
"in",
"base_names",
"and",
"getattr",
"(",
"cls",
",",
"name",
",",
"None",
")",
"is",
"not",
"None",
")",
":",
"try",
":",
"delattr",
"(",
"cls",
",",
"name",
")",
"except",
"AttributeError",
":",
"# This can happen if a base class defines a class",
"# variable and we want to set an attribute with the",
"# same name by using only a type annotation.",
"pass",
"# Attach our dunder methods.",
"for",
"name",
",",
"value",
"in",
"self",
".",
"_cls_dict",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"cls",
",",
"name",
",",
"value",
")",
"# Attach __setstate__. This is necessary to clear the hash code",
"# cache on deserialization. See issue",
"# https://github.com/python-attrs/attrs/issues/482 .",
"# Note that this code only handles setstate for dict classes.",
"# For slotted classes, see similar code in _create_slots_class .",
"if",
"self",
".",
"_cache_hash",
":",
"existing_set_state_method",
"=",
"getattr",
"(",
"cls",
",",
"\"__setstate__\"",
",",
"None",
")",
"if",
"existing_set_state_method",
":",
"raise",
"NotImplementedError",
"(",
"\"Currently you cannot use hash caching if \"",
"\"you specify your own __setstate__ method.\"",
"\"See https://github.com/python-attrs/attrs/issues/494 .\"",
")",
"def",
"cache_hash_set_state",
"(",
"chss_self",
",",
"_",
")",
":",
"# clear hash code cache",
"setattr",
"(",
"chss_self",
",",
"_hash_cache_field",
",",
"None",
")",
"setattr",
"(",
"cls",
",",
"\"__setstate__\"",
",",
"cache_hash_set_state",
")",
"return",
"cls"
] | Apply accumulated methods and return the class. | [
"Apply",
"accumulated",
"methods",
"and",
"return",
"the",
"class",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L509-L555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.