repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_split_optional_netmask
|
def _split_optional_netmask(address):
"""Helper to split the netmask and raise AddressValueError if needed"""
addr = _compat_str(address).split('/')
if len(addr) > 2:
raise AddressValueError("Only one '/' permitted in %r" % address)
return addr
|
python
|
def _split_optional_netmask(address):
"""Helper to split the netmask and raise AddressValueError if needed"""
addr = _compat_str(address).split('/')
if len(addr) > 2:
raise AddressValueError("Only one '/' permitted in %r" % address)
return addr
|
[
"def",
"_split_optional_netmask",
"(",
"address",
")",
":",
"addr",
"=",
"_compat_str",
"(",
"address",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"addr",
")",
">",
"2",
":",
"raise",
"AddressValueError",
"(",
"\"Only one '/' permitted in %r\"",
"%",
"address",
")",
"return",
"addr"
] |
Helper to split the netmask and raise AddressValueError if needed
|
[
"Helper",
"to",
"split",
"the",
"netmask",
"and",
"raise",
"AddressValueError",
"if",
"needed"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L278-L283
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_find_address_range
|
def _find_address_range(addresses):
"""Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
"""
it = iter(addresses)
first = last = next(it)
for ip in it:
if ip._ip != last._ip + 1:
yield first, last
first = ip
last = ip
yield first, last
|
python
|
def _find_address_range(addresses):
"""Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
"""
it = iter(addresses)
first = last = next(it)
for ip in it:
if ip._ip != last._ip + 1:
yield first, last
first = ip
last = ip
yield first, last
|
[
"def",
"_find_address_range",
"(",
"addresses",
")",
":",
"it",
"=",
"iter",
"(",
"addresses",
")",
"first",
"=",
"last",
"=",
"next",
"(",
"it",
")",
"for",
"ip",
"in",
"it",
":",
"if",
"ip",
".",
"_ip",
"!=",
"last",
".",
"_ip",
"+",
"1",
":",
"yield",
"first",
",",
"last",
"first",
"=",
"ip",
"last",
"=",
"ip",
"yield",
"first",
",",
"last"
] |
Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
|
[
"Find",
"a",
"sequence",
"of",
"sorted",
"deduplicated",
"IPv#Address",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L286-L303
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_count_righthand_zero_bits
|
def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return bits
return min(bits, _compat_bit_length(~number & (number - 1)))
|
python
|
def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return bits
return min(bits, _compat_bit_length(~number & (number - 1)))
|
[
"def",
"_count_righthand_zero_bits",
"(",
"number",
",",
"bits",
")",
":",
"if",
"number",
"==",
"0",
":",
"return",
"bits",
"return",
"min",
"(",
"bits",
",",
"_compat_bit_length",
"(",
"~",
"number",
"&",
"(",
"number",
"-",
"1",
")",
")",
")"
] |
Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
|
[
"Count",
"the",
"number",
"of",
"zero",
"bits",
"on",
"the",
"right",
"hand",
"side",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L306-L319
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_collapse_addresses_internal
|
def _collapse_addresses_internal(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
"""
# First merge
to_merge = list(addresses)
subnets = {}
while to_merge:
net = to_merge.pop()
supernet = net.supernet()
existing = subnets.get(supernet)
if existing is None:
subnets[supernet] = net
elif existing != net:
# Merge consecutive subnets
del subnets[supernet]
to_merge.append(supernet)
# Then iterate over resulting networks, skipping subsumed subnets
last = None
for net in sorted(subnets.values()):
if last is not None:
# Since they are sorted,
# last.network_address <= net.network_address is a given.
if last.broadcast_address >= net.broadcast_address:
continue
yield net
last = net
|
python
|
def _collapse_addresses_internal(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
"""
# First merge
to_merge = list(addresses)
subnets = {}
while to_merge:
net = to_merge.pop()
supernet = net.supernet()
existing = subnets.get(supernet)
if existing is None:
subnets[supernet] = net
elif existing != net:
# Merge consecutive subnets
del subnets[supernet]
to_merge.append(supernet)
# Then iterate over resulting networks, skipping subsumed subnets
last = None
for net in sorted(subnets.values()):
if last is not None:
# Since they are sorted,
# last.network_address <= net.network_address is a given.
if last.broadcast_address >= net.broadcast_address:
continue
yield net
last = net
|
[
"def",
"_collapse_addresses_internal",
"(",
"addresses",
")",
":",
"# First merge",
"to_merge",
"=",
"list",
"(",
"addresses",
")",
"subnets",
"=",
"{",
"}",
"while",
"to_merge",
":",
"net",
"=",
"to_merge",
".",
"pop",
"(",
")",
"supernet",
"=",
"net",
".",
"supernet",
"(",
")",
"existing",
"=",
"subnets",
".",
"get",
"(",
"supernet",
")",
"if",
"existing",
"is",
"None",
":",
"subnets",
"[",
"supernet",
"]",
"=",
"net",
"elif",
"existing",
"!=",
"net",
":",
"# Merge consecutive subnets",
"del",
"subnets",
"[",
"supernet",
"]",
"to_merge",
".",
"append",
"(",
"supernet",
")",
"# Then iterate over resulting networks, skipping subsumed subnets",
"last",
"=",
"None",
"for",
"net",
"in",
"sorted",
"(",
"subnets",
".",
"values",
"(",
")",
")",
":",
"if",
"last",
"is",
"not",
"None",
":",
"# Since they are sorted,",
"# last.network_address <= net.network_address is a given.",
"if",
"last",
".",
"broadcast_address",
">=",
"net",
".",
"broadcast_address",
":",
"continue",
"yield",
"net",
"last",
"=",
"net"
] |
Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
|
[
"Loops",
"through",
"the",
"addresses",
"collapsing",
"concurrent",
"netblocks",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L377-L423
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
collapse_addresses
|
def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
"""
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
# find consecutive address ranges in the sorted sequence and summarize them
if ips:
for first, last in _find_address_range(ips):
addrs.extend(summarize_address_range(first, last))
return _collapse_addresses_internal(addrs + nets)
|
python
|
def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
"""
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
# find consecutive address ranges in the sorted sequence and summarize them
if ips:
for first, last in _find_address_range(ips):
addrs.extend(summarize_address_range(first, last))
return _collapse_addresses_internal(addrs + nets)
|
[
"def",
"collapse_addresses",
"(",
"addresses",
")",
":",
"addrs",
"=",
"[",
"]",
"ips",
"=",
"[",
"]",
"nets",
"=",
"[",
"]",
"# split IP addresses and networks",
"for",
"ip",
"in",
"addresses",
":",
"if",
"isinstance",
"(",
"ip",
",",
"_BaseAddress",
")",
":",
"if",
"ips",
"and",
"ips",
"[",
"-",
"1",
"]",
".",
"_version",
"!=",
"ip",
".",
"_version",
":",
"raise",
"TypeError",
"(",
"\"%s and %s are not of the same version\"",
"%",
"(",
"ip",
",",
"ips",
"[",
"-",
"1",
"]",
")",
")",
"ips",
".",
"append",
"(",
"ip",
")",
"elif",
"ip",
".",
"_prefixlen",
"==",
"ip",
".",
"_max_prefixlen",
":",
"if",
"ips",
"and",
"ips",
"[",
"-",
"1",
"]",
".",
"_version",
"!=",
"ip",
".",
"_version",
":",
"raise",
"TypeError",
"(",
"\"%s and %s are not of the same version\"",
"%",
"(",
"ip",
",",
"ips",
"[",
"-",
"1",
"]",
")",
")",
"try",
":",
"ips",
".",
"append",
"(",
"ip",
".",
"ip",
")",
"except",
"AttributeError",
":",
"ips",
".",
"append",
"(",
"ip",
".",
"network_address",
")",
"else",
":",
"if",
"nets",
"and",
"nets",
"[",
"-",
"1",
"]",
".",
"_version",
"!=",
"ip",
".",
"_version",
":",
"raise",
"TypeError",
"(",
"\"%s and %s are not of the same version\"",
"%",
"(",
"ip",
",",
"nets",
"[",
"-",
"1",
"]",
")",
")",
"nets",
".",
"append",
"(",
"ip",
")",
"# sort and dedup",
"ips",
"=",
"sorted",
"(",
"set",
"(",
"ips",
")",
")",
"# find consecutive address ranges in the sorted sequence and summarize them",
"if",
"ips",
":",
"for",
"first",
",",
"last",
"in",
"_find_address_range",
"(",
"ips",
")",
":",
"addrs",
".",
"extend",
"(",
"summarize_address_range",
"(",
"first",
",",
"last",
")",
")",
"return",
"_collapse_addresses_internal",
"(",
"addrs",
"+",
"nets",
")"
] |
Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
|
[
"Collapse",
"a",
"list",
"of",
"IP",
"objects",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L426-L477
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
get_mixed_type_key
|
def get_mixed_type_key(obj):
"""Return a key suitable for sorting between networks and addresses.
Address and Network objects are not sortable by default; they're
fundamentally different so the expression
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
doesn't make any sense. There are some times however, where you may wish
to have ipaddress sort these for you anyway. If you need to do this, you
can use this function as the key= argument to sorted().
Args:
obj: either a Network or Address object.
Returns:
appropriate key.
"""
if isinstance(obj, _BaseNetwork):
return obj._get_networks_key()
elif isinstance(obj, _BaseAddress):
return obj._get_address_key()
return NotImplemented
|
python
|
def get_mixed_type_key(obj):
"""Return a key suitable for sorting between networks and addresses.
Address and Network objects are not sortable by default; they're
fundamentally different so the expression
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
doesn't make any sense. There are some times however, where you may wish
to have ipaddress sort these for you anyway. If you need to do this, you
can use this function as the key= argument to sorted().
Args:
obj: either a Network or Address object.
Returns:
appropriate key.
"""
if isinstance(obj, _BaseNetwork):
return obj._get_networks_key()
elif isinstance(obj, _BaseAddress):
return obj._get_address_key()
return NotImplemented
|
[
"def",
"get_mixed_type_key",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"_BaseNetwork",
")",
":",
"return",
"obj",
".",
"_get_networks_key",
"(",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"_BaseAddress",
")",
":",
"return",
"obj",
".",
"_get_address_key",
"(",
")",
"return",
"NotImplemented"
] |
Return a key suitable for sorting between networks and addresses.
Address and Network objects are not sortable by default; they're
fundamentally different so the expression
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
doesn't make any sense. There are some times however, where you may wish
to have ipaddress sort these for you anyway. If you need to do this, you
can use this function as the key= argument to sorted().
Args:
obj: either a Network or Address object.
Returns:
appropriate key.
|
[
"Return",
"a",
"key",
"suitable",
"for",
"sorting",
"between",
"networks",
"and",
"addresses",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L480-L502
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_IPAddressBase._prefix_from_ip_int
|
def _prefix_from_ip_int(cls, ip_int):
"""Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones
"""
trailing_zeroes = _count_righthand_zero_bits(ip_int,
cls._max_prefixlen)
prefixlen = cls._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefixlen) - 1
if leading_ones != all_ones:
byteslen = cls._max_prefixlen // 8
details = _compat_to_bytes(ip_int, byteslen, 'big')
msg = 'Netmask pattern %r mixes zeroes & ones'
raise ValueError(msg % details)
return prefixlen
|
python
|
def _prefix_from_ip_int(cls, ip_int):
"""Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones
"""
trailing_zeroes = _count_righthand_zero_bits(ip_int,
cls._max_prefixlen)
prefixlen = cls._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefixlen) - 1
if leading_ones != all_ones:
byteslen = cls._max_prefixlen // 8
details = _compat_to_bytes(ip_int, byteslen, 'big')
msg = 'Netmask pattern %r mixes zeroes & ones'
raise ValueError(msg % details)
return prefixlen
|
[
"def",
"_prefix_from_ip_int",
"(",
"cls",
",",
"ip_int",
")",
":",
"trailing_zeroes",
"=",
"_count_righthand_zero_bits",
"(",
"ip_int",
",",
"cls",
".",
"_max_prefixlen",
")",
"prefixlen",
"=",
"cls",
".",
"_max_prefixlen",
"-",
"trailing_zeroes",
"leading_ones",
"=",
"ip_int",
">>",
"trailing_zeroes",
"all_ones",
"=",
"(",
"1",
"<<",
"prefixlen",
")",
"-",
"1",
"if",
"leading_ones",
"!=",
"all_ones",
":",
"byteslen",
"=",
"cls",
".",
"_max_prefixlen",
"//",
"8",
"details",
"=",
"_compat_to_bytes",
"(",
"ip_int",
",",
"byteslen",
",",
"'big'",
")",
"msg",
"=",
"'Netmask pattern %r mixes zeroes & ones'",
"raise",
"ValueError",
"(",
"msg",
"%",
"details",
")",
"return",
"prefixlen"
] |
Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones
|
[
"Return",
"prefix",
"length",
"from",
"the",
"bitwise",
"netmask",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L570-L592
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_IPAddressBase._prefix_from_prefix_string
|
def _prefix_from_prefix_string(cls, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
"""
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
cls._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
cls._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen_str)
return prefixlen
|
python
|
def _prefix_from_prefix_string(cls, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
"""
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
cls._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
cls._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen_str)
return prefixlen
|
[
"def",
"_prefix_from_prefix_string",
"(",
"cls",
",",
"prefixlen_str",
")",
":",
"# int allows a leading +/- as well as surrounding whitespace,",
"# so we ensure that isn't the case",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"try",
":",
"prefixlen",
"=",
"int",
"(",
"prefixlen_str",
")",
"except",
"ValueError",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"if",
"not",
"(",
"0",
"<=",
"prefixlen",
"<=",
"cls",
".",
"_max_prefixlen",
")",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"return",
"prefixlen"
] |
Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
|
[
"Return",
"prefix",
"length",
"from",
"a",
"numeric",
"string"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L600-L622
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_IPAddressBase._prefix_from_ip_string
|
def _prefix_from_ip_string(cls, ip_str):
"""Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask
"""
# Parse the netmask/hostmask like an IP address.
try:
ip_int = cls._ip_int_from_string(ip_str)
except AddressValueError:
cls._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
# Note that the two ambiguous cases (all-ones and all-zeroes) are
# treated as netmasks.
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
pass
# Invert the bits, and try matching a /0+1+/ hostmask instead.
ip_int ^= cls._ALL_ONES
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
cls._report_invalid_netmask(ip_str)
|
python
|
def _prefix_from_ip_string(cls, ip_str):
"""Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask
"""
# Parse the netmask/hostmask like an IP address.
try:
ip_int = cls._ip_int_from_string(ip_str)
except AddressValueError:
cls._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
# Note that the two ambiguous cases (all-ones and all-zeroes) are
# treated as netmasks.
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
pass
# Invert the bits, and try matching a /0+1+/ hostmask instead.
ip_int ^= cls._ALL_ONES
try:
return cls._prefix_from_ip_int(ip_int)
except ValueError:
cls._report_invalid_netmask(ip_str)
|
[
"def",
"_prefix_from_ip_string",
"(",
"cls",
",",
"ip_str",
")",
":",
"# Parse the netmask/hostmask like an IP address.",
"try",
":",
"ip_int",
"=",
"cls",
".",
"_ip_int_from_string",
"(",
"ip_str",
")",
"except",
"AddressValueError",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"ip_str",
")",
"# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).",
"# Note that the two ambiguous cases (all-ones and all-zeroes) are",
"# treated as netmasks.",
"try",
":",
"return",
"cls",
".",
"_prefix_from_ip_int",
"(",
"ip_int",
")",
"except",
"ValueError",
":",
"pass",
"# Invert the bits, and try matching a /0+1+/ hostmask instead.",
"ip_int",
"^=",
"cls",
".",
"_ALL_ONES",
"try",
":",
"return",
"cls",
".",
"_prefix_from_ip_int",
"(",
"ip_int",
")",
"except",
"ValueError",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"ip_str",
")"
] |
Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask
|
[
"Turn",
"a",
"netmask",
"/",
"hostmask",
"string",
"into",
"a",
"prefix",
"length"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L625-L656
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseNetwork.overlaps
|
def overlaps(self, other):
"""Tell if self is partly contained in other."""
return self.network_address in other or (
self.broadcast_address in other or (
other.network_address in self or (
other.broadcast_address in self)))
|
python
|
def overlaps(self, other):
"""Tell if self is partly contained in other."""
return self.network_address in other or (
self.broadcast_address in other or (
other.network_address in self or (
other.broadcast_address in self)))
|
[
"def",
"overlaps",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"network_address",
"in",
"other",
"or",
"(",
"self",
".",
"broadcast_address",
"in",
"other",
"or",
"(",
"other",
".",
"network_address",
"in",
"self",
"or",
"(",
"other",
".",
"broadcast_address",
"in",
"self",
")",
")",
")"
] |
Tell if self is partly contained in other.
|
[
"Tell",
"if",
"self",
"is",
"partly",
"contained",
"in",
"other",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L810-L815
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseNetwork.address_exclude
|
def address_exclude(self, other):
"""Remove an address from a larger block.
For example:
addr1 = ip_network('192.0.2.0/28')
addr2 = ip_network('192.0.2.1/32')
list(addr1.address_exclude(addr2)) =
[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
or IPv6:
addr1 = ip_network('2001:db8::1/32')
addr2 = ip_network('2001:db8::1/128')
list(addr1.address_exclude(addr2)) =
[ip_network('2001:db8::1/128'),
ip_network('2001:db8::2/127'),
ip_network('2001:db8::4/126'),
ip_network('2001:db8::8/125'),
...
ip_network('2001:db8:8000::/33')]
Args:
other: An IPv4Network or IPv6Network object of the same type.
Returns:
An iterator of the IPv(4|6)Network objects which is self
minus other.
Raises:
TypeError: If self and other are of differing address
versions, or if other is not a network object.
ValueError: If other is not completely contained by self.
"""
if not self._version == other._version:
raise TypeError("%s and %s are not of the same version" % (
self, other))
if not isinstance(other, _BaseNetwork):
raise TypeError("%s is not a network object" % other)
if not other.subnet_of(self):
raise ValueError('%s not contained in %s' % (other, self))
if other == self:
return
# Make sure we're comparing the network of other.
other = other.__class__('%s/%s' % (other.network_address,
other.prefixlen))
s1, s2 = self.subnets()
while s1 != other and s2 != other:
if other.subnet_of(s1):
yield s2
s1, s2 = s1.subnets()
elif other.subnet_of(s2):
yield s1
s1, s2 = s2.subnets()
else:
# If we got here, there's a bug somewhere.
raise AssertionError('Error performing exclusion: '
's1: %s s2: %s other: %s' %
(s1, s2, other))
if s1 == other:
yield s2
elif s2 == other:
yield s1
else:
# If we got here, there's a bug somewhere.
raise AssertionError('Error performing exclusion: '
's1: %s s2: %s other: %s' %
(s1, s2, other))
|
python
|
def address_exclude(self, other):
"""Remove an address from a larger block.
For example:
addr1 = ip_network('192.0.2.0/28')
addr2 = ip_network('192.0.2.1/32')
list(addr1.address_exclude(addr2)) =
[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
or IPv6:
addr1 = ip_network('2001:db8::1/32')
addr2 = ip_network('2001:db8::1/128')
list(addr1.address_exclude(addr2)) =
[ip_network('2001:db8::1/128'),
ip_network('2001:db8::2/127'),
ip_network('2001:db8::4/126'),
ip_network('2001:db8::8/125'),
...
ip_network('2001:db8:8000::/33')]
Args:
other: An IPv4Network or IPv6Network object of the same type.
Returns:
An iterator of the IPv(4|6)Network objects which is self
minus other.
Raises:
TypeError: If self and other are of differing address
versions, or if other is not a network object.
ValueError: If other is not completely contained by self.
"""
if not self._version == other._version:
raise TypeError("%s and %s are not of the same version" % (
self, other))
if not isinstance(other, _BaseNetwork):
raise TypeError("%s is not a network object" % other)
if not other.subnet_of(self):
raise ValueError('%s not contained in %s' % (other, self))
if other == self:
return
# Make sure we're comparing the network of other.
other = other.__class__('%s/%s' % (other.network_address,
other.prefixlen))
s1, s2 = self.subnets()
while s1 != other and s2 != other:
if other.subnet_of(s1):
yield s2
s1, s2 = s1.subnets()
elif other.subnet_of(s2):
yield s1
s1, s2 = s2.subnets()
else:
# If we got here, there's a bug somewhere.
raise AssertionError('Error performing exclusion: '
's1: %s s2: %s other: %s' %
(s1, s2, other))
if s1 == other:
yield s2
elif s2 == other:
yield s1
else:
# If we got here, there's a bug somewhere.
raise AssertionError('Error performing exclusion: '
's1: %s s2: %s other: %s' %
(s1, s2, other))
|
[
"def",
"address_exclude",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"self",
".",
"_version",
"==",
"other",
".",
"_version",
":",
"raise",
"TypeError",
"(",
"\"%s and %s are not of the same version\"",
"%",
"(",
"self",
",",
"other",
")",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"_BaseNetwork",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not a network object\"",
"%",
"other",
")",
"if",
"not",
"other",
".",
"subnet_of",
"(",
"self",
")",
":",
"raise",
"ValueError",
"(",
"'%s not contained in %s'",
"%",
"(",
"other",
",",
"self",
")",
")",
"if",
"other",
"==",
"self",
":",
"return",
"# Make sure we're comparing the network of other.",
"other",
"=",
"other",
".",
"__class__",
"(",
"'%s/%s'",
"%",
"(",
"other",
".",
"network_address",
",",
"other",
".",
"prefixlen",
")",
")",
"s1",
",",
"s2",
"=",
"self",
".",
"subnets",
"(",
")",
"while",
"s1",
"!=",
"other",
"and",
"s2",
"!=",
"other",
":",
"if",
"other",
".",
"subnet_of",
"(",
"s1",
")",
":",
"yield",
"s2",
"s1",
",",
"s2",
"=",
"s1",
".",
"subnets",
"(",
")",
"elif",
"other",
".",
"subnet_of",
"(",
"s2",
")",
":",
"yield",
"s1",
"s1",
",",
"s2",
"=",
"s2",
".",
"subnets",
"(",
")",
"else",
":",
"# If we got here, there's a bug somewhere.",
"raise",
"AssertionError",
"(",
"'Error performing exclusion: '",
"'s1: %s s2: %s other: %s'",
"%",
"(",
"s1",
",",
"s2",
",",
"other",
")",
")",
"if",
"s1",
"==",
"other",
":",
"yield",
"s2",
"elif",
"s2",
"==",
"other",
":",
"yield",
"s1",
"else",
":",
"# If we got here, there's a bug somewhere.",
"raise",
"AssertionError",
"(",
"'Error performing exclusion: '",
"'s1: %s s2: %s other: %s'",
"%",
"(",
"s1",
",",
"s2",
",",
"other",
")",
")"
] |
Remove an address from a larger block.
For example:
addr1 = ip_network('192.0.2.0/28')
addr2 = ip_network('192.0.2.1/32')
list(addr1.address_exclude(addr2)) =
[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
or IPv6:
addr1 = ip_network('2001:db8::1/32')
addr2 = ip_network('2001:db8::1/128')
list(addr1.address_exclude(addr2)) =
[ip_network('2001:db8::1/128'),
ip_network('2001:db8::2/127'),
ip_network('2001:db8::4/126'),
ip_network('2001:db8::8/125'),
...
ip_network('2001:db8:8000::/33')]
Args:
other: An IPv4Network or IPv6Network object of the same type.
Returns:
An iterator of the IPv(4|6)Network objects which is self
minus other.
Raises:
TypeError: If self and other are of differing address
versions, or if other is not a network object.
ValueError: If other is not completely contained by self.
|
[
"Remove",
"an",
"address",
"from",
"a",
"larger",
"block",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L863-L936
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseNetwork.compare_networks
|
def compare_networks(self, other):
"""Compare two IP objects.
This is only concerned about the comparison of the integer
representation of the network addresses. This means that the
host bits aren't considered at all in this method. If you want
to compare host bits, you can easily enough do a
'HostA._ip < HostB._ip'
Args:
other: An IP object.
Returns:
If the IP versions of self and other are the same, returns:
-1 if self < other:
eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
IPv6Network('2001:db8::1000/124') <
IPv6Network('2001:db8::2000/124')
0 if self == other
eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
IPv6Network('2001:db8::1000/124') ==
IPv6Network('2001:db8::1000/124')
1 if self > other
eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
IPv6Network('2001:db8::2000/124') >
IPv6Network('2001:db8::1000/124')
Raises:
TypeError if the IP versions are different.
"""
# does this need to raise a ValueError?
if self._version != other._version:
raise TypeError('%s and %s are not of the same type' % (
self, other))
# self._version == other._version below here:
if self.network_address < other.network_address:
return -1
if self.network_address > other.network_address:
return 1
# self.network_address == other.network_address below here:
if self.netmask < other.netmask:
return -1
if self.netmask > other.netmask:
return 1
return 0
|
python
|
def compare_networks(self, other):
"""Compare two IP objects.
This is only concerned about the comparison of the integer
representation of the network addresses. This means that the
host bits aren't considered at all in this method. If you want
to compare host bits, you can easily enough do a
'HostA._ip < HostB._ip'
Args:
other: An IP object.
Returns:
If the IP versions of self and other are the same, returns:
-1 if self < other:
eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
IPv6Network('2001:db8::1000/124') <
IPv6Network('2001:db8::2000/124')
0 if self == other
eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
IPv6Network('2001:db8::1000/124') ==
IPv6Network('2001:db8::1000/124')
1 if self > other
eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
IPv6Network('2001:db8::2000/124') >
IPv6Network('2001:db8::1000/124')
Raises:
TypeError if the IP versions are different.
"""
# does this need to raise a ValueError?
if self._version != other._version:
raise TypeError('%s and %s are not of the same type' % (
self, other))
# self._version == other._version below here:
if self.network_address < other.network_address:
return -1
if self.network_address > other.network_address:
return 1
# self.network_address == other.network_address below here:
if self.netmask < other.netmask:
return -1
if self.netmask > other.netmask:
return 1
return 0
|
[
"def",
"compare_networks",
"(",
"self",
",",
"other",
")",
":",
"# does this need to raise a ValueError?",
"if",
"self",
".",
"_version",
"!=",
"other",
".",
"_version",
":",
"raise",
"TypeError",
"(",
"'%s and %s are not of the same type'",
"%",
"(",
"self",
",",
"other",
")",
")",
"# self._version == other._version below here:",
"if",
"self",
".",
"network_address",
"<",
"other",
".",
"network_address",
":",
"return",
"-",
"1",
"if",
"self",
".",
"network_address",
">",
"other",
".",
"network_address",
":",
"return",
"1",
"# self.network_address == other.network_address below here:",
"if",
"self",
".",
"netmask",
"<",
"other",
".",
"netmask",
":",
"return",
"-",
"1",
"if",
"self",
".",
"netmask",
">",
"other",
".",
"netmask",
":",
"return",
"1",
"return",
"0"
] |
Compare two IP objects.
This is only concerned about the comparison of the integer
representation of the network addresses. This means that the
host bits aren't considered at all in this method. If you want
to compare host bits, you can easily enough do a
'HostA._ip < HostB._ip'
Args:
other: An IP object.
Returns:
If the IP versions of self and other are the same, returns:
-1 if self < other:
eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
IPv6Network('2001:db8::1000/124') <
IPv6Network('2001:db8::2000/124')
0 if self == other
eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
IPv6Network('2001:db8::1000/124') ==
IPv6Network('2001:db8::1000/124')
1 if self > other
eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
IPv6Network('2001:db8::2000/124') >
IPv6Network('2001:db8::1000/124')
Raises:
TypeError if the IP versions are different.
|
[
"Compare",
"two",
"IP",
"objects",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L938-L984
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseNetwork.subnets
|
def subnets(self, prefixlen_diff=1, new_prefix=None):
"""The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)
"""
if self._prefixlen == self._max_prefixlen:
yield self
return
if new_prefix is not None:
if new_prefix < self._prefixlen:
raise ValueError('new prefix must be longer')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = new_prefix - self._prefixlen
if prefixlen_diff < 0:
raise ValueError('prefix length diff must be > 0')
new_prefixlen = self._prefixlen + prefixlen_diff
if new_prefixlen > self._max_prefixlen:
raise ValueError(
'prefix length diff %d is invalid for netblock %s' % (
new_prefixlen, self))
start = int(self.network_address)
end = int(self.broadcast_address) + 1
step = (int(self.hostmask) + 1) >> prefixlen_diff
for new_addr in _compat_range(start, end, step):
current = self.__class__((new_addr, new_prefixlen))
yield current
|
python
|
def subnets(self, prefixlen_diff=1, new_prefix=None):
"""The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)
"""
if self._prefixlen == self._max_prefixlen:
yield self
return
if new_prefix is not None:
if new_prefix < self._prefixlen:
raise ValueError('new prefix must be longer')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = new_prefix - self._prefixlen
if prefixlen_diff < 0:
raise ValueError('prefix length diff must be > 0')
new_prefixlen = self._prefixlen + prefixlen_diff
if new_prefixlen > self._max_prefixlen:
raise ValueError(
'prefix length diff %d is invalid for netblock %s' % (
new_prefixlen, self))
start = int(self.network_address)
end = int(self.broadcast_address) + 1
step = (int(self.hostmask) + 1) >> prefixlen_diff
for new_addr in _compat_range(start, end, step):
current = self.__class__((new_addr, new_prefixlen))
yield current
|
[
"def",
"subnets",
"(",
"self",
",",
"prefixlen_diff",
"=",
"1",
",",
"new_prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prefixlen",
"==",
"self",
".",
"_max_prefixlen",
":",
"yield",
"self",
"return",
"if",
"new_prefix",
"is",
"not",
"None",
":",
"if",
"new_prefix",
"<",
"self",
".",
"_prefixlen",
":",
"raise",
"ValueError",
"(",
"'new prefix must be longer'",
")",
"if",
"prefixlen_diff",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'cannot set prefixlen_diff and new_prefix'",
")",
"prefixlen_diff",
"=",
"new_prefix",
"-",
"self",
".",
"_prefixlen",
"if",
"prefixlen_diff",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'prefix length diff must be > 0'",
")",
"new_prefixlen",
"=",
"self",
".",
"_prefixlen",
"+",
"prefixlen_diff",
"if",
"new_prefixlen",
">",
"self",
".",
"_max_prefixlen",
":",
"raise",
"ValueError",
"(",
"'prefix length diff %d is invalid for netblock %s'",
"%",
"(",
"new_prefixlen",
",",
"self",
")",
")",
"start",
"=",
"int",
"(",
"self",
".",
"network_address",
")",
"end",
"=",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"+",
"1",
"step",
"=",
"(",
"int",
"(",
"self",
".",
"hostmask",
")",
"+",
"1",
")",
">>",
"prefixlen_diff",
"for",
"new_addr",
"in",
"_compat_range",
"(",
"start",
",",
"end",
",",
"step",
")",
":",
"current",
"=",
"self",
".",
"__class__",
"(",
"(",
"new_addr",
",",
"new_prefixlen",
")",
")",
"yield",
"current"
] |
The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)
|
[
"The",
"subnets",
"which",
"join",
"to",
"make",
"the",
"current",
"subnet",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L996-L1047
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseNetwork.supernet
|
def supernet(self, prefixlen_diff=1, new_prefix=None):
"""The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)
"""
if self._prefixlen == 0:
return self
if new_prefix is not None:
if new_prefix > self._prefixlen:
raise ValueError('new prefix must be shorter')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = self._prefixlen - new_prefix
new_prefixlen = self.prefixlen - prefixlen_diff
if new_prefixlen < 0:
raise ValueError(
'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
(self.prefixlen, prefixlen_diff))
return self.__class__((
int(self.network_address) & (int(self.netmask) << prefixlen_diff),
new_prefixlen))
|
python
|
def supernet(self, prefixlen_diff=1, new_prefix=None):
"""The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)
"""
if self._prefixlen == 0:
return self
if new_prefix is not None:
if new_prefix > self._prefixlen:
raise ValueError('new prefix must be shorter')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = self._prefixlen - new_prefix
new_prefixlen = self.prefixlen - prefixlen_diff
if new_prefixlen < 0:
raise ValueError(
'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
(self.prefixlen, prefixlen_diff))
return self.__class__((
int(self.network_address) & (int(self.netmask) << prefixlen_diff),
new_prefixlen))
|
[
"def",
"supernet",
"(",
"self",
",",
"prefixlen_diff",
"=",
"1",
",",
"new_prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prefixlen",
"==",
"0",
":",
"return",
"self",
"if",
"new_prefix",
"is",
"not",
"None",
":",
"if",
"new_prefix",
">",
"self",
".",
"_prefixlen",
":",
"raise",
"ValueError",
"(",
"'new prefix must be shorter'",
")",
"if",
"prefixlen_diff",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'cannot set prefixlen_diff and new_prefix'",
")",
"prefixlen_diff",
"=",
"self",
".",
"_prefixlen",
"-",
"new_prefix",
"new_prefixlen",
"=",
"self",
".",
"prefixlen",
"-",
"prefixlen_diff",
"if",
"new_prefixlen",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'current prefixlen is %d, cannot have a prefixlen_diff of %d'",
"%",
"(",
"self",
".",
"prefixlen",
",",
"prefixlen_diff",
")",
")",
"return",
"self",
".",
"__class__",
"(",
"(",
"int",
"(",
"self",
".",
"network_address",
")",
"&",
"(",
"int",
"(",
"self",
".",
"netmask",
")",
"<<",
"prefixlen_diff",
")",
",",
"new_prefixlen",
")",
")"
] |
The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)
|
[
"The",
"supernet",
"containing",
"the",
"current",
"network",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1049-L1087
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV4._make_netmask
|
def _make_netmask(cls, arg):
"""Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
"""
if arg not in cls._netmask_cache:
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
try:
# Check for a netmask in prefix length form
prefixlen = cls._prefix_from_prefix_string(arg)
except NetmaskValueError:
# Check for a netmask or hostmask in dotted-quad form.
# This may raise NetmaskValueError.
prefixlen = cls._prefix_from_ip_string(arg)
netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = netmask, prefixlen
return cls._netmask_cache[arg]
|
python
|
def _make_netmask(cls, arg):
"""Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
"""
if arg not in cls._netmask_cache:
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
try:
# Check for a netmask in prefix length form
prefixlen = cls._prefix_from_prefix_string(arg)
except NetmaskValueError:
# Check for a netmask or hostmask in dotted-quad form.
# This may raise NetmaskValueError.
prefixlen = cls._prefix_from_ip_string(arg)
netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = netmask, prefixlen
return cls._netmask_cache[arg]
|
[
"def",
"_make_netmask",
"(",
"cls",
",",
"arg",
")",
":",
"if",
"arg",
"not",
"in",
"cls",
".",
"_netmask_cache",
":",
"if",
"isinstance",
"(",
"arg",
",",
"_compat_int_types",
")",
":",
"prefixlen",
"=",
"arg",
"else",
":",
"try",
":",
"# Check for a netmask in prefix length form",
"prefixlen",
"=",
"cls",
".",
"_prefix_from_prefix_string",
"(",
"arg",
")",
"except",
"NetmaskValueError",
":",
"# Check for a netmask or hostmask in dotted-quad form.",
"# This may raise NetmaskValueError.",
"prefixlen",
"=",
"cls",
".",
"_prefix_from_ip_string",
"(",
"arg",
")",
"netmask",
"=",
"IPv4Address",
"(",
"cls",
".",
"_ip_int_from_prefix",
"(",
"prefixlen",
")",
")",
"cls",
".",
"_netmask_cache",
"[",
"arg",
"]",
"=",
"netmask",
",",
"prefixlen",
"return",
"cls",
".",
"_netmask_cache",
"[",
"arg",
"]"
] |
Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
|
[
"Make",
"a",
"(",
"netmask",
"prefix_len",
")",
"tuple",
"from",
"the",
"given",
"argument",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1219-L1240
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV4._ip_int_from_string
|
def _ip_int_from_string(cls, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _compat_int_from_byte_vals(
map(cls._parse_octet, octets), 'big')
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
|
python
|
def _ip_int_from_string(cls, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _compat_int_from_byte_vals(
map(cls._parse_octet, octets), 'big')
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
|
[
"def",
"_ip_int_from_string",
"(",
"cls",
",",
"ip_str",
")",
":",
"if",
"not",
"ip_str",
":",
"raise",
"AddressValueError",
"(",
"'Address cannot be empty'",
")",
"octets",
"=",
"ip_str",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"octets",
")",
"!=",
"4",
":",
"raise",
"AddressValueError",
"(",
"\"Expected 4 octets in %r\"",
"%",
"ip_str",
")",
"try",
":",
"return",
"_compat_int_from_byte_vals",
"(",
"map",
"(",
"cls",
".",
"_parse_octet",
",",
"octets",
")",
",",
"'big'",
")",
"except",
"ValueError",
"as",
"exc",
":",
"raise",
"AddressValueError",
"(",
"\"%s in %r\"",
"%",
"(",
"exc",
",",
"ip_str",
")",
")"
] |
Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
|
[
"Turn",
"the",
"given",
"IP",
"string",
"into",
"an",
"integer",
"for",
"comparison",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1243-L1267
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV4._string_from_ip_int
|
def _string_from_ip_int(cls, ip_int):
"""Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.
"""
return '.'.join(_compat_str(struct.unpack(b'!B', b)[0]
if isinstance(b, bytes)
else b)
for b in _compat_to_bytes(ip_int, 4, 'big'))
|
python
|
def _string_from_ip_int(cls, ip_int):
"""Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.
"""
return '.'.join(_compat_str(struct.unpack(b'!B', b)[0]
if isinstance(b, bytes)
else b)
for b in _compat_to_bytes(ip_int, 4, 'big'))
|
[
"def",
"_string_from_ip_int",
"(",
"cls",
",",
"ip_int",
")",
":",
"return",
"'.'",
".",
"join",
"(",
"_compat_str",
"(",
"struct",
".",
"unpack",
"(",
"b'!B'",
",",
"b",
")",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"b",
",",
"bytes",
")",
"else",
"b",
")",
"for",
"b",
"in",
"_compat_to_bytes",
"(",
"ip_int",
",",
"4",
",",
"'big'",
")",
")"
] |
Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.
|
[
"Turns",
"a",
"32",
"-",
"bit",
"integer",
"into",
"dotted",
"decimal",
"notation",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1307-L1320
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV4._is_hostmask
|
def _is_hostmask(self, ip_str):
"""Test if the IP string is a hostmask (rather than a netmask).
Args:
ip_str: A string, the potential hostmask.
Returns:
A boolean, True if the IP string is a hostmask.
"""
bits = ip_str.split('.')
try:
parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
except ValueError:
return False
if len(parts) != len(bits):
return False
if parts[0] < parts[-1]:
return True
return False
|
python
|
def _is_hostmask(self, ip_str):
"""Test if the IP string is a hostmask (rather than a netmask).
Args:
ip_str: A string, the potential hostmask.
Returns:
A boolean, True if the IP string is a hostmask.
"""
bits = ip_str.split('.')
try:
parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
except ValueError:
return False
if len(parts) != len(bits):
return False
if parts[0] < parts[-1]:
return True
return False
|
[
"def",
"_is_hostmask",
"(",
"self",
",",
"ip_str",
")",
":",
"bits",
"=",
"ip_str",
".",
"split",
"(",
"'.'",
")",
"try",
":",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"map",
"(",
"int",
",",
"bits",
")",
"if",
"x",
"in",
"self",
".",
"_valid_mask_octets",
"]",
"except",
"ValueError",
":",
"return",
"False",
"if",
"len",
"(",
"parts",
")",
"!=",
"len",
"(",
"bits",
")",
":",
"return",
"False",
"if",
"parts",
"[",
"0",
"]",
"<",
"parts",
"[",
"-",
"1",
"]",
":",
"return",
"True",
"return",
"False"
] |
Test if the IP string is a hostmask (rather than a netmask).
Args:
ip_str: A string, the potential hostmask.
Returns:
A boolean, True if the IP string is a hostmask.
|
[
"Test",
"if",
"the",
"IP",
"string",
"is",
"a",
"hostmask",
"(",
"rather",
"than",
"a",
"netmask",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1322-L1341
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
IPv4Network.is_global
|
def is_global(self):
"""Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.
"""
return (not (self.network_address in IPv4Network('100.64.0.0/10') and
self.broadcast_address in IPv4Network('100.64.0.0/10')) and
not self.is_private)
|
python
|
def is_global(self):
"""Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.
"""
return (not (self.network_address in IPv4Network('100.64.0.0/10') and
self.broadcast_address in IPv4Network('100.64.0.0/10')) and
not self.is_private)
|
[
"def",
"is_global",
"(",
"self",
")",
":",
"return",
"(",
"not",
"(",
"self",
".",
"network_address",
"in",
"IPv4Network",
"(",
"'100.64.0.0/10'",
")",
"and",
"self",
".",
"broadcast_address",
"in",
"IPv4Network",
"(",
"'100.64.0.0/10'",
")",
")",
"and",
"not",
"self",
".",
"is_private",
")"
] |
Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry.
|
[
"Test",
"if",
"this",
"address",
"is",
"allocated",
"for",
"public",
"networks",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1663-L1673
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV6._make_netmask
|
def _make_netmask(cls, arg):
"""Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
"""
if arg not in cls._netmask_cache:
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
prefixlen = cls._prefix_from_prefix_string(arg)
netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = netmask, prefixlen
return cls._netmask_cache[arg]
|
python
|
def _make_netmask(cls, arg):
"""Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
"""
if arg not in cls._netmask_cache:
if isinstance(arg, _compat_int_types):
prefixlen = arg
else:
prefixlen = cls._prefix_from_prefix_string(arg)
netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = netmask, prefixlen
return cls._netmask_cache[arg]
|
[
"def",
"_make_netmask",
"(",
"cls",
",",
"arg",
")",
":",
"if",
"arg",
"not",
"in",
"cls",
".",
"_netmask_cache",
":",
"if",
"isinstance",
"(",
"arg",
",",
"_compat_int_types",
")",
":",
"prefixlen",
"=",
"arg",
"else",
":",
"prefixlen",
"=",
"cls",
".",
"_prefix_from_prefix_string",
"(",
"arg",
")",
"netmask",
"=",
"IPv6Address",
"(",
"cls",
".",
"_ip_int_from_prefix",
"(",
"prefixlen",
")",
")",
"cls",
".",
"_netmask_cache",
"[",
"arg",
"]",
"=",
"netmask",
",",
"prefixlen",
"return",
"cls",
".",
"_netmask_cache",
"[",
"arg",
"]"
] |
Make a (netmask, prefix_len) tuple from the given argument.
Argument can be:
- an integer (the prefix length)
- a string representing the prefix length (e.g. "24")
- a string representing the prefix netmask (e.g. "255.255.255.0")
|
[
"Make",
"a",
"(",
"netmask",
"prefix_len",
")",
"tuple",
"from",
"the",
"given",
"argument",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1732-L1747
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV6._ip_int_from_string
|
def _ip_int_from_string(cls, ip_str):
"""Turn an IPv6 ip_str into an integer.
Args:
ip_str: A string, the IPv6 ip_str.
Returns:
An int, the IPv6 address
Raises:
AddressValueError: if ip_str isn't a valid IPv6 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
parts = ip_str.split(':')
# An IPv6 address needs at least 2 colons (3 parts).
_min_parts = 3
if len(parts) < _min_parts:
msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
raise AddressValueError(msg)
# If the address has an IPv4-style suffix, convert it to hexadecimal.
if '.' in parts[-1]:
try:
ipv4_int = IPv4Address(parts.pop())._ip
except AddressValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
parts.append('%x' % (ipv4_int & 0xFFFF))
# An IPv6 address can't have more than 8 colons (9 parts).
# The extra colon comes from using the "::" notation for a single
# leading or trailing zero part.
_max_parts = cls._HEXTET_COUNT + 1
if len(parts) > _max_parts:
msg = "At most %d colons permitted in %r" % (
_max_parts - 1, ip_str)
raise AddressValueError(msg)
# Disregarding the endpoints, find '::' with nothing in between.
# This indicates that a run of zeroes has been skipped.
skip_index = None
for i in _compat_range(1, len(parts) - 1):
if not parts[i]:
if skip_index is not None:
# Can't have more than one '::'
msg = "At most one '::' permitted in %r" % ip_str
raise AddressValueError(msg)
skip_index = i
# parts_hi is the number of parts to copy from above/before the '::'
# parts_lo is the number of parts to copy from below/after the '::'
if skip_index is not None:
# If we found a '::', then check if it also covers the endpoints.
parts_hi = skip_index
parts_lo = len(parts) - skip_index - 1
if not parts[0]:
parts_hi -= 1
if parts_hi:
msg = "Leading ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # ^: requires ^::
if not parts[-1]:
parts_lo -= 1
if parts_lo:
msg = "Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # :$ requires ::$
parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
if parts_skipped < 1:
msg = "Expected at most %d other parts with '::' in %r"
raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str))
else:
# Otherwise, allocate the entire address to parts_hi. The
# endpoints could still be empty, but _parse_hextet() will check
# for that.
if len(parts) != cls._HEXTET_COUNT:
msg = "Exactly %d parts expected without '::' in %r"
raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
if not parts[0]:
msg = "Leading ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # ^: requires ^::
if not parts[-1]:
msg = "Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # :$ requires ::$
parts_hi = len(parts)
parts_lo = 0
parts_skipped = 0
try:
# Now, parse the hextets into a 128-bit integer.
ip_int = 0
for i in range(parts_hi):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
ip_int <<= 16 * parts_skipped
for i in range(-parts_lo, 0):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
return ip_int
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
|
python
|
def _ip_int_from_string(cls, ip_str):
"""Turn an IPv6 ip_str into an integer.
Args:
ip_str: A string, the IPv6 ip_str.
Returns:
An int, the IPv6 address
Raises:
AddressValueError: if ip_str isn't a valid IPv6 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
parts = ip_str.split(':')
# An IPv6 address needs at least 2 colons (3 parts).
_min_parts = 3
if len(parts) < _min_parts:
msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
raise AddressValueError(msg)
# If the address has an IPv4-style suffix, convert it to hexadecimal.
if '.' in parts[-1]:
try:
ipv4_int = IPv4Address(parts.pop())._ip
except AddressValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
parts.append('%x' % (ipv4_int & 0xFFFF))
# An IPv6 address can't have more than 8 colons (9 parts).
# The extra colon comes from using the "::" notation for a single
# leading or trailing zero part.
_max_parts = cls._HEXTET_COUNT + 1
if len(parts) > _max_parts:
msg = "At most %d colons permitted in %r" % (
_max_parts - 1, ip_str)
raise AddressValueError(msg)
# Disregarding the endpoints, find '::' with nothing in between.
# This indicates that a run of zeroes has been skipped.
skip_index = None
for i in _compat_range(1, len(parts) - 1):
if not parts[i]:
if skip_index is not None:
# Can't have more than one '::'
msg = "At most one '::' permitted in %r" % ip_str
raise AddressValueError(msg)
skip_index = i
# parts_hi is the number of parts to copy from above/before the '::'
# parts_lo is the number of parts to copy from below/after the '::'
if skip_index is not None:
# If we found a '::', then check if it also covers the endpoints.
parts_hi = skip_index
parts_lo = len(parts) - skip_index - 1
if not parts[0]:
parts_hi -= 1
if parts_hi:
msg = "Leading ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # ^: requires ^::
if not parts[-1]:
parts_lo -= 1
if parts_lo:
msg = "Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # :$ requires ::$
parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
if parts_skipped < 1:
msg = "Expected at most %d other parts with '::' in %r"
raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str))
else:
# Otherwise, allocate the entire address to parts_hi. The
# endpoints could still be empty, but _parse_hextet() will check
# for that.
if len(parts) != cls._HEXTET_COUNT:
msg = "Exactly %d parts expected without '::' in %r"
raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
if not parts[0]:
msg = "Leading ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # ^: requires ^::
if not parts[-1]:
msg = "Trailing ':' only permitted as part of '::' in %r"
raise AddressValueError(msg % ip_str) # :$ requires ::$
parts_hi = len(parts)
parts_lo = 0
parts_skipped = 0
try:
# Now, parse the hextets into a 128-bit integer.
ip_int = 0
for i in range(parts_hi):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
ip_int <<= 16 * parts_skipped
for i in range(-parts_lo, 0):
ip_int <<= 16
ip_int |= cls._parse_hextet(parts[i])
return ip_int
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str))
|
[
"def",
"_ip_int_from_string",
"(",
"cls",
",",
"ip_str",
")",
":",
"if",
"not",
"ip_str",
":",
"raise",
"AddressValueError",
"(",
"'Address cannot be empty'",
")",
"parts",
"=",
"ip_str",
".",
"split",
"(",
"':'",
")",
"# An IPv6 address needs at least 2 colons (3 parts).",
"_min_parts",
"=",
"3",
"if",
"len",
"(",
"parts",
")",
"<",
"_min_parts",
":",
"msg",
"=",
"\"At least %d parts expected in %r\"",
"%",
"(",
"_min_parts",
",",
"ip_str",
")",
"raise",
"AddressValueError",
"(",
"msg",
")",
"# If the address has an IPv4-style suffix, convert it to hexadecimal.",
"if",
"'.'",
"in",
"parts",
"[",
"-",
"1",
"]",
":",
"try",
":",
"ipv4_int",
"=",
"IPv4Address",
"(",
"parts",
".",
"pop",
"(",
")",
")",
".",
"_ip",
"except",
"AddressValueError",
"as",
"exc",
":",
"raise",
"AddressValueError",
"(",
"\"%s in %r\"",
"%",
"(",
"exc",
",",
"ip_str",
")",
")",
"parts",
".",
"append",
"(",
"'%x'",
"%",
"(",
"(",
"ipv4_int",
">>",
"16",
")",
"&",
"0xFFFF",
")",
")",
"parts",
".",
"append",
"(",
"'%x'",
"%",
"(",
"ipv4_int",
"&",
"0xFFFF",
")",
")",
"# An IPv6 address can't have more than 8 colons (9 parts).",
"# The extra colon comes from using the \"::\" notation for a single",
"# leading or trailing zero part.",
"_max_parts",
"=",
"cls",
".",
"_HEXTET_COUNT",
"+",
"1",
"if",
"len",
"(",
"parts",
")",
">",
"_max_parts",
":",
"msg",
"=",
"\"At most %d colons permitted in %r\"",
"%",
"(",
"_max_parts",
"-",
"1",
",",
"ip_str",
")",
"raise",
"AddressValueError",
"(",
"msg",
")",
"# Disregarding the endpoints, find '::' with nothing in between.",
"# This indicates that a run of zeroes has been skipped.",
"skip_index",
"=",
"None",
"for",
"i",
"in",
"_compat_range",
"(",
"1",
",",
"len",
"(",
"parts",
")",
"-",
"1",
")",
":",
"if",
"not",
"parts",
"[",
"i",
"]",
":",
"if",
"skip_index",
"is",
"not",
"None",
":",
"# Can't have more than one '::'",
"msg",
"=",
"\"At most one '::' permitted in %r\"",
"%",
"ip_str",
"raise",
"AddressValueError",
"(",
"msg",
")",
"skip_index",
"=",
"i",
"# parts_hi is the number of parts to copy from above/before the '::'",
"# parts_lo is the number of parts to copy from below/after the '::'",
"if",
"skip_index",
"is",
"not",
"None",
":",
"# If we found a '::', then check if it also covers the endpoints.",
"parts_hi",
"=",
"skip_index",
"parts_lo",
"=",
"len",
"(",
"parts",
")",
"-",
"skip_index",
"-",
"1",
"if",
"not",
"parts",
"[",
"0",
"]",
":",
"parts_hi",
"-=",
"1",
"if",
"parts_hi",
":",
"msg",
"=",
"\"Leading ':' only permitted as part of '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"ip_str",
")",
"# ^: requires ^::",
"if",
"not",
"parts",
"[",
"-",
"1",
"]",
":",
"parts_lo",
"-=",
"1",
"if",
"parts_lo",
":",
"msg",
"=",
"\"Trailing ':' only permitted as part of '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"ip_str",
")",
"# :$ requires ::$",
"parts_skipped",
"=",
"cls",
".",
"_HEXTET_COUNT",
"-",
"(",
"parts_hi",
"+",
"parts_lo",
")",
"if",
"parts_skipped",
"<",
"1",
":",
"msg",
"=",
"\"Expected at most %d other parts with '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"(",
"cls",
".",
"_HEXTET_COUNT",
"-",
"1",
",",
"ip_str",
")",
")",
"else",
":",
"# Otherwise, allocate the entire address to parts_hi. The",
"# endpoints could still be empty, but _parse_hextet() will check",
"# for that.",
"if",
"len",
"(",
"parts",
")",
"!=",
"cls",
".",
"_HEXTET_COUNT",
":",
"msg",
"=",
"\"Exactly %d parts expected without '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"(",
"cls",
".",
"_HEXTET_COUNT",
",",
"ip_str",
")",
")",
"if",
"not",
"parts",
"[",
"0",
"]",
":",
"msg",
"=",
"\"Leading ':' only permitted as part of '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"ip_str",
")",
"# ^: requires ^::",
"if",
"not",
"parts",
"[",
"-",
"1",
"]",
":",
"msg",
"=",
"\"Trailing ':' only permitted as part of '::' in %r\"",
"raise",
"AddressValueError",
"(",
"msg",
"%",
"ip_str",
")",
"# :$ requires ::$",
"parts_hi",
"=",
"len",
"(",
"parts",
")",
"parts_lo",
"=",
"0",
"parts_skipped",
"=",
"0",
"try",
":",
"# Now, parse the hextets into a 128-bit integer.",
"ip_int",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"parts_hi",
")",
":",
"ip_int",
"<<=",
"16",
"ip_int",
"|=",
"cls",
".",
"_parse_hextet",
"(",
"parts",
"[",
"i",
"]",
")",
"ip_int",
"<<=",
"16",
"*",
"parts_skipped",
"for",
"i",
"in",
"range",
"(",
"-",
"parts_lo",
",",
"0",
")",
":",
"ip_int",
"<<=",
"16",
"ip_int",
"|=",
"cls",
".",
"_parse_hextet",
"(",
"parts",
"[",
"i",
"]",
")",
"return",
"ip_int",
"except",
"ValueError",
"as",
"exc",
":",
"raise",
"AddressValueError",
"(",
"\"%s in %r\"",
"%",
"(",
"exc",
",",
"ip_str",
")",
")"
] |
Turn an IPv6 ip_str into an integer.
Args:
ip_str: A string, the IPv6 ip_str.
Returns:
An int, the IPv6 address
Raises:
AddressValueError: if ip_str isn't a valid IPv6 Address.
|
[
"Turn",
"an",
"IPv6",
"ip_str",
"into",
"an",
"integer",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1750-L1852
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV6._parse_hextet
|
def _parse_hextet(cls, hextet_str):
"""Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from
[0..FFFF].
"""
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not cls._HEX_DIGITS.issuperset(hextet_str):
raise ValueError("Only hex digits permitted in %r" % hextet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(hextet_str) > 4:
msg = "At most 4 characters permitted in %r"
raise ValueError(msg % hextet_str)
# Length check means we can skip checking the integer value
return int(hextet_str, 16)
|
python
|
def _parse_hextet(cls, hextet_str):
"""Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from
[0..FFFF].
"""
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not cls._HEX_DIGITS.issuperset(hextet_str):
raise ValueError("Only hex digits permitted in %r" % hextet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(hextet_str) > 4:
msg = "At most 4 characters permitted in %r"
raise ValueError(msg % hextet_str)
# Length check means we can skip checking the integer value
return int(hextet_str, 16)
|
[
"def",
"_parse_hextet",
"(",
"cls",
",",
"hextet_str",
")",
":",
"# Whitelist the characters, since int() allows a lot of bizarre stuff.",
"if",
"not",
"cls",
".",
"_HEX_DIGITS",
".",
"issuperset",
"(",
"hextet_str",
")",
":",
"raise",
"ValueError",
"(",
"\"Only hex digits permitted in %r\"",
"%",
"hextet_str",
")",
"# We do the length check second, since the invalid character error",
"# is likely to be more informative for the user",
"if",
"len",
"(",
"hextet_str",
")",
">",
"4",
":",
"msg",
"=",
"\"At most 4 characters permitted in %r\"",
"raise",
"ValueError",
"(",
"msg",
"%",
"hextet_str",
")",
"# Length check means we can skip checking the integer value",
"return",
"int",
"(",
"hextet_str",
",",
"16",
")"
] |
Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from
[0..FFFF].
|
[
"Convert",
"an",
"IPv6",
"hextet",
"string",
"into",
"an",
"integer",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1855-L1878
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
_BaseV6._compress_hextets
|
def _compress_hextets(cls, hextets):
"""Compresses a list of hextets.
Compresses a list of strings, replacing the longest continuous
sequence of "0" in the list with "" and adding empty strings at
the beginning or at the end of the string such that subsequently
calling ":".join(hextets) will produce the compressed version of
the IPv6 address.
Args:
hextets: A list of strings, the hextets to compress.
Returns:
A list of strings.
"""
best_doublecolon_start = -1
best_doublecolon_len = 0
doublecolon_start = -1
doublecolon_len = 0
for index, hextet in enumerate(hextets):
if hextet == '0':
doublecolon_len += 1
if doublecolon_start == -1:
# Start of a sequence of zeros.
doublecolon_start = index
if doublecolon_len > best_doublecolon_len:
# This is the longest sequence of zeros so far.
best_doublecolon_len = doublecolon_len
best_doublecolon_start = doublecolon_start
else:
doublecolon_len = 0
doublecolon_start = -1
if best_doublecolon_len > 1:
best_doublecolon_end = (best_doublecolon_start +
best_doublecolon_len)
# For zeros at the end of the address.
if best_doublecolon_end == len(hextets):
hextets += ['']
hextets[best_doublecolon_start:best_doublecolon_end] = ['']
# For zeros at the beginning of the address.
if best_doublecolon_start == 0:
hextets = [''] + hextets
return hextets
|
python
|
def _compress_hextets(cls, hextets):
"""Compresses a list of hextets.
Compresses a list of strings, replacing the longest continuous
sequence of "0" in the list with "" and adding empty strings at
the beginning or at the end of the string such that subsequently
calling ":".join(hextets) will produce the compressed version of
the IPv6 address.
Args:
hextets: A list of strings, the hextets to compress.
Returns:
A list of strings.
"""
best_doublecolon_start = -1
best_doublecolon_len = 0
doublecolon_start = -1
doublecolon_len = 0
for index, hextet in enumerate(hextets):
if hextet == '0':
doublecolon_len += 1
if doublecolon_start == -1:
# Start of a sequence of zeros.
doublecolon_start = index
if doublecolon_len > best_doublecolon_len:
# This is the longest sequence of zeros so far.
best_doublecolon_len = doublecolon_len
best_doublecolon_start = doublecolon_start
else:
doublecolon_len = 0
doublecolon_start = -1
if best_doublecolon_len > 1:
best_doublecolon_end = (best_doublecolon_start +
best_doublecolon_len)
# For zeros at the end of the address.
if best_doublecolon_end == len(hextets):
hextets += ['']
hextets[best_doublecolon_start:best_doublecolon_end] = ['']
# For zeros at the beginning of the address.
if best_doublecolon_start == 0:
hextets = [''] + hextets
return hextets
|
[
"def",
"_compress_hextets",
"(",
"cls",
",",
"hextets",
")",
":",
"best_doublecolon_start",
"=",
"-",
"1",
"best_doublecolon_len",
"=",
"0",
"doublecolon_start",
"=",
"-",
"1",
"doublecolon_len",
"=",
"0",
"for",
"index",
",",
"hextet",
"in",
"enumerate",
"(",
"hextets",
")",
":",
"if",
"hextet",
"==",
"'0'",
":",
"doublecolon_len",
"+=",
"1",
"if",
"doublecolon_start",
"==",
"-",
"1",
":",
"# Start of a sequence of zeros.",
"doublecolon_start",
"=",
"index",
"if",
"doublecolon_len",
">",
"best_doublecolon_len",
":",
"# This is the longest sequence of zeros so far.",
"best_doublecolon_len",
"=",
"doublecolon_len",
"best_doublecolon_start",
"=",
"doublecolon_start",
"else",
":",
"doublecolon_len",
"=",
"0",
"doublecolon_start",
"=",
"-",
"1",
"if",
"best_doublecolon_len",
">",
"1",
":",
"best_doublecolon_end",
"=",
"(",
"best_doublecolon_start",
"+",
"best_doublecolon_len",
")",
"# For zeros at the end of the address.",
"if",
"best_doublecolon_end",
"==",
"len",
"(",
"hextets",
")",
":",
"hextets",
"+=",
"[",
"''",
"]",
"hextets",
"[",
"best_doublecolon_start",
":",
"best_doublecolon_end",
"]",
"=",
"[",
"''",
"]",
"# For zeros at the beginning of the address.",
"if",
"best_doublecolon_start",
"==",
"0",
":",
"hextets",
"=",
"[",
"''",
"]",
"+",
"hextets",
"return",
"hextets"
] |
Compresses a list of hextets.
Compresses a list of strings, replacing the longest continuous
sequence of "0" in the list with "" and adding empty strings at
the beginning or at the end of the string such that subsequently
calling ":".join(hextets) will produce the compressed version of
the IPv6 address.
Args:
hextets: A list of strings, the hextets to compress.
Returns:
A list of strings.
|
[
"Compresses",
"a",
"list",
"of",
"hextets",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L1881-L1926
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/ipaddress.py
|
IPv6Address.teredo
|
def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
"""
if (self._ip >> 96) != 0x20010000:
return None
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF))
|
python
|
def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
"""
if (self._ip >> 96) != 0x20010000:
return None
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF))
|
[
"def",
"teredo",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ip",
">>",
"96",
")",
"!=",
"0x20010000",
":",
"return",
"None",
"return",
"(",
"IPv4Address",
"(",
"(",
"self",
".",
"_ip",
">>",
"64",
")",
"&",
"0xFFFFFFFF",
")",
",",
"IPv4Address",
"(",
"~",
"self",
".",
"_ip",
"&",
"0xFFFFFFFF",
")",
")"
] |
Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
|
[
"Tuple",
"of",
"embedded",
"teredo",
"IPs",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L2148-L2160
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/serializer.py
|
serialize
|
def serialize(input, tree="etree", encoding=None, **serializer_opts):
"""Serializes the input token stream using the specified treewalker
:arg input: the token stream to serialize
:arg tree: the treewalker to use
:arg encoding: the encoding to use
:arg serializer_opts: any options to pass to the
:py:class:`html5lib.serializer.HTMLSerializer` that gets created
:returns: the tree serialized as a string
Example:
>>> from html5lib.html5parser import parse
>>> from html5lib.serializer import serialize
>>> token_stream = parse('<html><body><p>Hi!</p></body></html>')
>>> serialize(token_stream, omit_optional_tags=False)
'<html><head></head><body><p>Hi!</p></body></html>'
"""
# XXX: Should we cache this?
walker = treewalkers.getTreeWalker(tree)
s = HTMLSerializer(**serializer_opts)
return s.render(walker(input), encoding)
|
python
|
def serialize(input, tree="etree", encoding=None, **serializer_opts):
"""Serializes the input token stream using the specified treewalker
:arg input: the token stream to serialize
:arg tree: the treewalker to use
:arg encoding: the encoding to use
:arg serializer_opts: any options to pass to the
:py:class:`html5lib.serializer.HTMLSerializer` that gets created
:returns: the tree serialized as a string
Example:
>>> from html5lib.html5parser import parse
>>> from html5lib.serializer import serialize
>>> token_stream = parse('<html><body><p>Hi!</p></body></html>')
>>> serialize(token_stream, omit_optional_tags=False)
'<html><head></head><body><p>Hi!</p></body></html>'
"""
# XXX: Should we cache this?
walker = treewalkers.getTreeWalker(tree)
s = HTMLSerializer(**serializer_opts)
return s.render(walker(input), encoding)
|
[
"def",
"serialize",
"(",
"input",
",",
"tree",
"=",
"\"etree\"",
",",
"encoding",
"=",
"None",
",",
"*",
"*",
"serializer_opts",
")",
":",
"# XXX: Should we cache this?",
"walker",
"=",
"treewalkers",
".",
"getTreeWalker",
"(",
"tree",
")",
"s",
"=",
"HTMLSerializer",
"(",
"*",
"*",
"serializer_opts",
")",
"return",
"s",
".",
"render",
"(",
"walker",
"(",
"input",
")",
",",
"encoding",
")"
] |
Serializes the input token stream using the specified treewalker
:arg input: the token stream to serialize
:arg tree: the treewalker to use
:arg encoding: the encoding to use
:arg serializer_opts: any options to pass to the
:py:class:`html5lib.serializer.HTMLSerializer` that gets created
:returns: the tree serialized as a string
Example:
>>> from html5lib.html5parser import parse
>>> from html5lib.serializer import serialize
>>> token_stream = parse('<html><body><p>Hi!</p></body></html>')
>>> serialize(token_stream, omit_optional_tags=False)
'<html><head></head><body><p>Hi!</p></body></html>'
|
[
"Serializes",
"the",
"input",
"token",
"stream",
"using",
"the",
"specified",
"treewalker"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/serializer.py#L75-L101
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_vendor/html5lib/serializer.py
|
HTMLSerializer.render
|
def render(self, treewalker, encoding=None):
"""Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTreeWalker
>>> from html5lib.serializer import HTMLSerializer
>>> token_stream = parse('<html><body>Hi!</body></html>')
>>> walker = getTreeWalker('etree')
>>> serializer = HTMLSerializer(omit_optional_tags=False)
>>> serializer.render(walker(token_stream))
'<html><head></head><body>Hi!</body></html>'
"""
if encoding:
return b"".join(list(self.serialize(treewalker, encoding)))
else:
return "".join(list(self.serialize(treewalker)))
|
python
|
def render(self, treewalker, encoding=None):
"""Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTreeWalker
>>> from html5lib.serializer import HTMLSerializer
>>> token_stream = parse('<html><body>Hi!</body></html>')
>>> walker = getTreeWalker('etree')
>>> serializer = HTMLSerializer(omit_optional_tags=False)
>>> serializer.render(walker(token_stream))
'<html><head></head><body>Hi!</body></html>'
"""
if encoding:
return b"".join(list(self.serialize(treewalker, encoding)))
else:
return "".join(list(self.serialize(treewalker)))
|
[
"def",
"render",
"(",
"self",
",",
"treewalker",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
":",
"return",
"b\"\"",
".",
"join",
"(",
"list",
"(",
"self",
".",
"serialize",
"(",
"treewalker",
",",
"encoding",
")",
")",
")",
"else",
":",
"return",
"\"\"",
".",
"join",
"(",
"list",
"(",
"self",
".",
"serialize",
"(",
"treewalker",
")",
")",
")"
] |
Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTreeWalker
>>> from html5lib.serializer import HTMLSerializer
>>> token_stream = parse('<html><body>Hi!</body></html>')
>>> walker = getTreeWalker('etree')
>>> serializer = HTMLSerializer(omit_optional_tags=False)
>>> serializer.render(walker(token_stream))
'<html><head></head><body>Hi!</body></html>'
|
[
"Serializes",
"the",
"stream",
"from",
"the",
"treewalker",
"into",
"a",
"string"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/serializer.py#L375-L398
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.get_current_branch
|
def get_current_branch(self, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
output = self.run_command(
args, extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
return None
|
python
|
def get_current_branch(self, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
output = self.run_command(
args, extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
return None
|
[
"def",
"get_current_branch",
"(",
"self",
",",
"location",
")",
":",
"# git-symbolic-ref exits with empty stdout if \"HEAD\" is a detached",
"# HEAD rather than a symbolic ref. In addition, the -q causes the",
"# command to exit with status code 1 instead of 128 in this case",
"# and to suppress the message to stderr.",
"args",
"=",
"[",
"'symbolic-ref'",
",",
"'-q'",
",",
"'HEAD'",
"]",
"output",
"=",
"self",
".",
"run_command",
"(",
"args",
",",
"extra_ok_returncodes",
"=",
"(",
"1",
",",
")",
",",
"show_stdout",
"=",
"False",
",",
"cwd",
"=",
"location",
",",
")",
"ref",
"=",
"output",
".",
"strip",
"(",
")",
"if",
"ref",
".",
"startswith",
"(",
"'refs/heads/'",
")",
":",
"return",
"ref",
"[",
"len",
"(",
"'refs/heads/'",
")",
":",
"]",
"return",
"None"
] |
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
|
[
"Return",
"the",
"current",
"branch",
"or",
"None",
"if",
"HEAD",
"isn",
"t",
"at",
"a",
"branch",
"(",
"e",
".",
"g",
".",
"detached",
"HEAD",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L82-L100
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.get_revision_sha
|
def get_revision_sha(self, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to pre-filter the list.
output = self.run_command(['show-ref', rev], cwd=dest,
show_stdout=False, on_returncode='ignore')
refs = {}
for line in output.strip().splitlines():
try:
sha, ref = line.split()
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.format(rev)
sha = refs.get(branch_ref)
if sha is not None:
return (sha, True)
sha = refs.get(tag_ref)
return (sha, False)
|
python
|
def get_revision_sha(self, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to pre-filter the list.
output = self.run_command(['show-ref', rev], cwd=dest,
show_stdout=False, on_returncode='ignore')
refs = {}
for line in output.strip().splitlines():
try:
sha, ref = line.split()
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.format(rev)
sha = refs.get(branch_ref)
if sha is not None:
return (sha, True)
sha = refs.get(tag_ref)
return (sha, False)
|
[
"def",
"get_revision_sha",
"(",
"self",
",",
"dest",
",",
"rev",
")",
":",
"# Pass rev to pre-filter the list.",
"output",
"=",
"self",
".",
"run_command",
"(",
"[",
"'show-ref'",
",",
"rev",
"]",
",",
"cwd",
"=",
"dest",
",",
"show_stdout",
"=",
"False",
",",
"on_returncode",
"=",
"'ignore'",
")",
"refs",
"=",
"{",
"}",
"for",
"line",
"in",
"output",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"try",
":",
"sha",
",",
"ref",
"=",
"line",
".",
"split",
"(",
")",
"except",
"ValueError",
":",
"# Include the offending line to simplify troubleshooting if",
"# this error ever occurs.",
"raise",
"ValueError",
"(",
"'unexpected show-ref line: {!r}'",
".",
"format",
"(",
"line",
")",
")",
"refs",
"[",
"ref",
"]",
"=",
"sha",
"branch_ref",
"=",
"'refs/remotes/origin/{}'",
".",
"format",
"(",
"rev",
")",
"tag_ref",
"=",
"'refs/tags/{}'",
".",
"format",
"(",
"rev",
")",
"sha",
"=",
"refs",
".",
"get",
"(",
"branch_ref",
")",
"if",
"sha",
"is",
"not",
"None",
":",
"return",
"(",
"sha",
",",
"True",
")",
"sha",
"=",
"refs",
".",
"get",
"(",
"tag_ref",
")",
"return",
"(",
"sha",
",",
"False",
")"
] |
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
|
[
"Return",
"(",
"sha_or_none",
"is_branch",
")",
"where",
"sha_or_none",
"is",
"a",
"commit",
"hash",
"if",
"the",
"revision",
"names",
"a",
"remote",
"branch",
"or",
"tag",
"otherwise",
"None",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L114-L146
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.resolve_revision
|
def resolve_revision(self, dest, url, rev_options):
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev = rev_options.arg_rev
sha, is_branch = self.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not rev.startswith('refs/'):
return rev_options
# If it looks like a ref, we have to fetch it explicitly.
self.run_command(
['fetch', '-q', url] + rev_options.to_args(),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = self.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options
|
python
|
def resolve_revision(self, dest, url, rev_options):
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev = rev_options.arg_rev
sha, is_branch = self.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not rev.startswith('refs/'):
return rev_options
# If it looks like a ref, we have to fetch it explicitly.
self.run_command(
['fetch', '-q', url] + rev_options.to_args(),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = self.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options
|
[
"def",
"resolve_revision",
"(",
"self",
",",
"dest",
",",
"url",
",",
"rev_options",
")",
":",
"rev",
"=",
"rev_options",
".",
"arg_rev",
"sha",
",",
"is_branch",
"=",
"self",
".",
"get_revision_sha",
"(",
"dest",
",",
"rev",
")",
"if",
"sha",
"is",
"not",
"None",
":",
"rev_options",
"=",
"rev_options",
".",
"make_new",
"(",
"sha",
")",
"rev_options",
".",
"branch_name",
"=",
"rev",
"if",
"is_branch",
"else",
"None",
"return",
"rev_options",
"# Do not show a warning for the common case of something that has",
"# the form of a Git commit hash.",
"if",
"not",
"looks_like_hash",
"(",
"rev",
")",
":",
"logger",
".",
"warning",
"(",
"\"Did not find branch or tag '%s', assuming revision or ref.\"",
",",
"rev",
",",
")",
"if",
"not",
"rev",
".",
"startswith",
"(",
"'refs/'",
")",
":",
"return",
"rev_options",
"# If it looks like a ref, we have to fetch it explicitly.",
"self",
".",
"run_command",
"(",
"[",
"'fetch'",
",",
"'-q'",
",",
"url",
"]",
"+",
"rev_options",
".",
"to_args",
"(",
")",
",",
"cwd",
"=",
"dest",
",",
")",
"# Change the revision to the SHA of the ref we fetched",
"sha",
"=",
"self",
".",
"get_revision",
"(",
"dest",
",",
"rev",
"=",
"'FETCH_HEAD'",
")",
"rev_options",
"=",
"rev_options",
".",
"make_new",
"(",
"sha",
")",
"return",
"rev_options"
] |
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
|
[
"Resolve",
"a",
"revision",
"to",
"a",
"new",
"RevOptions",
"object",
"with",
"the",
"SHA1",
"of",
"the",
"branch",
"tag",
"or",
"ref",
"if",
"found",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L148-L185
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.is_commit_id_equal
|
def is_commit_id_equal(self, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return False
return self.get_revision(dest) == name
|
python
|
def is_commit_id_equal(self, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return False
return self.get_revision(dest) == name
|
[
"def",
"is_commit_id_equal",
"(",
"self",
",",
"dest",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"# Then avoid an unnecessary subprocess call.",
"return",
"False",
"return",
"self",
".",
"get_revision",
"(",
"dest",
")",
"==",
"name"
] |
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
|
[
"Return",
"whether",
"the",
"current",
"commit",
"hash",
"equals",
"the",
"given",
"name",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L187-L199
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.get_remote_url
|
def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip()
|
python
|
def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip()
|
[
"def",
"get_remote_url",
"(",
"cls",
",",
"location",
")",
":",
"# We need to pass 1 for extra_ok_returncodes since the command",
"# exits with return code 1 if there are no matching lines.",
"stdout",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'config'",
",",
"'--get-regexp'",
",",
"r'remote\\..*\\.url'",
"]",
",",
"extra_ok_returncodes",
"=",
"(",
"1",
",",
")",
",",
"show_stdout",
"=",
"False",
",",
"cwd",
"=",
"location",
",",
")",
"remotes",
"=",
"stdout",
".",
"splitlines",
"(",
")",
"try",
":",
"found_remote",
"=",
"remotes",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"RemoteNotFoundError",
"for",
"remote",
"in",
"remotes",
":",
"if",
"remote",
".",
"startswith",
"(",
"'remote.origin.url '",
")",
":",
"found_remote",
"=",
"remote",
"break",
"url",
"=",
"found_remote",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"return",
"url",
".",
"strip",
"(",
")"
] |
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
|
[
"Return",
"URL",
"of",
"the",
"first",
"remote",
"encountered",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L253-L277
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git._get_subdirectory
|
def _get_subdirectory(cls, location):
"""Return the relative path of setup.py to the git repo root."""
# find the repo root
git_dir = cls.run_command(['rev-parse', '--git-dir'],
show_stdout=False, cwd=location).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
root_dir = os.path.join(git_dir, '..')
# find setup.py
orig_location = location
while not os.path.exists(os.path.join(location, 'setup.py')):
last_location = location
location = os.path.dirname(location)
if location == last_location:
# We've traversed up to the root of the filesystem without
# finding setup.py
logger.warning(
"Could not find setup.py for directory %s (tried all "
"parent directories)",
orig_location,
)
return None
# relative path of setup.py to repo root
if samefile(root_dir, location):
return None
return os.path.relpath(location, root_dir)
|
python
|
def _get_subdirectory(cls, location):
"""Return the relative path of setup.py to the git repo root."""
# find the repo root
git_dir = cls.run_command(['rev-parse', '--git-dir'],
show_stdout=False, cwd=location).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
root_dir = os.path.join(git_dir, '..')
# find setup.py
orig_location = location
while not os.path.exists(os.path.join(location, 'setup.py')):
last_location = location
location = os.path.dirname(location)
if location == last_location:
# We've traversed up to the root of the filesystem without
# finding setup.py
logger.warning(
"Could not find setup.py for directory %s (tried all "
"parent directories)",
orig_location,
)
return None
# relative path of setup.py to repo root
if samefile(root_dir, location):
return None
return os.path.relpath(location, root_dir)
|
[
"def",
"_get_subdirectory",
"(",
"cls",
",",
"location",
")",
":",
"# find the repo root",
"git_dir",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'rev-parse'",
",",
"'--git-dir'",
"]",
",",
"show_stdout",
"=",
"False",
",",
"cwd",
"=",
"location",
")",
".",
"strip",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"git_dir",
")",
":",
"git_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"git_dir",
")",
"root_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"git_dir",
",",
"'..'",
")",
"# find setup.py",
"orig_location",
"=",
"location",
"while",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"'setup.py'",
")",
")",
":",
"last_location",
"=",
"location",
"location",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"location",
")",
"if",
"location",
"==",
"last_location",
":",
"# We've traversed up to the root of the filesystem without",
"# finding setup.py",
"logger",
".",
"warning",
"(",
"\"Could not find setup.py for directory %s (tried all \"",
"\"parent directories)\"",
",",
"orig_location",
",",
")",
"return",
"None",
"# relative path of setup.py to repo root",
"if",
"samefile",
"(",
"root_dir",
",",
"location",
")",
":",
"return",
"None",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"location",
",",
"root_dir",
")"
] |
Return the relative path of setup.py to the git repo root.
|
[
"Return",
"the",
"relative",
"path",
"of",
"setup",
".",
"py",
"to",
"the",
"git",
"repo",
"root",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L289-L314
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/vcs/git.py
|
Git.get_url_rev_and_auth
|
def get_url_rev_and_auth(self, url):
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
"""
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
return url, rev, user_pass
|
python
|
def get_url_rev_and_auth(self, url):
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
"""
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
return url, rev, user_pass
|
[
"def",
"get_url_rev_and_auth",
"(",
"self",
",",
"url",
")",
":",
"if",
"'://'",
"not",
"in",
"url",
":",
"assert",
"'file:'",
"not",
"in",
"url",
"url",
"=",
"url",
".",
"replace",
"(",
"'git+'",
",",
"'git+ssh://'",
")",
"url",
",",
"rev",
",",
"user_pass",
"=",
"super",
"(",
"Git",
",",
"self",
")",
".",
"get_url_rev_and_auth",
"(",
"url",
")",
"url",
"=",
"url",
".",
"replace",
"(",
"'ssh://'",
",",
"''",
")",
"else",
":",
"url",
",",
"rev",
",",
"user_pass",
"=",
"super",
"(",
"Git",
",",
"self",
")",
".",
"get_url_rev_and_auth",
"(",
"url",
")",
"return",
"url",
",",
"rev",
",",
"user_pass"
] |
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
|
[
"Prefixes",
"stub",
"URLs",
"like",
"user"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/git.py#L328-L343
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
_normalize_name
|
def _normalize_name(name):
# type: (str) -> str
"""Make a name consistent regardless of source (environment or file)
"""
name = name.lower().replace('_', '-')
if name.startswith('--'):
name = name[2:] # only prefer long opts
return name
|
python
|
def _normalize_name(name):
# type: (str) -> str
"""Make a name consistent regardless of source (environment or file)
"""
name = name.lower().replace('_', '-')
if name.startswith('--'):
name = name[2:] # only prefer long opts
return name
|
[
"def",
"_normalize_name",
"(",
"name",
")",
":",
"# type: (str) -> str",
"name",
"=",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"name",
".",
"startswith",
"(",
"'--'",
")",
":",
"name",
"=",
"name",
"[",
"2",
":",
"]",
"# only prefer long opts",
"return",
"name"
] |
Make a name consistent regardless of source (environment or file)
|
[
"Make",
"a",
"name",
"consistent",
"regardless",
"of",
"source",
"(",
"environment",
"or",
"file",
")"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L43-L50
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration.get_value
|
def get_value(self, key):
# type: (str) -> Any
"""Get a value from the configuration.
"""
try:
return self._dictionary[key]
except KeyError:
raise ConfigurationError("No such key - {}".format(key))
|
python
|
def get_value(self, key):
# type: (str) -> Any
"""Get a value from the configuration.
"""
try:
return self._dictionary[key]
except KeyError:
raise ConfigurationError("No such key - {}".format(key))
|
[
"def",
"get_value",
"(",
"self",
",",
"key",
")",
":",
"# type: (str) -> Any",
"try",
":",
"return",
"self",
".",
"_dictionary",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"ConfigurationError",
"(",
"\"No such key - {}\"",
".",
"format",
"(",
"key",
")",
")"
] |
Get a value from the configuration.
|
[
"Get",
"a",
"value",
"from",
"the",
"configuration",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L139-L146
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration.set_value
|
def set_value(self, key, value):
# type: (str, Any) -> None
"""Modify a value in the configuration.
"""
self._ensure_have_load_only()
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Modify the parser and the configuration
if not parser.has_section(section):
parser.add_section(section)
parser.set(section, name, value)
self._config[self.load_only][key] = value
self._mark_as_modified(fname, parser)
|
python
|
def set_value(self, key, value):
# type: (str, Any) -> None
"""Modify a value in the configuration.
"""
self._ensure_have_load_only()
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Modify the parser and the configuration
if not parser.has_section(section):
parser.add_section(section)
parser.set(section, name, value)
self._config[self.load_only][key] = value
self._mark_as_modified(fname, parser)
|
[
"def",
"set_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# type: (str, Any) -> None",
"self",
".",
"_ensure_have_load_only",
"(",
")",
"fname",
",",
"parser",
"=",
"self",
".",
"_get_parser_to_modify",
"(",
")",
"if",
"parser",
"is",
"not",
"None",
":",
"section",
",",
"name",
"=",
"_disassemble_key",
"(",
"key",
")",
"# Modify the parser and the configuration",
"if",
"not",
"parser",
".",
"has_section",
"(",
"section",
")",
":",
"parser",
".",
"add_section",
"(",
"section",
")",
"parser",
".",
"set",
"(",
"section",
",",
"name",
",",
"value",
")",
"self",
".",
"_config",
"[",
"self",
".",
"load_only",
"]",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"_mark_as_modified",
"(",
"fname",
",",
"parser",
")"
] |
Modify a value in the configuration.
|
[
"Modify",
"a",
"value",
"in",
"the",
"configuration",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L148-L165
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration.unset_value
|
def unset_value(self, key):
# type: (str) -> None
"""Unset a value in the configuration.
"""
self._ensure_have_load_only()
if key not in self._config[self.load_only]:
raise ConfigurationError("No such key - {}".format(key))
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Remove the key in the parser
modified_something = False
if parser.has_section(section):
# Returns whether the option was removed or not
modified_something = parser.remove_option(section, name)
if modified_something:
# name removed from parser, section may now be empty
section_iter = iter(parser.items(section))
try:
val = six.next(section_iter)
except StopIteration:
val = None
if val is None:
parser.remove_section(section)
self._mark_as_modified(fname, parser)
else:
raise ConfigurationError(
"Fatal Internal error [id=1]. Please report as a bug."
)
del self._config[self.load_only][key]
|
python
|
def unset_value(self, key):
# type: (str) -> None
"""Unset a value in the configuration.
"""
self._ensure_have_load_only()
if key not in self._config[self.load_only]:
raise ConfigurationError("No such key - {}".format(key))
fname, parser = self._get_parser_to_modify()
if parser is not None:
section, name = _disassemble_key(key)
# Remove the key in the parser
modified_something = False
if parser.has_section(section):
# Returns whether the option was removed or not
modified_something = parser.remove_option(section, name)
if modified_something:
# name removed from parser, section may now be empty
section_iter = iter(parser.items(section))
try:
val = six.next(section_iter)
except StopIteration:
val = None
if val is None:
parser.remove_section(section)
self._mark_as_modified(fname, parser)
else:
raise ConfigurationError(
"Fatal Internal error [id=1]. Please report as a bug."
)
del self._config[self.load_only][key]
|
[
"def",
"unset_value",
"(",
"self",
",",
"key",
")",
":",
"# type: (str) -> None",
"self",
".",
"_ensure_have_load_only",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_config",
"[",
"self",
".",
"load_only",
"]",
":",
"raise",
"ConfigurationError",
"(",
"\"No such key - {}\"",
".",
"format",
"(",
"key",
")",
")",
"fname",
",",
"parser",
"=",
"self",
".",
"_get_parser_to_modify",
"(",
")",
"if",
"parser",
"is",
"not",
"None",
":",
"section",
",",
"name",
"=",
"_disassemble_key",
"(",
"key",
")",
"# Remove the key in the parser",
"modified_something",
"=",
"False",
"if",
"parser",
".",
"has_section",
"(",
"section",
")",
":",
"# Returns whether the option was removed or not",
"modified_something",
"=",
"parser",
".",
"remove_option",
"(",
"section",
",",
"name",
")",
"if",
"modified_something",
":",
"# name removed from parser, section may now be empty",
"section_iter",
"=",
"iter",
"(",
"parser",
".",
"items",
"(",
"section",
")",
")",
"try",
":",
"val",
"=",
"six",
".",
"next",
"(",
"section_iter",
")",
"except",
"StopIteration",
":",
"val",
"=",
"None",
"if",
"val",
"is",
"None",
":",
"parser",
".",
"remove_section",
"(",
"section",
")",
"self",
".",
"_mark_as_modified",
"(",
"fname",
",",
"parser",
")",
"else",
":",
"raise",
"ConfigurationError",
"(",
"\"Fatal Internal error [id=1]. Please report as a bug.\"",
")",
"del",
"self",
".",
"_config",
"[",
"self",
".",
"load_only",
"]",
"[",
"key",
"]"
] |
Unset a value in the configuration.
|
[
"Unset",
"a",
"value",
"in",
"the",
"configuration",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L167-L204
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration.save
|
def save(self):
# type: () -> None
"""Save the currentin-memory state.
"""
self._ensure_have_load_only()
for fname, parser in self._modified_parsers:
logger.info("Writing to %s", fname)
# Ensure directory exists.
ensure_dir(os.path.dirname(fname))
with open(fname, "w") as f:
parser.write(f)
|
python
|
def save(self):
# type: () -> None
"""Save the currentin-memory state.
"""
self._ensure_have_load_only()
for fname, parser in self._modified_parsers:
logger.info("Writing to %s", fname)
# Ensure directory exists.
ensure_dir(os.path.dirname(fname))
with open(fname, "w") as f:
parser.write(f)
|
[
"def",
"save",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_ensure_have_load_only",
"(",
")",
"for",
"fname",
",",
"parser",
"in",
"self",
".",
"_modified_parsers",
":",
"logger",
".",
"info",
"(",
"\"Writing to %s\"",
",",
"fname",
")",
"# Ensure directory exists.",
"ensure_dir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fname",
")",
")",
"with",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"as",
"f",
":",
"parser",
".",
"write",
"(",
"f",
")"
] |
Save the currentin-memory state.
|
[
"Save",
"the",
"currentin",
"-",
"memory",
"state",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L206-L219
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._dictionary
|
def _dictionary(self):
# type: () -> Dict[str, Any]
"""A dictionary representing the loaded configuration.
"""
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
retval = {}
for variant in self._override_order:
retval.update(self._config[variant])
return retval
|
python
|
def _dictionary(self):
# type: () -> Dict[str, Any]
"""A dictionary representing the loaded configuration.
"""
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
retval = {}
for variant in self._override_order:
retval.update(self._config[variant])
return retval
|
[
"def",
"_dictionary",
"(",
"self",
")",
":",
"# type: () -> Dict[str, Any]",
"# NOTE: Dictionaries are not populated if not loaded. So, conditionals",
"# are not needed here.",
"retval",
"=",
"{",
"}",
"for",
"variant",
"in",
"self",
".",
"_override_order",
":",
"retval",
".",
"update",
"(",
"self",
".",
"_config",
"[",
"variant",
"]",
")",
"return",
"retval"
] |
A dictionary representing the loaded configuration.
|
[
"A",
"dictionary",
"representing",
"the",
"loaded",
"configuration",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L232-L243
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._load_config_files
|
def _load_config_files(self):
# type: () -> None
"""Loads configuration from configuration files
"""
config_files = dict(self._iter_config_files())
if config_files[kinds.ENV][0:1] == [os.devnull]:
logger.debug(
"Skipping loading configuration files due to "
"environment's PIP_CONFIG_FILE being os.devnull"
)
return
for variant, files in config_files.items():
for fname in files:
# If there's specific variant set in `load_only`, load only
# that variant, not the others.
if self.load_only is not None and variant != self.load_only:
logger.debug(
"Skipping file '%s' (variant: %s)", fname, variant
)
continue
parser = self._load_file(variant, fname)
# Keeping track of the parsers used
self._parsers[variant].append((fname, parser))
|
python
|
def _load_config_files(self):
# type: () -> None
"""Loads configuration from configuration files
"""
config_files = dict(self._iter_config_files())
if config_files[kinds.ENV][0:1] == [os.devnull]:
logger.debug(
"Skipping loading configuration files due to "
"environment's PIP_CONFIG_FILE being os.devnull"
)
return
for variant, files in config_files.items():
for fname in files:
# If there's specific variant set in `load_only`, load only
# that variant, not the others.
if self.load_only is not None and variant != self.load_only:
logger.debug(
"Skipping file '%s' (variant: %s)", fname, variant
)
continue
parser = self._load_file(variant, fname)
# Keeping track of the parsers used
self._parsers[variant].append((fname, parser))
|
[
"def",
"_load_config_files",
"(",
"self",
")",
":",
"# type: () -> None",
"config_files",
"=",
"dict",
"(",
"self",
".",
"_iter_config_files",
"(",
")",
")",
"if",
"config_files",
"[",
"kinds",
".",
"ENV",
"]",
"[",
"0",
":",
"1",
"]",
"==",
"[",
"os",
".",
"devnull",
"]",
":",
"logger",
".",
"debug",
"(",
"\"Skipping loading configuration files due to \"",
"\"environment's PIP_CONFIG_FILE being os.devnull\"",
")",
"return",
"for",
"variant",
",",
"files",
"in",
"config_files",
".",
"items",
"(",
")",
":",
"for",
"fname",
"in",
"files",
":",
"# If there's specific variant set in `load_only`, load only",
"# that variant, not the others.",
"if",
"self",
".",
"load_only",
"is",
"not",
"None",
"and",
"variant",
"!=",
"self",
".",
"load_only",
":",
"logger",
".",
"debug",
"(",
"\"Skipping file '%s' (variant: %s)\"",
",",
"fname",
",",
"variant",
")",
"continue",
"parser",
"=",
"self",
".",
"_load_file",
"(",
"variant",
",",
"fname",
")",
"# Keeping track of the parsers used",
"self",
".",
"_parsers",
"[",
"variant",
"]",
".",
"append",
"(",
"(",
"fname",
",",
"parser",
")",
")"
] |
Loads configuration from configuration files
|
[
"Loads",
"configuration",
"from",
"configuration",
"files"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L245-L270
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._load_environment_vars
|
def _load_environment_vars(self):
# type: () -> None
"""Loads configuration from environment variables
"""
self._config[kinds.ENV_VAR].update(
self._normalized_keys(":env:", self._get_environ_vars())
)
|
python
|
def _load_environment_vars(self):
# type: () -> None
"""Loads configuration from environment variables
"""
self._config[kinds.ENV_VAR].update(
self._normalized_keys(":env:", self._get_environ_vars())
)
|
[
"def",
"_load_environment_vars",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_config",
"[",
"kinds",
".",
"ENV_VAR",
"]",
".",
"update",
"(",
"self",
".",
"_normalized_keys",
"(",
"\":env:\"",
",",
"self",
".",
"_get_environ_vars",
"(",
")",
")",
")"
] |
Loads configuration from environment variables
|
[
"Loads",
"configuration",
"from",
"environment",
"variables"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L306-L312
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._normalized_keys
|
def _normalized_keys(self, section, items):
# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]
"""Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
regardless of source - configuration files or environment.
"""
normalized = {}
for name, val in items:
key = section + "." + _normalize_name(name)
normalized[key] = val
return normalized
|
python
|
def _normalized_keys(self, section, items):
# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]
"""Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
regardless of source - configuration files or environment.
"""
normalized = {}
for name, val in items:
key = section + "." + _normalize_name(name)
normalized[key] = val
return normalized
|
[
"def",
"_normalized_keys",
"(",
"self",
",",
"section",
",",
"items",
")",
":",
"# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]",
"normalized",
"=",
"{",
"}",
"for",
"name",
",",
"val",
"in",
"items",
":",
"key",
"=",
"section",
"+",
"\".\"",
"+",
"_normalize_name",
"(",
"name",
")",
"normalized",
"[",
"key",
"]",
"=",
"val",
"return",
"normalized"
] |
Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
regardless of source - configuration files or environment.
|
[
"Normalizes",
"items",
"to",
"construct",
"a",
"dictionary",
"with",
"normalized",
"keys",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L314-L325
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._get_environ_vars
|
def _get_environ_vars(self):
# type: () -> Iterable[Tuple[str, str]]
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
should_be_yielded = (
key.startswith("PIP_") and
key[4:].lower() not in self._ignore_env_names
)
if should_be_yielded:
yield key[4:].lower(), val
|
python
|
def _get_environ_vars(self):
# type: () -> Iterable[Tuple[str, str]]
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
should_be_yielded = (
key.startswith("PIP_") and
key[4:].lower() not in self._ignore_env_names
)
if should_be_yielded:
yield key[4:].lower(), val
|
[
"def",
"_get_environ_vars",
"(",
"self",
")",
":",
"# type: () -> Iterable[Tuple[str, str]]",
"for",
"key",
",",
"val",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"should_be_yielded",
"=",
"(",
"key",
".",
"startswith",
"(",
"\"PIP_\"",
")",
"and",
"key",
"[",
"4",
":",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"self",
".",
"_ignore_env_names",
")",
"if",
"should_be_yielded",
":",
"yield",
"key",
"[",
"4",
":",
"]",
".",
"lower",
"(",
")",
",",
"val"
] |
Returns a generator with all environmental vars with prefix PIP_
|
[
"Returns",
"a",
"generator",
"with",
"all",
"environmental",
"vars",
"with",
"prefix",
"PIP_"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L327-L336
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/configuration.py
|
Configuration._iter_config_files
|
def _iter_config_files(self):
# type: () -> Iterable[Tuple[Kind, List[str]]]
"""Yields variant and configuration files associated with it.
This should be treated like items of a dictionary.
"""
# SMELL: Move the conditions out of this function
# environment variables have the lowest priority
config_file = os.environ.get('PIP_CONFIG_FILE', None)
if config_file is not None:
yield kinds.ENV, [config_file]
else:
yield kinds.ENV, []
# at the base we have any global configuration
yield kinds.GLOBAL, list(site_config_files)
# per-user configuration next
should_load_user_config = not self.isolated and not (
config_file and os.path.exists(config_file)
)
if should_load_user_config:
# The legacy config file is overridden by the new config file
yield kinds.USER, [legacy_config_file, new_config_file]
# finally virtualenv configuration first trumping others
if running_under_virtualenv():
yield kinds.VENV, [venv_config_file]
|
python
|
def _iter_config_files(self):
# type: () -> Iterable[Tuple[Kind, List[str]]]
"""Yields variant and configuration files associated with it.
This should be treated like items of a dictionary.
"""
# SMELL: Move the conditions out of this function
# environment variables have the lowest priority
config_file = os.environ.get('PIP_CONFIG_FILE', None)
if config_file is not None:
yield kinds.ENV, [config_file]
else:
yield kinds.ENV, []
# at the base we have any global configuration
yield kinds.GLOBAL, list(site_config_files)
# per-user configuration next
should_load_user_config = not self.isolated and not (
config_file and os.path.exists(config_file)
)
if should_load_user_config:
# The legacy config file is overridden by the new config file
yield kinds.USER, [legacy_config_file, new_config_file]
# finally virtualenv configuration first trumping others
if running_under_virtualenv():
yield kinds.VENV, [venv_config_file]
|
[
"def",
"_iter_config_files",
"(",
"self",
")",
":",
"# type: () -> Iterable[Tuple[Kind, List[str]]]",
"# SMELL: Move the conditions out of this function",
"# environment variables have the lowest priority",
"config_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PIP_CONFIG_FILE'",
",",
"None",
")",
"if",
"config_file",
"is",
"not",
"None",
":",
"yield",
"kinds",
".",
"ENV",
",",
"[",
"config_file",
"]",
"else",
":",
"yield",
"kinds",
".",
"ENV",
",",
"[",
"]",
"# at the base we have any global configuration",
"yield",
"kinds",
".",
"GLOBAL",
",",
"list",
"(",
"site_config_files",
")",
"# per-user configuration next",
"should_load_user_config",
"=",
"not",
"self",
".",
"isolated",
"and",
"not",
"(",
"config_file",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
")",
"if",
"should_load_user_config",
":",
"# The legacy config file is overridden by the new config file",
"yield",
"kinds",
".",
"USER",
",",
"[",
"legacy_config_file",
",",
"new_config_file",
"]",
"# finally virtualenv configuration first trumping others",
"if",
"running_under_virtualenv",
"(",
")",
":",
"yield",
"kinds",
".",
"VENV",
",",
"[",
"venv_config_file",
"]"
] |
Yields variant and configuration files associated with it.
This should be treated like items of a dictionary.
|
[
"Yields",
"variant",
"and",
"configuration",
"files",
"associated",
"with",
"it",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/configuration.py#L339-L367
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/commands/configuration.py
|
ConfigurationCommand._get_n_args
|
def _get_n_args(self, args, example, n):
"""Helper to make sure the command got the right number of arguments
"""
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise PipError(msg)
if n == 1:
return args[0]
else:
return args
|
python
|
def _get_n_args(self, args, example, n):
"""Helper to make sure the command got the right number of arguments
"""
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise PipError(msg)
if n == 1:
return args[0]
else:
return args
|
[
"def",
"_get_n_args",
"(",
"self",
",",
"args",
",",
"example",
",",
"n",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"n",
":",
"msg",
"=",
"(",
"'Got unexpected number of arguments, expected {}. '",
"'(example: \"{} config {}\")'",
")",
".",
"format",
"(",
"n",
",",
"get_prog",
"(",
")",
",",
"example",
")",
"raise",
"PipError",
"(",
"msg",
")",
"if",
"n",
"==",
"1",
":",
"return",
"args",
"[",
"0",
"]",
"else",
":",
"return",
"args"
] |
Helper to make sure the command got the right number of arguments
|
[
"Helper",
"to",
"make",
"sure",
"the",
"command",
"got",
"the",
"right",
"number",
"of",
"arguments"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/configuration.py#L192-L205
|
train
|
pypa/pipenv
|
pipenv/cmdparse.py
|
Script.cmdify
|
def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
foul characters. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
Foul characters include:
* Whitespaces.
* Carets (^). (pypa/pipenv#3307)
* Parentheses in the command. (pypa/pipenv#3168)
Carets introduce a difficult situation since they are essentially
"lossy" when parsed. Consider this in cmd.exe::
> echo "foo^bar"
"foo^bar"
> echo foo^^bar
foo^bar
The two commands produce different results, but are both parsed by the
shell as `foo^bar`, and there's essentially no sensible way to tell
what was actually passed in. This implementation assumes the quoted
variation (the first) since it is easier to implement, and arguably
the more common case.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
"""
return " ".join(itertools.chain(
[_quote_if_contains(self.command, r'[\s^()]')],
(_quote_if_contains(arg, r'[\s^]') for arg in self.args),
))
|
python
|
def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
foul characters. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
Foul characters include:
* Whitespaces.
* Carets (^). (pypa/pipenv#3307)
* Parentheses in the command. (pypa/pipenv#3168)
Carets introduce a difficult situation since they are essentially
"lossy" when parsed. Consider this in cmd.exe::
> echo "foo^bar"
"foo^bar"
> echo foo^^bar
foo^bar
The two commands produce different results, but are both parsed by the
shell as `foo^bar`, and there's essentially no sensible way to tell
what was actually passed in. This implementation assumes the quoted
variation (the first) since it is easier to implement, and arguably
the more common case.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
"""
return " ".join(itertools.chain(
[_quote_if_contains(self.command, r'[\s^()]')],
(_quote_if_contains(arg, r'[\s^]') for arg in self.args),
))
|
[
"def",
"cmdify",
"(",
"self",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"[",
"_quote_if_contains",
"(",
"self",
".",
"command",
",",
"r'[\\s^()]'",
")",
"]",
",",
"(",
"_quote_if_contains",
"(",
"arg",
",",
"r'[\\s^]'",
")",
"for",
"arg",
"in",
"self",
".",
"args",
")",
",",
")",
")"
] |
Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
foul characters. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
Foul characters include:
* Whitespaces.
* Carets (^). (pypa/pipenv#3307)
* Parentheses in the command. (pypa/pipenv#3168)
Carets introduce a difficult situation since they are essentially
"lossy" when parsed. Consider this in cmd.exe::
> echo "foo^bar"
"foo^bar"
> echo foo^^bar
foo^bar
The two commands produce different results, but are both parsed by the
shell as `foo^bar`, and there's essentially no sensible way to tell
what was actually passed in. This implementation assumes the quoted
variation (the first) since it is easier to implement, and arguably
the more common case.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
|
[
"Encode",
"into",
"a",
"cmd",
"-",
"executable",
"string",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cmdparse.py#L51-L98
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
normalize_path
|
def normalize_path(path):
# type: (AnyStr) -> AnyStr
"""
Return a case-normalized absolute variable-expanded path.
:param str path: The non-normalized path
:return: A normalized, expanded, case-normalized path
:rtype: str
"""
return os.path.normpath(
os.path.normcase(
os.path.abspath(os.path.expandvars(os.path.expanduser(str(path))))
)
)
|
python
|
def normalize_path(path):
# type: (AnyStr) -> AnyStr
"""
Return a case-normalized absolute variable-expanded path.
:param str path: The non-normalized path
:return: A normalized, expanded, case-normalized path
:rtype: str
"""
return os.path.normpath(
os.path.normcase(
os.path.abspath(os.path.expandvars(os.path.expanduser(str(path))))
)
)
|
[
"def",
"normalize_path",
"(",
"path",
")",
":",
"# type: (AnyStr) -> AnyStr",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"str",
"(",
"path",
")",
")",
")",
")",
")",
")"
] |
Return a case-normalized absolute variable-expanded path.
:param str path: The non-normalized path
:return: A normalized, expanded, case-normalized path
:rtype: str
|
[
"Return",
"a",
"case",
"-",
"normalized",
"absolute",
"variable",
"-",
"expanded",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L97-L111
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
path_to_url
|
def path_to_url(path):
# type: (str) -> Text
"""Convert the supplied local path to a file uri.
:param str path: A string pointing to or representing a local path
:return: A `file://` uri for the same location
:rtype: str
>>> path_to_url("/home/user/code/myrepo/myfile.zip")
'file:///home/user/code/myrepo/myfile.zip'
"""
from .misc import to_text, to_bytes
if not path:
return path
path = to_bytes(path, encoding="utf-8")
normalized_path = to_text(normalize_drive(os.path.abspath(path)), encoding="utf-8")
return to_text(Path(normalized_path).as_uri(), encoding="utf-8")
|
python
|
def path_to_url(path):
# type: (str) -> Text
"""Convert the supplied local path to a file uri.
:param str path: A string pointing to or representing a local path
:return: A `file://` uri for the same location
:rtype: str
>>> path_to_url("/home/user/code/myrepo/myfile.zip")
'file:///home/user/code/myrepo/myfile.zip'
"""
from .misc import to_text, to_bytes
if not path:
return path
path = to_bytes(path, encoding="utf-8")
normalized_path = to_text(normalize_drive(os.path.abspath(path)), encoding="utf-8")
return to_text(Path(normalized_path).as_uri(), encoding="utf-8")
|
[
"def",
"path_to_url",
"(",
"path",
")",
":",
"# type: (str) -> Text",
"from",
".",
"misc",
"import",
"to_text",
",",
"to_bytes",
"if",
"not",
"path",
":",
"return",
"path",
"path",
"=",
"to_bytes",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"normalized_path",
"=",
"to_text",
"(",
"normalize_drive",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"return",
"to_text",
"(",
"Path",
"(",
"normalized_path",
")",
".",
"as_uri",
"(",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")"
] |
Convert the supplied local path to a file uri.
:param str path: A string pointing to or representing a local path
:return: A `file://` uri for the same location
:rtype: str
>>> path_to_url("/home/user/code/myrepo/myfile.zip")
'file:///home/user/code/myrepo/myfile.zip'
|
[
"Convert",
"the",
"supplied",
"local",
"path",
"to",
"a",
"file",
"uri",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L149-L166
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
url_to_path
|
def url_to_path(url):
# type: (str) -> ByteString
"""
Convert a valid file url to a local filesystem path
Follows logic taken from pip's equivalent function
"""
from .misc import to_bytes
assert is_file_url(url), "Only file: urls can be converted to local paths"
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# Netlocs are UNC paths
if netloc:
netloc = "\\\\" + netloc
path = urllib_request.url2pathname(netloc + path)
return to_bytes(path, encoding="utf-8")
|
python
|
def url_to_path(url):
# type: (str) -> ByteString
"""
Convert a valid file url to a local filesystem path
Follows logic taken from pip's equivalent function
"""
from .misc import to_bytes
assert is_file_url(url), "Only file: urls can be converted to local paths"
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# Netlocs are UNC paths
if netloc:
netloc = "\\\\" + netloc
path = urllib_request.url2pathname(netloc + path)
return to_bytes(path, encoding="utf-8")
|
[
"def",
"url_to_path",
"(",
"url",
")",
":",
"# type: (str) -> ByteString",
"from",
".",
"misc",
"import",
"to_bytes",
"assert",
"is_file_url",
"(",
"url",
")",
",",
"\"Only file: urls can be converted to local paths\"",
"_",
",",
"netloc",
",",
"path",
",",
"_",
",",
"_",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"# Netlocs are UNC paths",
"if",
"netloc",
":",
"netloc",
"=",
"\"\\\\\\\\\"",
"+",
"netloc",
"path",
"=",
"urllib_request",
".",
"url2pathname",
"(",
"netloc",
"+",
"path",
")",
"return",
"to_bytes",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")"
] |
Convert a valid file url to a local filesystem path
Follows logic taken from pip's equivalent function
|
[
"Convert",
"a",
"valid",
"file",
"url",
"to",
"a",
"local",
"filesystem",
"path"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L169-L185
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
is_valid_url
|
def is_valid_url(url):
"""Checks if a given string is an url"""
from .misc import to_text
if not url:
return url
pieces = urllib_parse.urlparse(to_text(url))
return all([pieces.scheme, pieces.netloc])
|
python
|
def is_valid_url(url):
"""Checks if a given string is an url"""
from .misc import to_text
if not url:
return url
pieces = urllib_parse.urlparse(to_text(url))
return all([pieces.scheme, pieces.netloc])
|
[
"def",
"is_valid_url",
"(",
"url",
")",
":",
"from",
".",
"misc",
"import",
"to_text",
"if",
"not",
"url",
":",
"return",
"url",
"pieces",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"to_text",
"(",
"url",
")",
")",
"return",
"all",
"(",
"[",
"pieces",
".",
"scheme",
",",
"pieces",
".",
"netloc",
"]",
")"
] |
Checks if a given string is an url
|
[
"Checks",
"if",
"a",
"given",
"string",
"is",
"an",
"url"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L188-L195
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
is_file_url
|
def is_file_url(url):
"""Returns true if the given url is a file url"""
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text(url, encoding="utf-8")
return urllib_parse.urlparse(url.lower()).scheme == "file"
|
python
|
def is_file_url(url):
"""Returns true if the given url is a file url"""
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text(url, encoding="utf-8")
return urllib_parse.urlparse(url.lower()).scheme == "file"
|
[
"def",
"is_file_url",
"(",
"url",
")",
":",
"from",
".",
"misc",
"import",
"to_text",
"if",
"not",
"url",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"url",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"url",
"=",
"getattr",
"(",
"url",
",",
"\"url\"",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"\"Cannot parse url from unknown type: {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"url",
"=",
"to_text",
"(",
"url",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"return",
"urllib_parse",
".",
"urlparse",
"(",
"url",
".",
"lower",
"(",
")",
")",
".",
"scheme",
"==",
"\"file\""
] |
Returns true if the given url is a file url
|
[
"Returns",
"true",
"if",
"the",
"given",
"url",
"is",
"a",
"file",
"url"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L198-L210
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
is_readonly_path
|
def is_readonly_path(fn):
"""Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
"""
fn = fs_encode(fn)
if os.path.exists(fn):
file_stat = os.stat(fn).st_mode
return not bool(file_stat & stat.S_IWRITE) or not os.access(fn, os.W_OK)
return False
|
python
|
def is_readonly_path(fn):
"""Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
"""
fn = fs_encode(fn)
if os.path.exists(fn):
file_stat = os.stat(fn).st_mode
return not bool(file_stat & stat.S_IWRITE) or not os.access(fn, os.W_OK)
return False
|
[
"def",
"is_readonly_path",
"(",
"fn",
")",
":",
"fn",
"=",
"fs_encode",
"(",
"fn",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"file_stat",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"st_mode",
"return",
"not",
"bool",
"(",
"file_stat",
"&",
"stat",
".",
"S_IWRITE",
")",
"or",
"not",
"os",
".",
"access",
"(",
"fn",
",",
"os",
".",
"W_OK",
")",
"return",
"False"
] |
Check if a provided path exists and is readonly.
Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
|
[
"Check",
"if",
"a",
"provided",
"path",
"exists",
"and",
"is",
"readonly",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L213-L223
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
mkdir_p
|
def mkdir_p(newdir, mode=0o777):
"""Recursively creates the target directory and all of its parents if they do not
already exist. Fails silently if they do.
:param str newdir: The directory path to ensure
:raises: OSError if a file is encountered along the way
"""
# http://code.activestate.com/recipes/82465-a-friendly-mkdir/
newdir = fs_encode(newdir)
if os.path.exists(newdir):
if not os.path.isdir(newdir):
raise OSError(
"a file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
else:
head, tail = os.path.split(newdir)
# Make sure the tail doesn't point to the asame place as the head
curdir = fs_encode(".")
tail_and_head_match = (
os.path.relpath(tail, start=os.path.basename(head)) == curdir
)
if tail and not tail_and_head_match and not os.path.isdir(newdir):
target = os.path.join(head, tail)
if os.path.exists(target) and os.path.isfile(target):
raise OSError(
"A file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
os.makedirs(os.path.join(head, tail), mode)
|
python
|
def mkdir_p(newdir, mode=0o777):
"""Recursively creates the target directory and all of its parents if they do not
already exist. Fails silently if they do.
:param str newdir: The directory path to ensure
:raises: OSError if a file is encountered along the way
"""
# http://code.activestate.com/recipes/82465-a-friendly-mkdir/
newdir = fs_encode(newdir)
if os.path.exists(newdir):
if not os.path.isdir(newdir):
raise OSError(
"a file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
else:
head, tail = os.path.split(newdir)
# Make sure the tail doesn't point to the asame place as the head
curdir = fs_encode(".")
tail_and_head_match = (
os.path.relpath(tail, start=os.path.basename(head)) == curdir
)
if tail and not tail_and_head_match and not os.path.isdir(newdir):
target = os.path.join(head, tail)
if os.path.exists(target) and os.path.isfile(target):
raise OSError(
"A file with the same name as the desired dir, '{0}', already exists.".format(
fs_decode(newdir)
)
)
os.makedirs(os.path.join(head, tail), mode)
|
[
"def",
"mkdir_p",
"(",
"newdir",
",",
"mode",
"=",
"0o777",
")",
":",
"# http://code.activestate.com/recipes/82465-a-friendly-mkdir/",
"newdir",
"=",
"fs_encode",
"(",
"newdir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"newdir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"newdir",
")",
":",
"raise",
"OSError",
"(",
"\"a file with the same name as the desired dir, '{0}', already exists.\"",
".",
"format",
"(",
"fs_decode",
"(",
"newdir",
")",
")",
")",
"else",
":",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"newdir",
")",
"# Make sure the tail doesn't point to the asame place as the head",
"curdir",
"=",
"fs_encode",
"(",
"\".\"",
")",
"tail_and_head_match",
"=",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"tail",
",",
"start",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"head",
")",
")",
"==",
"curdir",
")",
"if",
"tail",
"and",
"not",
"tail_and_head_match",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"newdir",
")",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"head",
",",
"tail",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"target",
")",
":",
"raise",
"OSError",
"(",
"\"A file with the same name as the desired dir, '{0}', already exists.\"",
".",
"format",
"(",
"fs_decode",
"(",
"newdir",
")",
")",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"head",
",",
"tail",
")",
",",
"mode",
")"
] |
Recursively creates the target directory and all of its parents if they do not
already exist. Fails silently if they do.
:param str newdir: The directory path to ensure
:raises: OSError if a file is encountered along the way
|
[
"Recursively",
"creates",
"the",
"target",
"directory",
"and",
"all",
"of",
"its",
"parents",
"if",
"they",
"do",
"not",
"already",
"exist",
".",
"Fails",
"silently",
"if",
"they",
"do",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L226-L258
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
ensure_mkdir_p
|
def ensure_mkdir_p(mode=0o777):
"""Decorator to ensure `mkdir_p` is called to the function's return value.
"""
def decorator(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
path = f(*args, **kwargs)
mkdir_p(path, mode=mode)
return path
return decorated
return decorator
|
python
|
def ensure_mkdir_p(mode=0o777):
"""Decorator to ensure `mkdir_p` is called to the function's return value.
"""
def decorator(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
path = f(*args, **kwargs)
mkdir_p(path, mode=mode)
return path
return decorated
return decorator
|
[
"def",
"ensure_mkdir_p",
"(",
"mode",
"=",
"0o777",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"mkdir_p",
"(",
"path",
",",
"mode",
"=",
"mode",
")",
"return",
"path",
"return",
"decorated",
"return",
"decorator"
] |
Decorator to ensure `mkdir_p` is called to the function's return value.
|
[
"Decorator",
"to",
"ensure",
"mkdir_p",
"is",
"called",
"to",
"the",
"function",
"s",
"return",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L261-L274
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
create_tracked_tempdir
|
def create_tracked_tempdir(*args, **kwargs):
"""Create a tracked temporary directory.
This uses `TemporaryDirectory`, but does not remove the directory when
the return value goes out of scope, instead registers a handler to cleanup
on program exit.
The return value is the path to the created directory.
"""
tempdir = TemporaryDirectory(*args, **kwargs)
TRACKED_TEMPORARY_DIRECTORIES.append(tempdir)
atexit.register(tempdir.cleanup)
warnings.simplefilter("ignore", ResourceWarning)
return tempdir.name
|
python
|
def create_tracked_tempdir(*args, **kwargs):
"""Create a tracked temporary directory.
This uses `TemporaryDirectory`, but does not remove the directory when
the return value goes out of scope, instead registers a handler to cleanup
on program exit.
The return value is the path to the created directory.
"""
tempdir = TemporaryDirectory(*args, **kwargs)
TRACKED_TEMPORARY_DIRECTORIES.append(tempdir)
atexit.register(tempdir.cleanup)
warnings.simplefilter("ignore", ResourceWarning)
return tempdir.name
|
[
"def",
"create_tracked_tempdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tempdir",
"=",
"TemporaryDirectory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"TRACKED_TEMPORARY_DIRECTORIES",
".",
"append",
"(",
"tempdir",
")",
"atexit",
".",
"register",
"(",
"tempdir",
".",
"cleanup",
")",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
",",
"ResourceWarning",
")",
"return",
"tempdir",
".",
"name"
] |
Create a tracked temporary directory.
This uses `TemporaryDirectory`, but does not remove the directory when
the return value goes out of scope, instead registers a handler to cleanup
on program exit.
The return value is the path to the created directory.
|
[
"Create",
"a",
"tracked",
"temporary",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L280-L294
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
set_write_bit
|
def set_write_bit(fn):
# type: (str) -> None
"""
Set read-write permissions for the current user on the target path. Fail silently
if the path doesn't exist.
:param str fn: The target filename or path
:return: None
"""
fn = fs_encode(fn)
if not os.path.exists(fn):
return
file_stat = os.stat(fn).st_mode
os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
if not os.path.isdir(fn):
for path in [fn, os.path.dirname(fn)]:
try:
os.chflags(path, 0)
except AttributeError:
pass
return None
for root, dirs, files in os.walk(fn, topdown=False):
for dir_ in [os.path.join(root, d) for d in dirs]:
set_write_bit(dir_)
for file_ in [os.path.join(root, f) for f in files]:
set_write_bit(file_)
|
python
|
def set_write_bit(fn):
# type: (str) -> None
"""
Set read-write permissions for the current user on the target path. Fail silently
if the path doesn't exist.
:param str fn: The target filename or path
:return: None
"""
fn = fs_encode(fn)
if not os.path.exists(fn):
return
file_stat = os.stat(fn).st_mode
os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
if not os.path.isdir(fn):
for path in [fn, os.path.dirname(fn)]:
try:
os.chflags(path, 0)
except AttributeError:
pass
return None
for root, dirs, files in os.walk(fn, topdown=False):
for dir_ in [os.path.join(root, d) for d in dirs]:
set_write_bit(dir_)
for file_ in [os.path.join(root, f) for f in files]:
set_write_bit(file_)
|
[
"def",
"set_write_bit",
"(",
"fn",
")",
":",
"# type: (str) -> None",
"fn",
"=",
"fs_encode",
"(",
"fn",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"return",
"file_stat",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"st_mode",
"os",
".",
"chmod",
"(",
"fn",
",",
"file_stat",
"|",
"stat",
".",
"S_IRWXU",
"|",
"stat",
".",
"S_IRWXG",
"|",
"stat",
".",
"S_IRWXO",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"fn",
")",
":",
"for",
"path",
"in",
"[",
"fn",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"fn",
")",
"]",
":",
"try",
":",
"os",
".",
"chflags",
"(",
"path",
",",
"0",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"None",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"fn",
",",
"topdown",
"=",
"False",
")",
":",
"for",
"dir_",
"in",
"[",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
")",
"for",
"d",
"in",
"dirs",
"]",
":",
"set_write_bit",
"(",
"dir_",
")",
"for",
"file_",
"in",
"[",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"for",
"f",
"in",
"files",
"]",
":",
"set_write_bit",
"(",
"file_",
")"
] |
Set read-write permissions for the current user on the target path. Fail silently
if the path doesn't exist.
:param str fn: The target filename or path
:return: None
|
[
"Set",
"read",
"-",
"write",
"permissions",
"for",
"the",
"current",
"user",
"on",
"the",
"target",
"path",
".",
"Fail",
"silently",
"if",
"the",
"path",
"doesn",
"t",
"exist",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L310-L336
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
rmtree
|
def rmtree(directory, ignore_errors=False, onerror=None):
# type: (str, bool, Optional[Callable]) -> None
"""
Stand-in for :func:`~shutil.rmtree` with additional error-handling.
This version of `rmtree` handles read-only paths, especially in the case of index
files written by certain source control systems.
:param str directory: The target directory to remove
:param bool ignore_errors: Whether to ignore errors, defaults to False
:param func onerror: An error handling function, defaults to :func:`handle_remove_readonly`
.. note::
Setting `ignore_errors=True` may cause this to silently fail to delete the path
"""
directory = fs_encode(directory)
if onerror is None:
onerror = handle_remove_readonly
try:
shutil.rmtree(directory, ignore_errors=ignore_errors, onerror=onerror)
except (IOError, OSError, FileNotFoundError, PermissionError) as exc:
# Ignore removal failures where the file doesn't exist
if exc.errno != errno.ENOENT:
raise
|
python
|
def rmtree(directory, ignore_errors=False, onerror=None):
# type: (str, bool, Optional[Callable]) -> None
"""
Stand-in for :func:`~shutil.rmtree` with additional error-handling.
This version of `rmtree` handles read-only paths, especially in the case of index
files written by certain source control systems.
:param str directory: The target directory to remove
:param bool ignore_errors: Whether to ignore errors, defaults to False
:param func onerror: An error handling function, defaults to :func:`handle_remove_readonly`
.. note::
Setting `ignore_errors=True` may cause this to silently fail to delete the path
"""
directory = fs_encode(directory)
if onerror is None:
onerror = handle_remove_readonly
try:
shutil.rmtree(directory, ignore_errors=ignore_errors, onerror=onerror)
except (IOError, OSError, FileNotFoundError, PermissionError) as exc:
# Ignore removal failures where the file doesn't exist
if exc.errno != errno.ENOENT:
raise
|
[
"def",
"rmtree",
"(",
"directory",
",",
"ignore_errors",
"=",
"False",
",",
"onerror",
"=",
"None",
")",
":",
"# type: (str, bool, Optional[Callable]) -> None",
"directory",
"=",
"fs_encode",
"(",
"directory",
")",
"if",
"onerror",
"is",
"None",
":",
"onerror",
"=",
"handle_remove_readonly",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"directory",
",",
"ignore_errors",
"=",
"ignore_errors",
",",
"onerror",
"=",
"onerror",
")",
"except",
"(",
"IOError",
",",
"OSError",
",",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"exc",
":",
"# Ignore removal failures where the file doesn't exist",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] |
Stand-in for :func:`~shutil.rmtree` with additional error-handling.
This version of `rmtree` handles read-only paths, especially in the case of index
files written by certain source control systems.
:param str directory: The target directory to remove
:param bool ignore_errors: Whether to ignore errors, defaults to False
:param func onerror: An error handling function, defaults to :func:`handle_remove_readonly`
.. note::
Setting `ignore_errors=True` may cause this to silently fail to delete the path
|
[
"Stand",
"-",
"in",
"for",
":",
"func",
":",
"~shutil",
".",
"rmtree",
"with",
"additional",
"error",
"-",
"handling",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L339-L364
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
_wait_for_files
|
def _wait_for_files(path):
"""
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
"""
timeout = 0.001
remaining = []
while timeout < 1.0:
remaining = []
if os.path.isdir(path):
L = os.listdir(path)
for target in L:
_remaining = _wait_for_files(target)
if _remaining:
remaining.extend(_remaining)
continue
try:
os.unlink(path)
except FileNotFoundError as e:
if e.errno == errno.ENOENT:
return
except (OSError, IOError, PermissionError):
time.sleep(timeout)
timeout *= 2
remaining.append(path)
else:
return
return remaining
|
python
|
def _wait_for_files(path):
"""
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
"""
timeout = 0.001
remaining = []
while timeout < 1.0:
remaining = []
if os.path.isdir(path):
L = os.listdir(path)
for target in L:
_remaining = _wait_for_files(target)
if _remaining:
remaining.extend(_remaining)
continue
try:
os.unlink(path)
except FileNotFoundError as e:
if e.errno == errno.ENOENT:
return
except (OSError, IOError, PermissionError):
time.sleep(timeout)
timeout *= 2
remaining.append(path)
else:
return
return remaining
|
[
"def",
"_wait_for_files",
"(",
"path",
")",
":",
"timeout",
"=",
"0.001",
"remaining",
"=",
"[",
"]",
"while",
"timeout",
"<",
"1.0",
":",
"remaining",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"L",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"for",
"target",
"in",
"L",
":",
"_remaining",
"=",
"_wait_for_files",
"(",
"target",
")",
"if",
"_remaining",
":",
"remaining",
".",
"extend",
"(",
"_remaining",
")",
"continue",
"try",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"except",
"FileNotFoundError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"except",
"(",
"OSError",
",",
"IOError",
",",
"PermissionError",
")",
":",
"time",
".",
"sleep",
"(",
"timeout",
")",
"timeout",
"*=",
"2",
"remaining",
".",
"append",
"(",
"path",
")",
"else",
":",
"return",
"return",
"remaining"
] |
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
|
[
"Retry",
"with",
"backoff",
"up",
"to",
"1",
"second",
"to",
"delete",
"files",
"from",
"a",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L367-L397
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
handle_remove_readonly
|
def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exception
This function will call check :func:`is_readonly_path` before attempting to call
:func:`set_write_bit` on the target path and try again.
"""
# Check for read-only attribute
from .compat import ResourceWarning, FileNotFoundError, PermissionError
PERM_ERRORS = (errno.EACCES, errno.EPERM, errno.ENOENT)
default_warning_message = "Unable to remove file due to permissions restriction: {!r}"
# split the initial exception out into its type, exception, and traceback
exc_type, exc_exception, exc_tb = exc
if is_readonly_path(path):
# Apply write permission and call original function
set_write_bit(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno == errno.ENOENT:
return
elif e.errno in PERM_ERRORS:
remaining = None
if os.path.isdir(path):
remaining =_wait_for_files(path)
if remaining:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
raise
if exc_exception.errno in PERM_ERRORS:
set_write_bit(path)
remaining = _wait_for_files(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno in PERM_ERRORS:
warnings.warn(default_warning_message.format(path), ResourceWarning)
pass
elif e.errno == errno.ENOENT: # File already gone
pass
else:
raise
else:
return
elif exc_exception.errno == errno.ENOENT:
pass
else:
raise exc_exception
|
python
|
def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exception
This function will call check :func:`is_readonly_path` before attempting to call
:func:`set_write_bit` on the target path and try again.
"""
# Check for read-only attribute
from .compat import ResourceWarning, FileNotFoundError, PermissionError
PERM_ERRORS = (errno.EACCES, errno.EPERM, errno.ENOENT)
default_warning_message = "Unable to remove file due to permissions restriction: {!r}"
# split the initial exception out into its type, exception, and traceback
exc_type, exc_exception, exc_tb = exc
if is_readonly_path(path):
# Apply write permission and call original function
set_write_bit(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno == errno.ENOENT:
return
elif e.errno in PERM_ERRORS:
remaining = None
if os.path.isdir(path):
remaining =_wait_for_files(path)
if remaining:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
raise
if exc_exception.errno in PERM_ERRORS:
set_write_bit(path)
remaining = _wait_for_files(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno in PERM_ERRORS:
warnings.warn(default_warning_message.format(path), ResourceWarning)
pass
elif e.errno == errno.ENOENT: # File already gone
pass
else:
raise
else:
return
elif exc_exception.errno == errno.ENOENT:
pass
else:
raise exc_exception
|
[
"def",
"handle_remove_readonly",
"(",
"func",
",",
"path",
",",
"exc",
")",
":",
"# Check for read-only attribute",
"from",
".",
"compat",
"import",
"ResourceWarning",
",",
"FileNotFoundError",
",",
"PermissionError",
"PERM_ERRORS",
"=",
"(",
"errno",
".",
"EACCES",
",",
"errno",
".",
"EPERM",
",",
"errno",
".",
"ENOENT",
")",
"default_warning_message",
"=",
"\"Unable to remove file due to permissions restriction: {!r}\"",
"# split the initial exception out into its type, exception, and traceback",
"exc_type",
",",
"exc_exception",
",",
"exc_tb",
"=",
"exc",
"if",
"is_readonly_path",
"(",
"path",
")",
":",
"# Apply write permission and call original function",
"set_write_bit",
"(",
"path",
")",
"try",
":",
"func",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"IOError",
",",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"elif",
"e",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"remaining",
"=",
"None",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"remaining",
"=",
"_wait_for_files",
"(",
"path",
")",
"if",
"remaining",
":",
"warnings",
".",
"warn",
"(",
"default_warning_message",
".",
"format",
"(",
"path",
")",
",",
"ResourceWarning",
")",
"return",
"raise",
"if",
"exc_exception",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"set_write_bit",
"(",
"path",
")",
"remaining",
"=",
"_wait_for_files",
"(",
"path",
")",
"try",
":",
"func",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"IOError",
",",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"warnings",
".",
"warn",
"(",
"default_warning_message",
".",
"format",
"(",
"path",
")",
",",
"ResourceWarning",
")",
"pass",
"elif",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# File already gone",
"pass",
"else",
":",
"raise",
"else",
":",
"return",
"elif",
"exc_exception",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"pass",
"else",
":",
"raise",
"exc_exception"
] |
Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exception
This function will call check :func:`is_readonly_path` before attempting to call
:func:`set_write_bit` on the target path and try again.
|
[
"Error",
"handler",
"for",
"shutil",
".",
"rmtree",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L400-L455
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
check_for_unc_path
|
def check_for_unc_path(path):
""" Checks to see if a pathlib `Path` object is a unc path or not"""
if (
os.name == "nt"
and len(path.drive) > 2
and not path.drive[0].isalpha()
and path.drive[1] != ":"
):
return True
else:
return False
|
python
|
def check_for_unc_path(path):
""" Checks to see if a pathlib `Path` object is a unc path or not"""
if (
os.name == "nt"
and len(path.drive) > 2
and not path.drive[0].isalpha()
and path.drive[1] != ":"
):
return True
else:
return False
|
[
"def",
"check_for_unc_path",
"(",
"path",
")",
":",
"if",
"(",
"os",
".",
"name",
"==",
"\"nt\"",
"and",
"len",
"(",
"path",
".",
"drive",
")",
">",
"2",
"and",
"not",
"path",
".",
"drive",
"[",
"0",
"]",
".",
"isalpha",
"(",
")",
"and",
"path",
".",
"drive",
"[",
"1",
"]",
"!=",
"\":\"",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
Checks to see if a pathlib `Path` object is a unc path or not
|
[
"Checks",
"to",
"see",
"if",
"a",
"pathlib",
"Path",
"object",
"is",
"a",
"unc",
"path",
"or",
"not"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L486-L496
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/path.py
|
get_converted_relative_path
|
def get_converted_relative_path(path, relative_to=None):
"""Convert `path` to be relative.
Given a vague relative path, return the path relative to the given
location.
:param str path: The location of a target path
:param str relative_to: The starting path to build against, optional
:returns: A relative posix-style path with a leading `./`
This performs additional conversion to ensure the result is of POSIX form,
and starts with `./`, or is precisely `.`.
>>> os.chdir('/home/user/code/myrepo/myfolder')
>>> vistir.path.get_converted_relative_path('/home/user/code/file.zip')
'./../../file.zip'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder/mysubfolder')
'./mysubfolder'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder')
'.'
"""
from .misc import to_text, to_bytes # noqa
if not relative_to:
relative_to = os.getcwdu() if six.PY2 else os.getcwd()
if six.PY2:
path = to_bytes(path, encoding="utf-8")
else:
path = to_text(path, encoding="utf-8")
relative_to = to_text(relative_to, encoding="utf-8")
start_path = Path(relative_to)
try:
start = start_path.resolve()
except OSError:
start = start_path.absolute()
# check if there is a drive letter or mount point
# if it is a mountpoint use the original absolute path
# instead of the unc path
if check_for_unc_path(start):
start = start_path.absolute()
path = start.joinpath(path).relative_to(start)
# check and see if the path that was passed into the function is a UNC path
# and raise value error if it is not.
if check_for_unc_path(path):
raise ValueError("The path argument does not currently accept UNC paths")
relpath_s = to_text(posixpath.normpath(path.as_posix()))
if not (relpath_s == "." or relpath_s.startswith("./")):
relpath_s = posixpath.join(".", relpath_s)
return relpath_s
|
python
|
def get_converted_relative_path(path, relative_to=None):
"""Convert `path` to be relative.
Given a vague relative path, return the path relative to the given
location.
:param str path: The location of a target path
:param str relative_to: The starting path to build against, optional
:returns: A relative posix-style path with a leading `./`
This performs additional conversion to ensure the result is of POSIX form,
and starts with `./`, or is precisely `.`.
>>> os.chdir('/home/user/code/myrepo/myfolder')
>>> vistir.path.get_converted_relative_path('/home/user/code/file.zip')
'./../../file.zip'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder/mysubfolder')
'./mysubfolder'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder')
'.'
"""
from .misc import to_text, to_bytes # noqa
if not relative_to:
relative_to = os.getcwdu() if six.PY2 else os.getcwd()
if six.PY2:
path = to_bytes(path, encoding="utf-8")
else:
path = to_text(path, encoding="utf-8")
relative_to = to_text(relative_to, encoding="utf-8")
start_path = Path(relative_to)
try:
start = start_path.resolve()
except OSError:
start = start_path.absolute()
# check if there is a drive letter or mount point
# if it is a mountpoint use the original absolute path
# instead of the unc path
if check_for_unc_path(start):
start = start_path.absolute()
path = start.joinpath(path).relative_to(start)
# check and see if the path that was passed into the function is a UNC path
# and raise value error if it is not.
if check_for_unc_path(path):
raise ValueError("The path argument does not currently accept UNC paths")
relpath_s = to_text(posixpath.normpath(path.as_posix()))
if not (relpath_s == "." or relpath_s.startswith("./")):
relpath_s = posixpath.join(".", relpath_s)
return relpath_s
|
[
"def",
"get_converted_relative_path",
"(",
"path",
",",
"relative_to",
"=",
"None",
")",
":",
"from",
".",
"misc",
"import",
"to_text",
",",
"to_bytes",
"# noqa",
"if",
"not",
"relative_to",
":",
"relative_to",
"=",
"os",
".",
"getcwdu",
"(",
")",
"if",
"six",
".",
"PY2",
"else",
"os",
".",
"getcwd",
"(",
")",
"if",
"six",
".",
"PY2",
":",
"path",
"=",
"to_bytes",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"else",
":",
"path",
"=",
"to_text",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"relative_to",
"=",
"to_text",
"(",
"relative_to",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"start_path",
"=",
"Path",
"(",
"relative_to",
")",
"try",
":",
"start",
"=",
"start_path",
".",
"resolve",
"(",
")",
"except",
"OSError",
":",
"start",
"=",
"start_path",
".",
"absolute",
"(",
")",
"# check if there is a drive letter or mount point",
"# if it is a mountpoint use the original absolute path",
"# instead of the unc path",
"if",
"check_for_unc_path",
"(",
"start",
")",
":",
"start",
"=",
"start_path",
".",
"absolute",
"(",
")",
"path",
"=",
"start",
".",
"joinpath",
"(",
"path",
")",
".",
"relative_to",
"(",
"start",
")",
"# check and see if the path that was passed into the function is a UNC path",
"# and raise value error if it is not.",
"if",
"check_for_unc_path",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"\"The path argument does not currently accept UNC paths\"",
")",
"relpath_s",
"=",
"to_text",
"(",
"posixpath",
".",
"normpath",
"(",
"path",
".",
"as_posix",
"(",
")",
")",
")",
"if",
"not",
"(",
"relpath_s",
"==",
"\".\"",
"or",
"relpath_s",
".",
"startswith",
"(",
"\"./\"",
")",
")",
":",
"relpath_s",
"=",
"posixpath",
".",
"join",
"(",
"\".\"",
",",
"relpath_s",
")",
"return",
"relpath_s"
] |
Convert `path` to be relative.
Given a vague relative path, return the path relative to the given
location.
:param str path: The location of a target path
:param str relative_to: The starting path to build against, optional
:returns: A relative posix-style path with a leading `./`
This performs additional conversion to ensure the result is of POSIX form,
and starts with `./`, or is precisely `.`.
>>> os.chdir('/home/user/code/myrepo/myfolder')
>>> vistir.path.get_converted_relative_path('/home/user/code/file.zip')
'./../../file.zip'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder/mysubfolder')
'./mysubfolder'
>>> vistir.path.get_converted_relative_path('/home/user/code/myrepo/myfolder')
'.'
|
[
"Convert",
"path",
"to",
"be",
"relative",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L499-L551
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/response.py
|
is_fp_closed
|
def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check `isclosed()` first, in case Python3 doesn't set `closed`.
# GH Issue #928
return obj.isclosed()
except AttributeError:
pass
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object is a container for another file-like object that
# gets released on exhaustion (e.g. HTTPResponse).
return obj.fp is None
except AttributeError:
pass
raise ValueError("Unable to determine whether fp is closed.")
|
python
|
def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check `isclosed()` first, in case Python3 doesn't set `closed`.
# GH Issue #928
return obj.isclosed()
except AttributeError:
pass
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object is a container for another file-like object that
# gets released on exhaustion (e.g. HTTPResponse).
return obj.fp is None
except AttributeError:
pass
raise ValueError("Unable to determine whether fp is closed.")
|
[
"def",
"is_fp_closed",
"(",
"obj",
")",
":",
"try",
":",
"# Check `isclosed()` first, in case Python3 doesn't set `closed`.",
"# GH Issue #928",
"return",
"obj",
".",
"isclosed",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# Check via the official file-like-object way.",
"return",
"obj",
".",
"closed",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# Check if the object is a container for another file-like object that",
"# gets released on exhaustion (e.g. HTTPResponse).",
"return",
"obj",
".",
"fp",
"is",
"None",
"except",
"AttributeError",
":",
"pass",
"raise",
"ValueError",
"(",
"\"Unable to determine whether fp is closed.\"",
")"
] |
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
|
[
"Checks",
"whether",
"a",
"given",
"file",
"-",
"like",
"object",
"is",
"closed",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/response.py#L7-L35
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/response.py
|
assert_header_parsing
|
def assert_header_parsing(headers):
"""
Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers.
Only works on Python 3.
:param headers: Headers to verify.
:type headers: `httplib.HTTPMessage`.
:raises urllib3.exceptions.HeaderParsingError:
If parsing errors are found.
"""
# This will fail silently if we pass in the wrong kind of parameter.
# To make debugging easier add an explicit check.
if not isinstance(headers, httplib.HTTPMessage):
raise TypeError('expected httplib.Message, got {0}.'.format(
type(headers)))
defects = getattr(headers, 'defects', None)
get_payload = getattr(headers, 'get_payload', None)
unparsed_data = None
if get_payload:
# get_payload is actually email.message.Message.get_payload;
# we're only interested in the result if it's not a multipart message
if not headers.is_multipart():
payload = get_payload()
if isinstance(payload, (bytes, str)):
unparsed_data = payload
if defects or unparsed_data:
raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
|
python
|
def assert_header_parsing(headers):
"""
Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers.
Only works on Python 3.
:param headers: Headers to verify.
:type headers: `httplib.HTTPMessage`.
:raises urllib3.exceptions.HeaderParsingError:
If parsing errors are found.
"""
# This will fail silently if we pass in the wrong kind of parameter.
# To make debugging easier add an explicit check.
if not isinstance(headers, httplib.HTTPMessage):
raise TypeError('expected httplib.Message, got {0}.'.format(
type(headers)))
defects = getattr(headers, 'defects', None)
get_payload = getattr(headers, 'get_payload', None)
unparsed_data = None
if get_payload:
# get_payload is actually email.message.Message.get_payload;
# we're only interested in the result if it's not a multipart message
if not headers.is_multipart():
payload = get_payload()
if isinstance(payload, (bytes, str)):
unparsed_data = payload
if defects or unparsed_data:
raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
|
[
"def",
"assert_header_parsing",
"(",
"headers",
")",
":",
"# This will fail silently if we pass in the wrong kind of parameter.",
"# To make debugging easier add an explicit check.",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"httplib",
".",
"HTTPMessage",
")",
":",
"raise",
"TypeError",
"(",
"'expected httplib.Message, got {0}.'",
".",
"format",
"(",
"type",
"(",
"headers",
")",
")",
")",
"defects",
"=",
"getattr",
"(",
"headers",
",",
"'defects'",
",",
"None",
")",
"get_payload",
"=",
"getattr",
"(",
"headers",
",",
"'get_payload'",
",",
"None",
")",
"unparsed_data",
"=",
"None",
"if",
"get_payload",
":",
"# get_payload is actually email.message.Message.get_payload;",
"# we're only interested in the result if it's not a multipart message",
"if",
"not",
"headers",
".",
"is_multipart",
"(",
")",
":",
"payload",
"=",
"get_payload",
"(",
")",
"if",
"isinstance",
"(",
"payload",
",",
"(",
"bytes",
",",
"str",
")",
")",
":",
"unparsed_data",
"=",
"payload",
"if",
"defects",
"or",
"unparsed_data",
":",
"raise",
"HeaderParsingError",
"(",
"defects",
"=",
"defects",
",",
"unparsed_data",
"=",
"unparsed_data",
")"
] |
Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers.
Only works on Python 3.
:param headers: Headers to verify.
:type headers: `httplib.HTTPMessage`.
:raises urllib3.exceptions.HeaderParsingError:
If parsing errors are found.
|
[
"Asserts",
"whether",
"all",
"headers",
"have",
"been",
"successfully",
"parsed",
".",
"Extracts",
"encountered",
"errors",
"from",
"the",
"result",
"of",
"parsing",
"headers",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/response.py#L38-L72
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/response.py
|
is_response_to_head
|
def is_response_to_head(response):
"""
Checks whether the request of a response has been a HEAD-request.
Handles the quirks of AppEngine.
:param conn:
:type conn: :class:`httplib.HTTPResponse`
"""
# FIXME: Can we do this somehow without accessing private httplib _method?
method = response._method
if isinstance(method, int): # Platform-specific: Appengine
return method == 3
return method.upper() == 'HEAD'
|
python
|
def is_response_to_head(response):
"""
Checks whether the request of a response has been a HEAD-request.
Handles the quirks of AppEngine.
:param conn:
:type conn: :class:`httplib.HTTPResponse`
"""
# FIXME: Can we do this somehow without accessing private httplib _method?
method = response._method
if isinstance(method, int): # Platform-specific: Appengine
return method == 3
return method.upper() == 'HEAD'
|
[
"def",
"is_response_to_head",
"(",
"response",
")",
":",
"# FIXME: Can we do this somehow without accessing private httplib _method?",
"method",
"=",
"response",
".",
"_method",
"if",
"isinstance",
"(",
"method",
",",
"int",
")",
":",
"# Platform-specific: Appengine",
"return",
"method",
"==",
"3",
"return",
"method",
".",
"upper",
"(",
")",
"==",
"'HEAD'"
] |
Checks whether the request of a response has been a HEAD-request.
Handles the quirks of AppEngine.
:param conn:
:type conn: :class:`httplib.HTTPResponse`
|
[
"Checks",
"whether",
"the",
"request",
"of",
"a",
"response",
"has",
"been",
"a",
"HEAD",
"-",
"request",
".",
"Handles",
"the",
"quirks",
"of",
"AppEngine",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/response.py#L75-L87
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.levenshtein_distance
|
def levenshtein_distance(self, a, b):
'''This calculates the Levenshtein distance between a and b.
'''
n, m = len(a), len(b)
if n > m:
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1,m+1):
previous, current = current, [i]+[0]*n
for j in range(1,n+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n]
|
python
|
def levenshtein_distance(self, a, b):
'''This calculates the Levenshtein distance between a and b.
'''
n, m = len(a), len(b)
if n > m:
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1,m+1):
previous, current = current, [i]+[0]*n
for j in range(1,n+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n]
|
[
"def",
"levenshtein_distance",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"n",
",",
"m",
"=",
"len",
"(",
"a",
")",
",",
"len",
"(",
"b",
")",
"if",
"n",
">",
"m",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"n",
",",
"m",
"=",
"m",
",",
"n",
"current",
"=",
"range",
"(",
"n",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"m",
"+",
"1",
")",
":",
"previous",
",",
"current",
"=",
"current",
",",
"[",
"i",
"]",
"+",
"[",
"0",
"]",
"*",
"n",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"n",
"+",
"1",
")",
":",
"add",
",",
"delete",
"=",
"previous",
"[",
"j",
"]",
"+",
"1",
",",
"current",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
"change",
"=",
"previous",
"[",
"j",
"-",
"1",
"]",
"if",
"a",
"[",
"j",
"-",
"1",
"]",
"!=",
"b",
"[",
"i",
"-",
"1",
"]",
":",
"change",
"=",
"change",
"+",
"1",
"current",
"[",
"j",
"]",
"=",
"min",
"(",
"add",
",",
"delete",
",",
"change",
")",
"return",
"current",
"[",
"n",
"]"
] |
This calculates the Levenshtein distance between a and b.
|
[
"This",
"calculates",
"the",
"Levenshtein",
"distance",
"between",
"a",
"and",
"b",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L164-L181
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.try_read_prompt
|
def try_read_prompt(self, timeout_multiplier):
'''This facilitates using communication timeouts to perform
synchronization as quickly as possible, while supporting high latency
connections with a tunable worst case performance. Fast connections
should be read almost immediately. Worst case performance for this
method is timeout_multiplier * 3 seconds.
'''
# maximum time allowed to read the first response
first_char_timeout = timeout_multiplier * 0.5
# maximum time allowed between subsequent characters
inter_char_timeout = timeout_multiplier * 0.1
# maximum time for reading the entire prompt
total_timeout = timeout_multiplier * 3.0
prompt = self.string_type()
begin = time.time()
expired = 0.0
timeout = first_char_timeout
while expired < total_timeout:
try:
prompt += self.read_nonblocking(size=1, timeout=timeout)
expired = time.time() - begin # updated total time expired
timeout = inter_char_timeout
except TIMEOUT:
break
return prompt
|
python
|
def try_read_prompt(self, timeout_multiplier):
'''This facilitates using communication timeouts to perform
synchronization as quickly as possible, while supporting high latency
connections with a tunable worst case performance. Fast connections
should be read almost immediately. Worst case performance for this
method is timeout_multiplier * 3 seconds.
'''
# maximum time allowed to read the first response
first_char_timeout = timeout_multiplier * 0.5
# maximum time allowed between subsequent characters
inter_char_timeout = timeout_multiplier * 0.1
# maximum time for reading the entire prompt
total_timeout = timeout_multiplier * 3.0
prompt = self.string_type()
begin = time.time()
expired = 0.0
timeout = first_char_timeout
while expired < total_timeout:
try:
prompt += self.read_nonblocking(size=1, timeout=timeout)
expired = time.time() - begin # updated total time expired
timeout = inter_char_timeout
except TIMEOUT:
break
return prompt
|
[
"def",
"try_read_prompt",
"(",
"self",
",",
"timeout_multiplier",
")",
":",
"# maximum time allowed to read the first response",
"first_char_timeout",
"=",
"timeout_multiplier",
"*",
"0.5",
"# maximum time allowed between subsequent characters",
"inter_char_timeout",
"=",
"timeout_multiplier",
"*",
"0.1",
"# maximum time for reading the entire prompt",
"total_timeout",
"=",
"timeout_multiplier",
"*",
"3.0",
"prompt",
"=",
"self",
".",
"string_type",
"(",
")",
"begin",
"=",
"time",
".",
"time",
"(",
")",
"expired",
"=",
"0.0",
"timeout",
"=",
"first_char_timeout",
"while",
"expired",
"<",
"total_timeout",
":",
"try",
":",
"prompt",
"+=",
"self",
".",
"read_nonblocking",
"(",
"size",
"=",
"1",
",",
"timeout",
"=",
"timeout",
")",
"expired",
"=",
"time",
".",
"time",
"(",
")",
"-",
"begin",
"# updated total time expired",
"timeout",
"=",
"inter_char_timeout",
"except",
"TIMEOUT",
":",
"break",
"return",
"prompt"
] |
This facilitates using communication timeouts to perform
synchronization as quickly as possible, while supporting high latency
connections with a tunable worst case performance. Fast connections
should be read almost immediately. Worst case performance for this
method is timeout_multiplier * 3 seconds.
|
[
"This",
"facilitates",
"using",
"communication",
"timeouts",
"to",
"perform",
"synchronization",
"as",
"quickly",
"as",
"possible",
"while",
"supporting",
"high",
"latency",
"connections",
"with",
"a",
"tunable",
"worst",
"case",
"performance",
".",
"Fast",
"connections",
"should",
"be",
"read",
"almost",
"immediately",
".",
"Worst",
"case",
"performance",
"for",
"this",
"method",
"is",
"timeout_multiplier",
"*",
"3",
"seconds",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L183-L213
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.sync_original_prompt
|
def sync_original_prompt (self, sync_multiplier=1.0):
'''This attempts to find the prompt. Basically, press enter and record
the response; press enter again and record the response; if the two
responses are similar then assume we are at the original prompt.
This can be a slow function. Worst case with the default sync_multiplier
can take 12 seconds. Low latency connections are more likely to fail
with a low sync_multiplier. Best case sync time gets worse with a
high sync multiplier (500 ms with default). '''
# All of these timing pace values are magic.
# I came up with these based on what seemed reliable for
# connecting to a heavily loaded machine I have.
self.sendline()
time.sleep(0.1)
try:
# Clear the buffer before getting the prompt.
self.try_read_prompt(sync_multiplier)
except TIMEOUT:
pass
self.sendline()
x = self.try_read_prompt(sync_multiplier)
self.sendline()
a = self.try_read_prompt(sync_multiplier)
self.sendline()
b = self.try_read_prompt(sync_multiplier)
ld = self.levenshtein_distance(a,b)
len_a = len(a)
if len_a == 0:
return False
if float(ld)/len_a < 0.4:
return True
return False
|
python
|
def sync_original_prompt (self, sync_multiplier=1.0):
'''This attempts to find the prompt. Basically, press enter and record
the response; press enter again and record the response; if the two
responses are similar then assume we are at the original prompt.
This can be a slow function. Worst case with the default sync_multiplier
can take 12 seconds. Low latency connections are more likely to fail
with a low sync_multiplier. Best case sync time gets worse with a
high sync multiplier (500 ms with default). '''
# All of these timing pace values are magic.
# I came up with these based on what seemed reliable for
# connecting to a heavily loaded machine I have.
self.sendline()
time.sleep(0.1)
try:
# Clear the buffer before getting the prompt.
self.try_read_prompt(sync_multiplier)
except TIMEOUT:
pass
self.sendline()
x = self.try_read_prompt(sync_multiplier)
self.sendline()
a = self.try_read_prompt(sync_multiplier)
self.sendline()
b = self.try_read_prompt(sync_multiplier)
ld = self.levenshtein_distance(a,b)
len_a = len(a)
if len_a == 0:
return False
if float(ld)/len_a < 0.4:
return True
return False
|
[
"def",
"sync_original_prompt",
"(",
"self",
",",
"sync_multiplier",
"=",
"1.0",
")",
":",
"# All of these timing pace values are magic.",
"# I came up with these based on what seemed reliable for",
"# connecting to a heavily loaded machine I have.",
"self",
".",
"sendline",
"(",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"try",
":",
"# Clear the buffer before getting the prompt.",
"self",
".",
"try_read_prompt",
"(",
"sync_multiplier",
")",
"except",
"TIMEOUT",
":",
"pass",
"self",
".",
"sendline",
"(",
")",
"x",
"=",
"self",
".",
"try_read_prompt",
"(",
"sync_multiplier",
")",
"self",
".",
"sendline",
"(",
")",
"a",
"=",
"self",
".",
"try_read_prompt",
"(",
"sync_multiplier",
")",
"self",
".",
"sendline",
"(",
")",
"b",
"=",
"self",
".",
"try_read_prompt",
"(",
"sync_multiplier",
")",
"ld",
"=",
"self",
".",
"levenshtein_distance",
"(",
"a",
",",
"b",
")",
"len_a",
"=",
"len",
"(",
"a",
")",
"if",
"len_a",
"==",
"0",
":",
"return",
"False",
"if",
"float",
"(",
"ld",
")",
"/",
"len_a",
"<",
"0.4",
":",
"return",
"True",
"return",
"False"
] |
This attempts to find the prompt. Basically, press enter and record
the response; press enter again and record the response; if the two
responses are similar then assume we are at the original prompt.
This can be a slow function. Worst case with the default sync_multiplier
can take 12 seconds. Low latency connections are more likely to fail
with a low sync_multiplier. Best case sync time gets worse with a
high sync multiplier (500 ms with default).
|
[
"This",
"attempts",
"to",
"find",
"the",
"prompt",
".",
"Basically",
"press",
"enter",
"and",
"record",
"the",
"response",
";",
"press",
"enter",
"again",
"and",
"record",
"the",
"response",
";",
"if",
"the",
"two",
"responses",
"are",
"similar",
"then",
"assume",
"we",
"are",
"at",
"the",
"original",
"prompt",
".",
"This",
"can",
"be",
"a",
"slow",
"function",
".",
"Worst",
"case",
"with",
"the",
"default",
"sync_multiplier",
"can",
"take",
"12",
"seconds",
".",
"Low",
"latency",
"connections",
"are",
"more",
"likely",
"to",
"fail",
"with",
"a",
"low",
"sync_multiplier",
".",
"Best",
"case",
"sync",
"time",
"gets",
"worse",
"with",
"a",
"high",
"sync",
"multiplier",
"(",
"500",
"ms",
"with",
"default",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L215-L251
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.login
|
def login (self, server, username, password='', terminal_type='ansi',
original_prompt=r"[#$]", login_timeout=10, port=None,
auto_prompt_reset=True, ssh_key=None, quiet=True,
sync_multiplier=1, check_local_ip=True,
password_regex=r'(?i)(?:password:)|(?:passphrase for key)',
ssh_tunnels={}, spawn_local_ssh=True,
sync_original_prompt=True, ssh_config=None):
'''This logs the user into the given server.
It uses
'original_prompt' to try to find the prompt right after login. When it
finds the prompt it immediately tries to reset the prompt to something
more easily matched. The default 'original_prompt' is very optimistic
and is easily fooled. It's more reliable to try to match the original
prompt as exactly as possible to prevent false matches by server
strings such as the "Message Of The Day". On many systems you can
disable the MOTD on the remote server by creating a zero-length file
called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
then this will not necessarily cause the login to fail. In the case of
a timeout when looking for the prompt we assume that the original
prompt was so weird that we could not match it, so we use a few tricks
to guess when we have reached the prompt. Then we hope for the best and
blindly try to reset the prompt to something more unique. If that fails
then login() raises an :class:`ExceptionPxssh` exception.
In some situations it is not possible or desirable to reset the
original prompt. In this case, pass ``auto_prompt_reset=False`` to
inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
uses a unique prompt in the :meth:`prompt` method. If the original prompt is
not reset then this will disable the :meth:`prompt` method unless you
manually set the :attr:`PROMPT` attribute.
Set ``password_regex`` if there is a MOTD message with `password` in it.
Changing this is like playing in traffic, don't (p)expect it to match straight
away.
If you require to connect to another SSH server from the your original SSH
connection set ``spawn_local_ssh`` to `False` and this will use your current
session to do so. Setting this option to `False` and not having an active session
will trigger an error.
Set ``ssh_key`` to a file path to an SSH private key to use that SSH key
for the session authentication.
Set ``ssh_key`` to `True` to force passing the current SSH authentication socket
to the desired ``hostname``.
Set ``ssh_config`` to a file path string of an SSH client config file to pass that
file to the client to handle itself. You may set any options you wish in here, however
doing so will require you to post extra information that you may not want to if you
run into issues.
'''
session_regex_array = ["(?i)are you sure you want to continue connecting", original_prompt, password_regex, "(?i)permission denied", "(?i)terminal type", TIMEOUT]
session_init_regex_array = []
session_init_regex_array.extend(session_regex_array)
session_init_regex_array.extend(["(?i)connection closed by remote host", EOF])
ssh_options = ''.join([" -o '%s=%s'" % (o, v) for (o, v) in self.options.items()])
if quiet:
ssh_options = ssh_options + ' -q'
if not check_local_ip:
ssh_options = ssh_options + " -o'NoHostAuthenticationForLocalhost=yes'"
if self.force_password:
ssh_options = ssh_options + ' ' + self.SSH_OPTS
if ssh_config is not None:
if spawn_local_ssh and not os.path.isfile(ssh_config):
raise ExceptionPxssh('SSH config does not exist or is not a file.')
ssh_options = ssh_options + '-F ' + ssh_config
if port is not None:
ssh_options = ssh_options + ' -p %s'%(str(port))
if ssh_key is not None:
# Allow forwarding our SSH key to the current session
if ssh_key==True:
ssh_options = ssh_options + ' -A'
else:
if spawn_local_ssh and not os.path.isfile(ssh_key):
raise ExceptionPxssh('private ssh key does not exist or is not a file.')
ssh_options = ssh_options + ' -i %s' % (ssh_key)
# SSH tunnels, make sure you know what you're putting into the lists
# under each heading. Do not expect these to open 100% of the time,
# The port you're requesting might be bound.
#
# The structure should be like this:
# { 'local': ['2424:localhost:22'], # Local SSH tunnels
# 'remote': ['2525:localhost:22'], # Remote SSH tunnels
# 'dynamic': [8888] } # Dynamic/SOCKS tunnels
if ssh_tunnels!={} and isinstance({},type(ssh_tunnels)):
tunnel_types = {
'local':'L',
'remote':'R',
'dynamic':'D'
}
for tunnel_type in tunnel_types:
cmd_type = tunnel_types[tunnel_type]
if tunnel_type in ssh_tunnels:
tunnels = ssh_tunnels[tunnel_type]
for tunnel in tunnels:
if spawn_local_ssh==False:
tunnel = quote(str(tunnel))
ssh_options = ssh_options + ' -' + cmd_type + ' ' + str(tunnel)
cmd = "ssh %s -l %s %s" % (ssh_options, username, server)
if self.debug_command_string:
return(cmd)
# Are we asking for a local ssh command or to spawn one in another session?
if spawn_local_ssh:
spawn._spawn(self, cmd)
else:
self.sendline(cmd)
# This does not distinguish between a remote server 'password' prompt
# and a local ssh 'passphrase' prompt (for unlocking a private key).
i = self.expect(session_init_regex_array, timeout=login_timeout)
# First phase
if i==0:
# New certificate -- always accept it.
# This is what you get if SSH does not have the remote host's
# public key stored in the 'known_hosts' cache.
self.sendline("yes")
i = self.expect(session_regex_array)
if i==2: # password or passphrase
self.sendline(password)
i = self.expect(session_regex_array)
if i==4:
self.sendline(terminal_type)
i = self.expect(session_regex_array)
if i==7:
self.close()
raise ExceptionPxssh('Could not establish connection to host')
# Second phase
if i==0:
# This is weird. This should not happen twice in a row.
self.close()
raise ExceptionPxssh('Weird error. Got "are you sure" prompt twice.')
elif i==1: # can occur if you have a public key pair set to authenticate.
### TODO: May NOT be OK if expect() got tricked and matched a false prompt.
pass
elif i==2: # password prompt again
# For incorrect passwords, some ssh servers will
# ask for the password again, others return 'denied' right away.
# If we get the password prompt again then this means
# we didn't get the password right the first time.
self.close()
raise ExceptionPxssh('password refused')
elif i==3: # permission denied -- password was bad.
self.close()
raise ExceptionPxssh('permission denied')
elif i==4: # terminal type again? WTF?
self.close()
raise ExceptionPxssh('Weird error. Got "terminal type" prompt twice.')
elif i==5: # Timeout
#This is tricky... I presume that we are at the command-line prompt.
#It may be that the shell prompt was so weird that we couldn't match
#it. Or it may be that we couldn't log in for some other reason. I
#can't be sure, but it's safe to guess that we did login because if
#I presume wrong and we are not logged in then this should be caught
#later when I try to set the shell prompt.
pass
elif i==6: # Connection closed by remote host
self.close()
raise ExceptionPxssh('connection closed')
else: # Unexpected
self.close()
raise ExceptionPxssh('unexpected login response')
if sync_original_prompt:
if not self.sync_original_prompt(sync_multiplier):
self.close()
raise ExceptionPxssh('could not synchronize with original prompt')
# We appear to be in.
# set shell prompt to something unique.
if auto_prompt_reset:
if not self.set_unique_prompt():
self.close()
raise ExceptionPxssh('could not set shell prompt '
'(received: %r, expected: %r).' % (
self.before, self.PROMPT,))
return True
|
python
|
def login (self, server, username, password='', terminal_type='ansi',
original_prompt=r"[#$]", login_timeout=10, port=None,
auto_prompt_reset=True, ssh_key=None, quiet=True,
sync_multiplier=1, check_local_ip=True,
password_regex=r'(?i)(?:password:)|(?:passphrase for key)',
ssh_tunnels={}, spawn_local_ssh=True,
sync_original_prompt=True, ssh_config=None):
'''This logs the user into the given server.
It uses
'original_prompt' to try to find the prompt right after login. When it
finds the prompt it immediately tries to reset the prompt to something
more easily matched. The default 'original_prompt' is very optimistic
and is easily fooled. It's more reliable to try to match the original
prompt as exactly as possible to prevent false matches by server
strings such as the "Message Of The Day". On many systems you can
disable the MOTD on the remote server by creating a zero-length file
called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
then this will not necessarily cause the login to fail. In the case of
a timeout when looking for the prompt we assume that the original
prompt was so weird that we could not match it, so we use a few tricks
to guess when we have reached the prompt. Then we hope for the best and
blindly try to reset the prompt to something more unique. If that fails
then login() raises an :class:`ExceptionPxssh` exception.
In some situations it is not possible or desirable to reset the
original prompt. In this case, pass ``auto_prompt_reset=False`` to
inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
uses a unique prompt in the :meth:`prompt` method. If the original prompt is
not reset then this will disable the :meth:`prompt` method unless you
manually set the :attr:`PROMPT` attribute.
Set ``password_regex`` if there is a MOTD message with `password` in it.
Changing this is like playing in traffic, don't (p)expect it to match straight
away.
If you require to connect to another SSH server from the your original SSH
connection set ``spawn_local_ssh`` to `False` and this will use your current
session to do so. Setting this option to `False` and not having an active session
will trigger an error.
Set ``ssh_key`` to a file path to an SSH private key to use that SSH key
for the session authentication.
Set ``ssh_key`` to `True` to force passing the current SSH authentication socket
to the desired ``hostname``.
Set ``ssh_config`` to a file path string of an SSH client config file to pass that
file to the client to handle itself. You may set any options you wish in here, however
doing so will require you to post extra information that you may not want to if you
run into issues.
'''
session_regex_array = ["(?i)are you sure you want to continue connecting", original_prompt, password_regex, "(?i)permission denied", "(?i)terminal type", TIMEOUT]
session_init_regex_array = []
session_init_regex_array.extend(session_regex_array)
session_init_regex_array.extend(["(?i)connection closed by remote host", EOF])
ssh_options = ''.join([" -o '%s=%s'" % (o, v) for (o, v) in self.options.items()])
if quiet:
ssh_options = ssh_options + ' -q'
if not check_local_ip:
ssh_options = ssh_options + " -o'NoHostAuthenticationForLocalhost=yes'"
if self.force_password:
ssh_options = ssh_options + ' ' + self.SSH_OPTS
if ssh_config is not None:
if spawn_local_ssh and not os.path.isfile(ssh_config):
raise ExceptionPxssh('SSH config does not exist or is not a file.')
ssh_options = ssh_options + '-F ' + ssh_config
if port is not None:
ssh_options = ssh_options + ' -p %s'%(str(port))
if ssh_key is not None:
# Allow forwarding our SSH key to the current session
if ssh_key==True:
ssh_options = ssh_options + ' -A'
else:
if spawn_local_ssh and not os.path.isfile(ssh_key):
raise ExceptionPxssh('private ssh key does not exist or is not a file.')
ssh_options = ssh_options + ' -i %s' % (ssh_key)
# SSH tunnels, make sure you know what you're putting into the lists
# under each heading. Do not expect these to open 100% of the time,
# The port you're requesting might be bound.
#
# The structure should be like this:
# { 'local': ['2424:localhost:22'], # Local SSH tunnels
# 'remote': ['2525:localhost:22'], # Remote SSH tunnels
# 'dynamic': [8888] } # Dynamic/SOCKS tunnels
if ssh_tunnels!={} and isinstance({},type(ssh_tunnels)):
tunnel_types = {
'local':'L',
'remote':'R',
'dynamic':'D'
}
for tunnel_type in tunnel_types:
cmd_type = tunnel_types[tunnel_type]
if tunnel_type in ssh_tunnels:
tunnels = ssh_tunnels[tunnel_type]
for tunnel in tunnels:
if spawn_local_ssh==False:
tunnel = quote(str(tunnel))
ssh_options = ssh_options + ' -' + cmd_type + ' ' + str(tunnel)
cmd = "ssh %s -l %s %s" % (ssh_options, username, server)
if self.debug_command_string:
return(cmd)
# Are we asking for a local ssh command or to spawn one in another session?
if spawn_local_ssh:
spawn._spawn(self, cmd)
else:
self.sendline(cmd)
# This does not distinguish between a remote server 'password' prompt
# and a local ssh 'passphrase' prompt (for unlocking a private key).
i = self.expect(session_init_regex_array, timeout=login_timeout)
# First phase
if i==0:
# New certificate -- always accept it.
# This is what you get if SSH does not have the remote host's
# public key stored in the 'known_hosts' cache.
self.sendline("yes")
i = self.expect(session_regex_array)
if i==2: # password or passphrase
self.sendline(password)
i = self.expect(session_regex_array)
if i==4:
self.sendline(terminal_type)
i = self.expect(session_regex_array)
if i==7:
self.close()
raise ExceptionPxssh('Could not establish connection to host')
# Second phase
if i==0:
# This is weird. This should not happen twice in a row.
self.close()
raise ExceptionPxssh('Weird error. Got "are you sure" prompt twice.')
elif i==1: # can occur if you have a public key pair set to authenticate.
### TODO: May NOT be OK if expect() got tricked and matched a false prompt.
pass
elif i==2: # password prompt again
# For incorrect passwords, some ssh servers will
# ask for the password again, others return 'denied' right away.
# If we get the password prompt again then this means
# we didn't get the password right the first time.
self.close()
raise ExceptionPxssh('password refused')
elif i==3: # permission denied -- password was bad.
self.close()
raise ExceptionPxssh('permission denied')
elif i==4: # terminal type again? WTF?
self.close()
raise ExceptionPxssh('Weird error. Got "terminal type" prompt twice.')
elif i==5: # Timeout
#This is tricky... I presume that we are at the command-line prompt.
#It may be that the shell prompt was so weird that we couldn't match
#it. Or it may be that we couldn't log in for some other reason. I
#can't be sure, but it's safe to guess that we did login because if
#I presume wrong and we are not logged in then this should be caught
#later when I try to set the shell prompt.
pass
elif i==6: # Connection closed by remote host
self.close()
raise ExceptionPxssh('connection closed')
else: # Unexpected
self.close()
raise ExceptionPxssh('unexpected login response')
if sync_original_prompt:
if not self.sync_original_prompt(sync_multiplier):
self.close()
raise ExceptionPxssh('could not synchronize with original prompt')
# We appear to be in.
# set shell prompt to something unique.
if auto_prompt_reset:
if not self.set_unique_prompt():
self.close()
raise ExceptionPxssh('could not set shell prompt '
'(received: %r, expected: %r).' % (
self.before, self.PROMPT,))
return True
|
[
"def",
"login",
"(",
"self",
",",
"server",
",",
"username",
",",
"password",
"=",
"''",
",",
"terminal_type",
"=",
"'ansi'",
",",
"original_prompt",
"=",
"r\"[#$]\"",
",",
"login_timeout",
"=",
"10",
",",
"port",
"=",
"None",
",",
"auto_prompt_reset",
"=",
"True",
",",
"ssh_key",
"=",
"None",
",",
"quiet",
"=",
"True",
",",
"sync_multiplier",
"=",
"1",
",",
"check_local_ip",
"=",
"True",
",",
"password_regex",
"=",
"r'(?i)(?:password:)|(?:passphrase for key)'",
",",
"ssh_tunnels",
"=",
"{",
"}",
",",
"spawn_local_ssh",
"=",
"True",
",",
"sync_original_prompt",
"=",
"True",
",",
"ssh_config",
"=",
"None",
")",
":",
"session_regex_array",
"=",
"[",
"\"(?i)are you sure you want to continue connecting\"",
",",
"original_prompt",
",",
"password_regex",
",",
"\"(?i)permission denied\"",
",",
"\"(?i)terminal type\"",
",",
"TIMEOUT",
"]",
"session_init_regex_array",
"=",
"[",
"]",
"session_init_regex_array",
".",
"extend",
"(",
"session_regex_array",
")",
"session_init_regex_array",
".",
"extend",
"(",
"[",
"\"(?i)connection closed by remote host\"",
",",
"EOF",
"]",
")",
"ssh_options",
"=",
"''",
".",
"join",
"(",
"[",
"\" -o '%s=%s'\"",
"%",
"(",
"o",
",",
"v",
")",
"for",
"(",
"o",
",",
"v",
")",
"in",
"self",
".",
"options",
".",
"items",
"(",
")",
"]",
")",
"if",
"quiet",
":",
"ssh_options",
"=",
"ssh_options",
"+",
"' -q'",
"if",
"not",
"check_local_ip",
":",
"ssh_options",
"=",
"ssh_options",
"+",
"\" -o'NoHostAuthenticationForLocalhost=yes'\"",
"if",
"self",
".",
"force_password",
":",
"ssh_options",
"=",
"ssh_options",
"+",
"' '",
"+",
"self",
".",
"SSH_OPTS",
"if",
"ssh_config",
"is",
"not",
"None",
":",
"if",
"spawn_local_ssh",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"ssh_config",
")",
":",
"raise",
"ExceptionPxssh",
"(",
"'SSH config does not exist or is not a file.'",
")",
"ssh_options",
"=",
"ssh_options",
"+",
"'-F '",
"+",
"ssh_config",
"if",
"port",
"is",
"not",
"None",
":",
"ssh_options",
"=",
"ssh_options",
"+",
"' -p %s'",
"%",
"(",
"str",
"(",
"port",
")",
")",
"if",
"ssh_key",
"is",
"not",
"None",
":",
"# Allow forwarding our SSH key to the current session",
"if",
"ssh_key",
"==",
"True",
":",
"ssh_options",
"=",
"ssh_options",
"+",
"' -A'",
"else",
":",
"if",
"spawn_local_ssh",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"ssh_key",
")",
":",
"raise",
"ExceptionPxssh",
"(",
"'private ssh key does not exist or is not a file.'",
")",
"ssh_options",
"=",
"ssh_options",
"+",
"' -i %s'",
"%",
"(",
"ssh_key",
")",
"# SSH tunnels, make sure you know what you're putting into the lists",
"# under each heading. Do not expect these to open 100% of the time,",
"# The port you're requesting might be bound.",
"#",
"# The structure should be like this:",
"# { 'local': ['2424:localhost:22'], # Local SSH tunnels",
"# 'remote': ['2525:localhost:22'], # Remote SSH tunnels",
"# 'dynamic': [8888] } # Dynamic/SOCKS tunnels",
"if",
"ssh_tunnels",
"!=",
"{",
"}",
"and",
"isinstance",
"(",
"{",
"}",
",",
"type",
"(",
"ssh_tunnels",
")",
")",
":",
"tunnel_types",
"=",
"{",
"'local'",
":",
"'L'",
",",
"'remote'",
":",
"'R'",
",",
"'dynamic'",
":",
"'D'",
"}",
"for",
"tunnel_type",
"in",
"tunnel_types",
":",
"cmd_type",
"=",
"tunnel_types",
"[",
"tunnel_type",
"]",
"if",
"tunnel_type",
"in",
"ssh_tunnels",
":",
"tunnels",
"=",
"ssh_tunnels",
"[",
"tunnel_type",
"]",
"for",
"tunnel",
"in",
"tunnels",
":",
"if",
"spawn_local_ssh",
"==",
"False",
":",
"tunnel",
"=",
"quote",
"(",
"str",
"(",
"tunnel",
")",
")",
"ssh_options",
"=",
"ssh_options",
"+",
"' -'",
"+",
"cmd_type",
"+",
"' '",
"+",
"str",
"(",
"tunnel",
")",
"cmd",
"=",
"\"ssh %s -l %s %s\"",
"%",
"(",
"ssh_options",
",",
"username",
",",
"server",
")",
"if",
"self",
".",
"debug_command_string",
":",
"return",
"(",
"cmd",
")",
"# Are we asking for a local ssh command or to spawn one in another session?",
"if",
"spawn_local_ssh",
":",
"spawn",
".",
"_spawn",
"(",
"self",
",",
"cmd",
")",
"else",
":",
"self",
".",
"sendline",
"(",
"cmd",
")",
"# This does not distinguish between a remote server 'password' prompt",
"# and a local ssh 'passphrase' prompt (for unlocking a private key).",
"i",
"=",
"self",
".",
"expect",
"(",
"session_init_regex_array",
",",
"timeout",
"=",
"login_timeout",
")",
"# First phase",
"if",
"i",
"==",
"0",
":",
"# New certificate -- always accept it.",
"# This is what you get if SSH does not have the remote host's",
"# public key stored in the 'known_hosts' cache.",
"self",
".",
"sendline",
"(",
"\"yes\"",
")",
"i",
"=",
"self",
".",
"expect",
"(",
"session_regex_array",
")",
"if",
"i",
"==",
"2",
":",
"# password or passphrase",
"self",
".",
"sendline",
"(",
"password",
")",
"i",
"=",
"self",
".",
"expect",
"(",
"session_regex_array",
")",
"if",
"i",
"==",
"4",
":",
"self",
".",
"sendline",
"(",
"terminal_type",
")",
"i",
"=",
"self",
".",
"expect",
"(",
"session_regex_array",
")",
"if",
"i",
"==",
"7",
":",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'Could not establish connection to host'",
")",
"# Second phase",
"if",
"i",
"==",
"0",
":",
"# This is weird. This should not happen twice in a row.",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'Weird error. Got \"are you sure\" prompt twice.'",
")",
"elif",
"i",
"==",
"1",
":",
"# can occur if you have a public key pair set to authenticate.",
"### TODO: May NOT be OK if expect() got tricked and matched a false prompt.",
"pass",
"elif",
"i",
"==",
"2",
":",
"# password prompt again",
"# For incorrect passwords, some ssh servers will",
"# ask for the password again, others return 'denied' right away.",
"# If we get the password prompt again then this means",
"# we didn't get the password right the first time.",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'password refused'",
")",
"elif",
"i",
"==",
"3",
":",
"# permission denied -- password was bad.",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'permission denied'",
")",
"elif",
"i",
"==",
"4",
":",
"# terminal type again? WTF?",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'Weird error. Got \"terminal type\" prompt twice.'",
")",
"elif",
"i",
"==",
"5",
":",
"# Timeout",
"#This is tricky... I presume that we are at the command-line prompt.",
"#It may be that the shell prompt was so weird that we couldn't match",
"#it. Or it may be that we couldn't log in for some other reason. I",
"#can't be sure, but it's safe to guess that we did login because if",
"#I presume wrong and we are not logged in then this should be caught",
"#later when I try to set the shell prompt.",
"pass",
"elif",
"i",
"==",
"6",
":",
"# Connection closed by remote host",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'connection closed'",
")",
"else",
":",
"# Unexpected",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'unexpected login response'",
")",
"if",
"sync_original_prompt",
":",
"if",
"not",
"self",
".",
"sync_original_prompt",
"(",
"sync_multiplier",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'could not synchronize with original prompt'",
")",
"# We appear to be in.",
"# set shell prompt to something unique.",
"if",
"auto_prompt_reset",
":",
"if",
"not",
"self",
".",
"set_unique_prompt",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"ExceptionPxssh",
"(",
"'could not set shell prompt '",
"'(received: %r, expected: %r).'",
"%",
"(",
"self",
".",
"before",
",",
"self",
".",
"PROMPT",
",",
")",
")",
"return",
"True"
] |
This logs the user into the given server.
It uses
'original_prompt' to try to find the prompt right after login. When it
finds the prompt it immediately tries to reset the prompt to something
more easily matched. The default 'original_prompt' is very optimistic
and is easily fooled. It's more reliable to try to match the original
prompt as exactly as possible to prevent false matches by server
strings such as the "Message Of The Day". On many systems you can
disable the MOTD on the remote server by creating a zero-length file
called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
then this will not necessarily cause the login to fail. In the case of
a timeout when looking for the prompt we assume that the original
prompt was so weird that we could not match it, so we use a few tricks
to guess when we have reached the prompt. Then we hope for the best and
blindly try to reset the prompt to something more unique. If that fails
then login() raises an :class:`ExceptionPxssh` exception.
In some situations it is not possible or desirable to reset the
original prompt. In this case, pass ``auto_prompt_reset=False`` to
inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
uses a unique prompt in the :meth:`prompt` method. If the original prompt is
not reset then this will disable the :meth:`prompt` method unless you
manually set the :attr:`PROMPT` attribute.
Set ``password_regex`` if there is a MOTD message with `password` in it.
Changing this is like playing in traffic, don't (p)expect it to match straight
away.
If you require to connect to another SSH server from the your original SSH
connection set ``spawn_local_ssh`` to `False` and this will use your current
session to do so. Setting this option to `False` and not having an active session
will trigger an error.
Set ``ssh_key`` to a file path to an SSH private key to use that SSH key
for the session authentication.
Set ``ssh_key`` to `True` to force passing the current SSH authentication socket
to the desired ``hostname``.
Set ``ssh_config`` to a file path string of an SSH client config file to pass that
file to the client to handle itself. You may set any options you wish in here, however
doing so will require you to post extra information that you may not want to if you
run into issues.
|
[
"This",
"logs",
"the",
"user",
"into",
"the",
"given",
"server",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L256-L435
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.logout
|
def logout (self):
'''Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice.
'''
self.sendline("exit")
index = self.expect([EOF, "(?i)there are stopped jobs"])
if index==1:
self.sendline("exit")
self.expect(EOF)
self.close()
|
python
|
def logout (self):
'''Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice.
'''
self.sendline("exit")
index = self.expect([EOF, "(?i)there are stopped jobs"])
if index==1:
self.sendline("exit")
self.expect(EOF)
self.close()
|
[
"def",
"logout",
"(",
"self",
")",
":",
"self",
".",
"sendline",
"(",
"\"exit\"",
")",
"index",
"=",
"self",
".",
"expect",
"(",
"[",
"EOF",
",",
"\"(?i)there are stopped jobs\"",
"]",
")",
"if",
"index",
"==",
"1",
":",
"self",
".",
"sendline",
"(",
"\"exit\"",
")",
"self",
".",
"expect",
"(",
"EOF",
")",
"self",
".",
"close",
"(",
")"
] |
Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice.
|
[
"Sends",
"exit",
"to",
"the",
"remote",
"shell",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L437-L447
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.prompt
|
def prompt(self, timeout=-1):
'''Match the next shell prompt.
This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
method. Note that if you called :meth:`login` with
``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
set the :attr:`PROMPT` attribute to a regex that it will use for
matching the prompt.
Calling :meth:`prompt` will erase the contents of the :attr:`before`
attribute even if no prompt is ever matched. If timeout is not given or
it is set to -1 then self.timeout is used.
:return: True if the shell prompt was matched, False if the timeout was
reached.
'''
if timeout == -1:
timeout = self.timeout
i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
if i==1:
return False
return True
|
python
|
def prompt(self, timeout=-1):
'''Match the next shell prompt.
This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
method. Note that if you called :meth:`login` with
``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
set the :attr:`PROMPT` attribute to a regex that it will use for
matching the prompt.
Calling :meth:`prompt` will erase the contents of the :attr:`before`
attribute even if no prompt is ever matched. If timeout is not given or
it is set to -1 then self.timeout is used.
:return: True if the shell prompt was matched, False if the timeout was
reached.
'''
if timeout == -1:
timeout = self.timeout
i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
if i==1:
return False
return True
|
[
"def",
"prompt",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"self",
".",
"PROMPT",
",",
"TIMEOUT",
"]",
",",
"timeout",
"=",
"timeout",
")",
"if",
"i",
"==",
"1",
":",
"return",
"False",
"return",
"True"
] |
Match the next shell prompt.
This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
method. Note that if you called :meth:`login` with
``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
set the :attr:`PROMPT` attribute to a regex that it will use for
matching the prompt.
Calling :meth:`prompt` will erase the contents of the :attr:`before`
attribute even if no prompt is ever matched. If timeout is not given or
it is set to -1 then self.timeout is used.
:return: True if the shell prompt was matched, False if the timeout was
reached.
|
[
"Match",
"the",
"next",
"shell",
"prompt",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L449-L471
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/pxssh.py
|
pxssh.set_unique_prompt
|
def set_unique_prompt(self):
'''This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands.
Alternatively, you may use your own prompt pattern. In this case you
should call :meth:`login` with ``auto_prompt_reset=False``; then set the
:attr:`PROMPT` attribute to a regular expression. After that, the
:meth:`prompt` method will try to match your prompt pattern.
'''
self.sendline("unset PROMPT_COMMAND")
self.sendline(self.PROMPT_SET_SH) # sh-style
i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
if i == 0: # csh-style
self.sendline(self.PROMPT_SET_CSH)
i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
if i == 0:
return False
return True
|
python
|
def set_unique_prompt(self):
'''This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands.
Alternatively, you may use your own prompt pattern. In this case you
should call :meth:`login` with ``auto_prompt_reset=False``; then set the
:attr:`PROMPT` attribute to a regular expression. After that, the
:meth:`prompt` method will try to match your prompt pattern.
'''
self.sendline("unset PROMPT_COMMAND")
self.sendline(self.PROMPT_SET_SH) # sh-style
i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
if i == 0: # csh-style
self.sendline(self.PROMPT_SET_CSH)
i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
if i == 0:
return False
return True
|
[
"def",
"set_unique_prompt",
"(",
"self",
")",
":",
"self",
".",
"sendline",
"(",
"\"unset PROMPT_COMMAND\"",
")",
"self",
".",
"sendline",
"(",
"self",
".",
"PROMPT_SET_SH",
")",
"# sh-style",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"TIMEOUT",
",",
"self",
".",
"PROMPT",
"]",
",",
"timeout",
"=",
"10",
")",
"if",
"i",
"==",
"0",
":",
"# csh-style",
"self",
".",
"sendline",
"(",
"self",
".",
"PROMPT_SET_CSH",
")",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"TIMEOUT",
",",
"self",
".",
"PROMPT",
"]",
",",
"timeout",
"=",
"10",
")",
"if",
"i",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] |
This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands.
Alternatively, you may use your own prompt pattern. In this case you
should call :meth:`login` with ``auto_prompt_reset=False``; then set the
:attr:`PROMPT` attribute to a regular expression. After that, the
:meth:`prompt` method will try to match your prompt pattern.
|
[
"This",
"sets",
"the",
"remote",
"prompt",
"to",
"something",
"more",
"unique",
"than",
"#",
"or",
"$",
".",
"This",
"makes",
"it",
"easier",
"for",
"the",
":",
"meth",
":",
"prompt",
"method",
"to",
"match",
"the",
"shell",
"prompt",
"unambiguously",
".",
"This",
"method",
"is",
"called",
"automatically",
"by",
"the",
":",
"meth",
":",
"login",
"method",
"but",
"you",
"may",
"want",
"to",
"call",
"it",
"manually",
"if",
"you",
"somehow",
"reset",
"the",
"shell",
"prompt",
".",
"For",
"example",
"if",
"you",
"su",
"to",
"a",
"different",
"user",
"then",
"you",
"will",
"need",
"to",
"manually",
"reset",
"the",
"prompt",
".",
"This",
"sends",
"shell",
"commands",
"to",
"the",
"remote",
"host",
"to",
"set",
"the",
"prompt",
"so",
"this",
"assumes",
"the",
"remote",
"host",
"is",
"ready",
"to",
"receive",
"commands",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pxssh.py#L473-L497
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
user_agent
|
def user_agent():
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": pipenv.patched.notpip.__version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["implementation"]["name"] == 'CPython':
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'PyPy':
if sys.pypy_version_info.releaselevel == 'final':
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data["implementation"]["version"] = ".".join(
[str(x) for x in pypy_version_info]
)
elif data["implementation"]["name"] == 'Jython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'IronPython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
if sys.platform.startswith("linux"):
from pipenv.patched.notpip._vendor import distro
distro_infos = dict(filter(
lambda x: x[1],
zip(["name", "version", "id"], distro.linux_distribution()),
))
libc = dict(filter(
lambda x: x[1],
zip(["lib", "version"], libc_ver()),
))
if libc:
distro_infos["libc"] = libc
if distro_infos:
data["distro"] = distro_infos
if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
if platform.system():
data.setdefault("system", {})["name"] = platform.system()
if platform.release():
data.setdefault("system", {})["release"] = platform.release()
if platform.machine():
data["cpu"] = platform.machine()
if HAS_TLS:
data["openssl_version"] = ssl.OPENSSL_VERSION
setuptools_version = get_installed_version("setuptools")
if setuptools_version is not None:
data["setuptools_version"] = setuptools_version
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
)
|
python
|
def user_agent():
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": pipenv.patched.notpip.__version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["implementation"]["name"] == 'CPython':
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'PyPy':
if sys.pypy_version_info.releaselevel == 'final':
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data["implementation"]["version"] = ".".join(
[str(x) for x in pypy_version_info]
)
elif data["implementation"]["name"] == 'Jython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'IronPython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
if sys.platform.startswith("linux"):
from pipenv.patched.notpip._vendor import distro
distro_infos = dict(filter(
lambda x: x[1],
zip(["name", "version", "id"], distro.linux_distribution()),
))
libc = dict(filter(
lambda x: x[1],
zip(["lib", "version"], libc_ver()),
))
if libc:
distro_infos["libc"] = libc
if distro_infos:
data["distro"] = distro_infos
if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
if platform.system():
data.setdefault("system", {})["name"] = platform.system()
if platform.release():
data.setdefault("system", {})["release"] = platform.release()
if platform.machine():
data["cpu"] = platform.machine()
if HAS_TLS:
data["openssl_version"] = ssl.OPENSSL_VERSION
setuptools_version = get_installed_version("setuptools")
if setuptools_version is not None:
data["setuptools_version"] = setuptools_version
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
)
|
[
"def",
"user_agent",
"(",
")",
":",
"data",
"=",
"{",
"\"installer\"",
":",
"{",
"\"name\"",
":",
"\"pip\"",
",",
"\"version\"",
":",
"pipenv",
".",
"patched",
".",
"notpip",
".",
"__version__",
"}",
",",
"\"python\"",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"\"implementation\"",
":",
"{",
"\"name\"",
":",
"platform",
".",
"python_implementation",
"(",
")",
",",
"}",
",",
"}",
"if",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'CPython'",
":",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'PyPy'",
":",
"if",
"sys",
".",
"pypy_version_info",
".",
"releaselevel",
"==",
"'final'",
":",
"pypy_version_info",
"=",
"sys",
".",
"pypy_version_info",
"[",
":",
"3",
"]",
"else",
":",
"pypy_version_info",
"=",
"sys",
".",
"pypy_version_info",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"\".\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"pypy_version_info",
"]",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'Jython'",
":",
"# Complete Guess",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'IronPython'",
":",
"# Complete Guess",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
":",
"from",
"pipenv",
".",
"patched",
".",
"notpip",
".",
"_vendor",
"import",
"distro",
"distro_infos",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"zip",
"(",
"[",
"\"name\"",
",",
"\"version\"",
",",
"\"id\"",
"]",
",",
"distro",
".",
"linux_distribution",
"(",
")",
")",
",",
")",
")",
"libc",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"zip",
"(",
"[",
"\"lib\"",
",",
"\"version\"",
"]",
",",
"libc_ver",
"(",
")",
")",
",",
")",
")",
"if",
"libc",
":",
"distro_infos",
"[",
"\"libc\"",
"]",
"=",
"libc",
"if",
"distro_infos",
":",
"data",
"[",
"\"distro\"",
"]",
"=",
"distro_infos",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"darwin\"",
")",
"and",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
":",
"data",
"[",
"\"distro\"",
"]",
"=",
"{",
"\"name\"",
":",
"\"macOS\"",
",",
"\"version\"",
":",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
"}",
"if",
"platform",
".",
"system",
"(",
")",
":",
"data",
".",
"setdefault",
"(",
"\"system\"",
",",
"{",
"}",
")",
"[",
"\"name\"",
"]",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"platform",
".",
"release",
"(",
")",
":",
"data",
".",
"setdefault",
"(",
"\"system\"",
",",
"{",
"}",
")",
"[",
"\"release\"",
"]",
"=",
"platform",
".",
"release",
"(",
")",
"if",
"platform",
".",
"machine",
"(",
")",
":",
"data",
"[",
"\"cpu\"",
"]",
"=",
"platform",
".",
"machine",
"(",
")",
"if",
"HAS_TLS",
":",
"data",
"[",
"\"openssl_version\"",
"]",
"=",
"ssl",
".",
"OPENSSL_VERSION",
"setuptools_version",
"=",
"get_installed_version",
"(",
"\"setuptools\"",
")",
"if",
"setuptools_version",
"is",
"not",
"None",
":",
"data",
"[",
"\"setuptools_version\"",
"]",
"=",
"setuptools_version",
"return",
"\"{data[installer][name]}/{data[installer][version]} {json}\"",
".",
"format",
"(",
"data",
"=",
"data",
",",
"json",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
",",
"sort_keys",
"=",
"True",
")",
",",
")"
] |
Return a string representing the user agent.
|
[
"Return",
"a",
"string",
"representing",
"the",
"user",
"agent",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L75-L141
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
url_to_path
|
def url_to_path(url):
# type: (str) -> str
"""
Convert a file: URL to a path.
"""
assert url.startswith('file:'), (
"You can only turn file: urls into filenames (not %r)" % url)
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# if we have a UNC path, prepend UNC share notation
if netloc:
netloc = '\\\\' + netloc
path = urllib_request.url2pathname(netloc + path)
return path
|
python
|
def url_to_path(url):
# type: (str) -> str
"""
Convert a file: URL to a path.
"""
assert url.startswith('file:'), (
"You can only turn file: urls into filenames (not %r)" % url)
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# if we have a UNC path, prepend UNC share notation
if netloc:
netloc = '\\\\' + netloc
path = urllib_request.url2pathname(netloc + path)
return path
|
[
"def",
"url_to_path",
"(",
"url",
")",
":",
"# type: (str) -> str",
"assert",
"url",
".",
"startswith",
"(",
"'file:'",
")",
",",
"(",
"\"You can only turn file: urls into filenames (not %r)\"",
"%",
"url",
")",
"_",
",",
"netloc",
",",
"path",
",",
"_",
",",
"_",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"# if we have a UNC path, prepend UNC share notation",
"if",
"netloc",
":",
"netloc",
"=",
"'\\\\\\\\'",
"+",
"netloc",
"path",
"=",
"urllib_request",
".",
"url2pathname",
"(",
"netloc",
"+",
"path",
")",
"return",
"path"
] |
Convert a file: URL to a path.
|
[
"Convert",
"a",
"file",
":",
"URL",
"to",
"a",
"path",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L466-L481
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
path_to_url
|
def path_to_url(path):
# type: (Union[str, Text]) -> str
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path))
return url
|
python
|
def path_to_url(path):
# type: (Union[str, Text]) -> str
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path))
return url
|
[
"def",
"path_to_url",
"(",
"path",
")",
":",
"# type: (Union[str, Text]) -> str",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"url",
"=",
"urllib_parse",
".",
"urljoin",
"(",
"'file:'",
",",
"urllib_request",
".",
"pathname2url",
"(",
"path",
")",
")",
"return",
"url"
] |
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
|
[
"Convert",
"a",
"path",
"to",
"a",
"file",
":",
"URL",
".",
"The",
"path",
"will",
"be",
"made",
"absolute",
"and",
"have",
"quoted",
"path",
"parts",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L484-L492
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
is_archive_file
|
def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file."""
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False
|
python
|
def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file."""
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False
|
[
"def",
"is_archive_file",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"return",
"True",
"return",
"False"
] |
Return True if `name` is a considered as an archive file.
|
[
"Return",
"True",
"if",
"name",
"is",
"a",
"considered",
"as",
"an",
"archive",
"file",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L495-L501
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
is_dir_url
|
def is_dir_url(link):
# type: (Link) -> bool
"""Return whether a file:// Link points to a directory.
``link`` must not have any other scheme but file://. Call is_file_url()
first.
"""
link_path = url_to_path(link.url_without_fragment)
return os.path.isdir(link_path)
|
python
|
def is_dir_url(link):
# type: (Link) -> bool
"""Return whether a file:// Link points to a directory.
``link`` must not have any other scheme but file://. Call is_file_url()
first.
"""
link_path = url_to_path(link.url_without_fragment)
return os.path.isdir(link_path)
|
[
"def",
"is_dir_url",
"(",
"link",
")",
":",
"# type: (Link) -> bool",
"link_path",
"=",
"url_to_path",
"(",
"link",
".",
"url_without_fragment",
")",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"link_path",
")"
] |
Return whether a file:// Link points to a directory.
``link`` must not have any other scheme but file://. Call is_file_url()
first.
|
[
"Return",
"whether",
"a",
"file",
":",
"//",
"Link",
"points",
"to",
"a",
"directory",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L526-L535
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
unpack_file_url
|
def unpack_file_url(
link, # type: Link
location, # type: str
download_dir=None, # type: Optional[str]
hashes=None # type: Optional[Hashes]
):
# type: (...) -> None
"""Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir.
"""
link_path = url_to_path(link.url_without_fragment)
# If it's a url to a local directory
if is_dir_url(link):
if os.path.isdir(location):
rmtree(location)
shutil.copytree(link_path, location, symlinks=True)
if download_dir:
logger.info('Link is a directory, ignoring download_dir')
return
# If --require-hashes is off, `hashes` is either empty, the
# link's embedded hash, or MissingHashes; it is required to
# match. If --require-hashes is on, we are satisfied by any
# hash in `hashes` matching: a URL-based or an option-based
# one; no internet-sourced hash will be in `hashes`.
if hashes:
hashes.check_against_path(link_path)
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link,
download_dir,
hashes)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link_path
content_type = mimetypes.guess_type(from_path)[0]
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies
unpack_file(from_path, location, content_type, link)
# a download dir is specified and not already downloaded
if download_dir and not already_downloaded_path:
_copy_file(from_path, download_dir, link)
|
python
|
def unpack_file_url(
link, # type: Link
location, # type: str
download_dir=None, # type: Optional[str]
hashes=None # type: Optional[Hashes]
):
# type: (...) -> None
"""Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir.
"""
link_path = url_to_path(link.url_without_fragment)
# If it's a url to a local directory
if is_dir_url(link):
if os.path.isdir(location):
rmtree(location)
shutil.copytree(link_path, location, symlinks=True)
if download_dir:
logger.info('Link is a directory, ignoring download_dir')
return
# If --require-hashes is off, `hashes` is either empty, the
# link's embedded hash, or MissingHashes; it is required to
# match. If --require-hashes is on, we are satisfied by any
# hash in `hashes` matching: a URL-based or an option-based
# one; no internet-sourced hash will be in `hashes`.
if hashes:
hashes.check_against_path(link_path)
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link,
download_dir,
hashes)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link_path
content_type = mimetypes.guess_type(from_path)[0]
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies
unpack_file(from_path, location, content_type, link)
# a download dir is specified and not already downloaded
if download_dir and not already_downloaded_path:
_copy_file(from_path, download_dir, link)
|
[
"def",
"unpack_file_url",
"(",
"link",
",",
"# type: Link",
"location",
",",
"# type: str",
"download_dir",
"=",
"None",
",",
"# type: Optional[str]",
"hashes",
"=",
"None",
"# type: Optional[Hashes]",
")",
":",
"# type: (...) -> None",
"link_path",
"=",
"url_to_path",
"(",
"link",
".",
"url_without_fragment",
")",
"# If it's a url to a local directory",
"if",
"is_dir_url",
"(",
"link",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"location",
")",
":",
"rmtree",
"(",
"location",
")",
"shutil",
".",
"copytree",
"(",
"link_path",
",",
"location",
",",
"symlinks",
"=",
"True",
")",
"if",
"download_dir",
":",
"logger",
".",
"info",
"(",
"'Link is a directory, ignoring download_dir'",
")",
"return",
"# If --require-hashes is off, `hashes` is either empty, the",
"# link's embedded hash, or MissingHashes; it is required to",
"# match. If --require-hashes is on, we are satisfied by any",
"# hash in `hashes` matching: a URL-based or an option-based",
"# one; no internet-sourced hash will be in `hashes`.",
"if",
"hashes",
":",
"hashes",
".",
"check_against_path",
"(",
"link_path",
")",
"# If a download dir is specified, is the file already there and valid?",
"already_downloaded_path",
"=",
"None",
"if",
"download_dir",
":",
"already_downloaded_path",
"=",
"_check_download_dir",
"(",
"link",
",",
"download_dir",
",",
"hashes",
")",
"if",
"already_downloaded_path",
":",
"from_path",
"=",
"already_downloaded_path",
"else",
":",
"from_path",
"=",
"link_path",
"content_type",
"=",
"mimetypes",
".",
"guess_type",
"(",
"from_path",
")",
"[",
"0",
"]",
"# unpack the archive to the build dir location. even when only downloading",
"# archives, they have to be unpacked to parse dependencies",
"unpack_file",
"(",
"from_path",
",",
"location",
",",
"content_type",
",",
"link",
")",
"# a download dir is specified and not already downloaded",
"if",
"download_dir",
"and",
"not",
"already_downloaded_path",
":",
"_copy_file",
"(",
"from_path",
",",
"download_dir",
",",
"link",
")"
] |
Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir.
|
[
"Unpack",
"link",
"into",
"location",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L716-L767
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
_copy_dist_from_dir
|
def _copy_dist_from_dir(link_path, location):
"""Copy distribution files in `link_path` to `location`.
Invoked when user requests to install a local directory. E.g.:
pip install .
pip install ~/dev/git-repos/python-prompt-toolkit
"""
# Note: This is currently VERY SLOW if you have a lot of data in the
# directory, because it copies everything with `shutil.copytree`.
# What it should really do is build an sdist and install that.
# See https://github.com/pypa/pip/issues/2195
if os.path.isdir(location):
rmtree(location)
# build an sdist
setup_py = 'setup.py'
sdist_args = [sys.executable]
sdist_args.append('-c')
sdist_args.append(SETUPTOOLS_SHIM % setup_py)
sdist_args.append('sdist')
sdist_args += ['--dist-dir', location]
logger.info('Running setup.py sdist for %s', link_path)
with indent_log():
call_subprocess(sdist_args, cwd=link_path, show_stdout=False)
# unpack sdist into `location`
sdist = os.path.join(location, os.listdir(location)[0])
logger.info('Unpacking sdist %s into %s', sdist, location)
unpack_file(sdist, location, content_type=None, link=None)
|
python
|
def _copy_dist_from_dir(link_path, location):
"""Copy distribution files in `link_path` to `location`.
Invoked when user requests to install a local directory. E.g.:
pip install .
pip install ~/dev/git-repos/python-prompt-toolkit
"""
# Note: This is currently VERY SLOW if you have a lot of data in the
# directory, because it copies everything with `shutil.copytree`.
# What it should really do is build an sdist and install that.
# See https://github.com/pypa/pip/issues/2195
if os.path.isdir(location):
rmtree(location)
# build an sdist
setup_py = 'setup.py'
sdist_args = [sys.executable]
sdist_args.append('-c')
sdist_args.append(SETUPTOOLS_SHIM % setup_py)
sdist_args.append('sdist')
sdist_args += ['--dist-dir', location]
logger.info('Running setup.py sdist for %s', link_path)
with indent_log():
call_subprocess(sdist_args, cwd=link_path, show_stdout=False)
# unpack sdist into `location`
sdist = os.path.join(location, os.listdir(location)[0])
logger.info('Unpacking sdist %s into %s', sdist, location)
unpack_file(sdist, location, content_type=None, link=None)
|
[
"def",
"_copy_dist_from_dir",
"(",
"link_path",
",",
"location",
")",
":",
"# Note: This is currently VERY SLOW if you have a lot of data in the",
"# directory, because it copies everything with `shutil.copytree`.",
"# What it should really do is build an sdist and install that.",
"# See https://github.com/pypa/pip/issues/2195",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"location",
")",
":",
"rmtree",
"(",
"location",
")",
"# build an sdist",
"setup_py",
"=",
"'setup.py'",
"sdist_args",
"=",
"[",
"sys",
".",
"executable",
"]",
"sdist_args",
".",
"append",
"(",
"'-c'",
")",
"sdist_args",
".",
"append",
"(",
"SETUPTOOLS_SHIM",
"%",
"setup_py",
")",
"sdist_args",
".",
"append",
"(",
"'sdist'",
")",
"sdist_args",
"+=",
"[",
"'--dist-dir'",
",",
"location",
"]",
"logger",
".",
"info",
"(",
"'Running setup.py sdist for %s'",
",",
"link_path",
")",
"with",
"indent_log",
"(",
")",
":",
"call_subprocess",
"(",
"sdist_args",
",",
"cwd",
"=",
"link_path",
",",
"show_stdout",
"=",
"False",
")",
"# unpack sdist into `location`",
"sdist",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"os",
".",
"listdir",
"(",
"location",
")",
"[",
"0",
"]",
")",
"logger",
".",
"info",
"(",
"'Unpacking sdist %s into %s'",
",",
"sdist",
",",
"location",
")",
"unpack_file",
"(",
"sdist",
",",
"location",
",",
"content_type",
"=",
"None",
",",
"link",
"=",
"None",
")"
] |
Copy distribution files in `link_path` to `location`.
Invoked when user requests to install a local directory. E.g.:
pip install .
pip install ~/dev/git-repos/python-prompt-toolkit
|
[
"Copy",
"distribution",
"files",
"in",
"link_path",
"to",
"location",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L770-L803
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
unpack_url
|
def unpack_url(
link, # type: Optional[Link]
location, # type: Optional[str]
download_dir=None, # type: Optional[str]
only_download=False, # type: bool
session=None, # type: Optional[PipSession]
hashes=None, # type: Optional[Hashes]
progress_bar="on" # type: str
):
# type: (...) -> None
"""Unpack link.
If link is a VCS link:
if only_download, export into download_dir and ignore location
else unpack into location
for other types of link:
- unpack into location
- if download_dir, copy the file into download_dir
- if only_download, mark location for deletion
:param hashes: A Hashes object, one of whose embedded hashes must match,
or HashMismatch will be raised. If the Hashes is empty, no matches are
required, and unhashable types of requirements (like VCS ones, which
would ordinarily raise HashUnsupported) are allowed.
"""
# non-editable vcs urls
if is_vcs_url(link):
unpack_vcs_link(link, location)
# file urls
elif is_file_url(link):
unpack_file_url(link, location, download_dir, hashes=hashes)
# http urls
else:
if session is None:
session = PipSession()
unpack_http_url(
link,
location,
download_dir,
session,
hashes=hashes,
progress_bar=progress_bar
)
if only_download:
write_delete_marker_file(location)
|
python
|
def unpack_url(
link, # type: Optional[Link]
location, # type: Optional[str]
download_dir=None, # type: Optional[str]
only_download=False, # type: bool
session=None, # type: Optional[PipSession]
hashes=None, # type: Optional[Hashes]
progress_bar="on" # type: str
):
# type: (...) -> None
"""Unpack link.
If link is a VCS link:
if only_download, export into download_dir and ignore location
else unpack into location
for other types of link:
- unpack into location
- if download_dir, copy the file into download_dir
- if only_download, mark location for deletion
:param hashes: A Hashes object, one of whose embedded hashes must match,
or HashMismatch will be raised. If the Hashes is empty, no matches are
required, and unhashable types of requirements (like VCS ones, which
would ordinarily raise HashUnsupported) are allowed.
"""
# non-editable vcs urls
if is_vcs_url(link):
unpack_vcs_link(link, location)
# file urls
elif is_file_url(link):
unpack_file_url(link, location, download_dir, hashes=hashes)
# http urls
else:
if session is None:
session = PipSession()
unpack_http_url(
link,
location,
download_dir,
session,
hashes=hashes,
progress_bar=progress_bar
)
if only_download:
write_delete_marker_file(location)
|
[
"def",
"unpack_url",
"(",
"link",
",",
"# type: Optional[Link]",
"location",
",",
"# type: Optional[str]",
"download_dir",
"=",
"None",
",",
"# type: Optional[str]",
"only_download",
"=",
"False",
",",
"# type: bool",
"session",
"=",
"None",
",",
"# type: Optional[PipSession]",
"hashes",
"=",
"None",
",",
"# type: Optional[Hashes]",
"progress_bar",
"=",
"\"on\"",
"# type: str",
")",
":",
"# type: (...) -> None",
"# non-editable vcs urls",
"if",
"is_vcs_url",
"(",
"link",
")",
":",
"unpack_vcs_link",
"(",
"link",
",",
"location",
")",
"# file urls",
"elif",
"is_file_url",
"(",
"link",
")",
":",
"unpack_file_url",
"(",
"link",
",",
"location",
",",
"download_dir",
",",
"hashes",
"=",
"hashes",
")",
"# http urls",
"else",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"PipSession",
"(",
")",
"unpack_http_url",
"(",
"link",
",",
"location",
",",
"download_dir",
",",
"session",
",",
"hashes",
"=",
"hashes",
",",
"progress_bar",
"=",
"progress_bar",
")",
"if",
"only_download",
":",
"write_delete_marker_file",
"(",
"location",
")"
] |
Unpack link.
If link is a VCS link:
if only_download, export into download_dir and ignore location
else unpack into location
for other types of link:
- unpack into location
- if download_dir, copy the file into download_dir
- if only_download, mark location for deletion
:param hashes: A Hashes object, one of whose embedded hashes must match,
or HashMismatch will be raised. If the Hashes is empty, no matches are
required, and unhashable types of requirements (like VCS ones, which
would ordinarily raise HashUnsupported) are allowed.
|
[
"Unpack",
"link",
".",
"If",
"link",
"is",
"a",
"VCS",
"link",
":",
"if",
"only_download",
"export",
"into",
"download_dir",
"and",
"ignore",
"location",
"else",
"unpack",
"into",
"location",
"for",
"other",
"types",
"of",
"link",
":",
"-",
"unpack",
"into",
"location",
"-",
"if",
"download_dir",
"copy",
"the",
"file",
"into",
"download_dir",
"-",
"if",
"only_download",
"mark",
"location",
"for",
"deletion"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L835-L881
|
train
|
pypa/pipenv
|
pipenv/patched/notpip/_internal/download.py
|
_check_download_dir
|
def _check_download_dir(link, download_dir, hashes):
# type: (Link, str, Hashes) -> Optional[str]
""" Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
"""
download_path = os.path.join(download_dir, link.filename)
if os.path.exists(download_path):
# If already downloaded, does its hash match?
logger.info('File was already downloaded %s', download_path)
if hashes:
try:
hashes.check_against_path(download_path)
except HashMismatch:
logger.warning(
'Previously-downloaded file %s has bad hash. '
'Re-downloading.',
download_path
)
os.unlink(download_path)
return None
return download_path
return None
|
python
|
def _check_download_dir(link, download_dir, hashes):
# type: (Link, str, Hashes) -> Optional[str]
""" Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
"""
download_path = os.path.join(download_dir, link.filename)
if os.path.exists(download_path):
# If already downloaded, does its hash match?
logger.info('File was already downloaded %s', download_path)
if hashes:
try:
hashes.check_against_path(download_path)
except HashMismatch:
logger.warning(
'Previously-downloaded file %s has bad hash. '
'Re-downloading.',
download_path
)
os.unlink(download_path)
return None
return download_path
return None
|
[
"def",
"_check_download_dir",
"(",
"link",
",",
"download_dir",
",",
"hashes",
")",
":",
"# type: (Link, str, Hashes) -> Optional[str]",
"download_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"download_dir",
",",
"link",
".",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"download_path",
")",
":",
"# If already downloaded, does its hash match?",
"logger",
".",
"info",
"(",
"'File was already downloaded %s'",
",",
"download_path",
")",
"if",
"hashes",
":",
"try",
":",
"hashes",
".",
"check_against_path",
"(",
"download_path",
")",
"except",
"HashMismatch",
":",
"logger",
".",
"warning",
"(",
"'Previously-downloaded file %s has bad hash. '",
"'Re-downloading.'",
",",
"download_path",
")",
"os",
".",
"unlink",
"(",
"download_path",
")",
"return",
"None",
"return",
"download_path",
"return",
"None"
] |
Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
|
[
"Check",
"download_dir",
"for",
"previously",
"downloaded",
"file",
"with",
"correct",
"hash",
"If",
"a",
"correct",
"file",
"is",
"found",
"return",
"its",
"path",
"else",
"None"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/download.py#L950-L971
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
_default_key_normalizer
|
def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey
"""
# Since we mutate the dictionary, make a copy first
context = request_context.copy()
context['scheme'] = context['scheme'].lower()
context['host'] = context['host'].lower()
# These are both dictionaries and need to be transformed into frozensets
for key in ('headers', '_proxy_headers', '_socks_options'):
if key in context and context[key] is not None:
context[key] = frozenset(context[key].items())
# The socket_options key may be a list and needs to be transformed into a
# tuple.
socket_opts = context.get('socket_options')
if socket_opts is not None:
context['socket_options'] = tuple(socket_opts)
# Map the kwargs to the names in the namedtuple - this is necessary since
# namedtuples can't have fields starting with '_'.
for key in list(context.keys()):
context['key_' + key] = context.pop(key)
# Default to ``None`` for keys missing from the context
for field in key_class._fields:
if field not in context:
context[field] = None
return key_class(**context)
|
python
|
def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey
"""
# Since we mutate the dictionary, make a copy first
context = request_context.copy()
context['scheme'] = context['scheme'].lower()
context['host'] = context['host'].lower()
# These are both dictionaries and need to be transformed into frozensets
for key in ('headers', '_proxy_headers', '_socks_options'):
if key in context and context[key] is not None:
context[key] = frozenset(context[key].items())
# The socket_options key may be a list and needs to be transformed into a
# tuple.
socket_opts = context.get('socket_options')
if socket_opts is not None:
context['socket_options'] = tuple(socket_opts)
# Map the kwargs to the names in the namedtuple - this is necessary since
# namedtuples can't have fields starting with '_'.
for key in list(context.keys()):
context['key_' + key] = context.pop(key)
# Default to ``None`` for keys missing from the context
for field in key_class._fields:
if field not in context:
context[field] = None
return key_class(**context)
|
[
"def",
"_default_key_normalizer",
"(",
"key_class",
",",
"request_context",
")",
":",
"# Since we mutate the dictionary, make a copy first",
"context",
"=",
"request_context",
".",
"copy",
"(",
")",
"context",
"[",
"'scheme'",
"]",
"=",
"context",
"[",
"'scheme'",
"]",
".",
"lower",
"(",
")",
"context",
"[",
"'host'",
"]",
"=",
"context",
"[",
"'host'",
"]",
".",
"lower",
"(",
")",
"# These are both dictionaries and need to be transformed into frozensets",
"for",
"key",
"in",
"(",
"'headers'",
",",
"'_proxy_headers'",
",",
"'_socks_options'",
")",
":",
"if",
"key",
"in",
"context",
"and",
"context",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"context",
"[",
"key",
"]",
"=",
"frozenset",
"(",
"context",
"[",
"key",
"]",
".",
"items",
"(",
")",
")",
"# The socket_options key may be a list and needs to be transformed into a",
"# tuple.",
"socket_opts",
"=",
"context",
".",
"get",
"(",
"'socket_options'",
")",
"if",
"socket_opts",
"is",
"not",
"None",
":",
"context",
"[",
"'socket_options'",
"]",
"=",
"tuple",
"(",
"socket_opts",
")",
"# Map the kwargs to the names in the namedtuple - this is necessary since",
"# namedtuples can't have fields starting with '_'.",
"for",
"key",
"in",
"list",
"(",
"context",
".",
"keys",
"(",
")",
")",
":",
"context",
"[",
"'key_'",
"+",
"key",
"]",
"=",
"context",
".",
"pop",
"(",
"key",
")",
"# Default to ``None`` for keys missing from the context",
"for",
"field",
"in",
"key_class",
".",
"_fields",
":",
"if",
"field",
"not",
"in",
"context",
":",
"context",
"[",
"field",
"]",
"=",
"None",
"return",
"key_class",
"(",
"*",
"*",
"context",
")"
] |
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey
|
[
"Create",
"a",
"pool",
"key",
"out",
"of",
"a",
"request",
"context",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L58-L104
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager._new_pool
|
def _new_pool(self, scheme, host, port, request_context=None):
"""
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This method is used to actually create the
connection pools handed out by :meth:`connection_from_url` and
companion methods. It is intended to be overridden for customization.
"""
pool_cls = self.pool_classes_by_scheme[scheme]
if request_context is None:
request_context = self.connection_pool_kw.copy()
# Although the context has everything necessary to create the pool,
# this function has historically only used the scheme, host, and port
# in the positional args. When an API change is acceptable these can
# be removed.
for key in ('scheme', 'host', 'port'):
request_context.pop(key, None)
if scheme == 'http':
for kw in SSL_KEYWORDS:
request_context.pop(kw, None)
return pool_cls(host, port, **request_context)
|
python
|
def _new_pool(self, scheme, host, port, request_context=None):
"""
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This method is used to actually create the
connection pools handed out by :meth:`connection_from_url` and
companion methods. It is intended to be overridden for customization.
"""
pool_cls = self.pool_classes_by_scheme[scheme]
if request_context is None:
request_context = self.connection_pool_kw.copy()
# Although the context has everything necessary to create the pool,
# this function has historically only used the scheme, host, and port
# in the positional args. When an API change is acceptable these can
# be removed.
for key in ('scheme', 'host', 'port'):
request_context.pop(key, None)
if scheme == 'http':
for kw in SSL_KEYWORDS:
request_context.pop(kw, None)
return pool_cls(host, port, **request_context)
|
[
"def",
"_new_pool",
"(",
"self",
",",
"scheme",
",",
"host",
",",
"port",
",",
"request_context",
"=",
"None",
")",
":",
"pool_cls",
"=",
"self",
".",
"pool_classes_by_scheme",
"[",
"scheme",
"]",
"if",
"request_context",
"is",
"None",
":",
"request_context",
"=",
"self",
".",
"connection_pool_kw",
".",
"copy",
"(",
")",
"# Although the context has everything necessary to create the pool,",
"# this function has historically only used the scheme, host, and port",
"# in the positional args. When an API change is acceptable these can",
"# be removed.",
"for",
"key",
"in",
"(",
"'scheme'",
",",
"'host'",
",",
"'port'",
")",
":",
"request_context",
".",
"pop",
"(",
"key",
",",
"None",
")",
"if",
"scheme",
"==",
"'http'",
":",
"for",
"kw",
"in",
"SSL_KEYWORDS",
":",
"request_context",
".",
"pop",
"(",
"kw",
",",
"None",
")",
"return",
"pool_cls",
"(",
"host",
",",
"port",
",",
"*",
"*",
"request_context",
")"
] |
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This method is used to actually create the
connection pools handed out by :meth:`connection_from_url` and
companion methods. It is intended to be overridden for customization.
|
[
"Create",
"a",
"new",
":",
"class",
":",
"ConnectionPool",
"based",
"on",
"host",
"port",
"scheme",
"and",
"any",
"additional",
"pool",
"keyword",
"arguments",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L171-L196
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager.connection_from_host
|
def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
provided, it is merged with the instance's ``connection_pool_kw``
variable and used to create the new connection pool, if one is
needed.
"""
if not host:
raise LocationValueError("No host specified.")
request_context = self._merge_pool_kwargs(pool_kwargs)
request_context['scheme'] = scheme or 'http'
if not port:
port = port_by_scheme.get(request_context['scheme'].lower(), 80)
request_context['port'] = port
request_context['host'] = host
return self.connection_from_context(request_context)
|
python
|
def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
provided, it is merged with the instance's ``connection_pool_kw``
variable and used to create the new connection pool, if one is
needed.
"""
if not host:
raise LocationValueError("No host specified.")
request_context = self._merge_pool_kwargs(pool_kwargs)
request_context['scheme'] = scheme or 'http'
if not port:
port = port_by_scheme.get(request_context['scheme'].lower(), 80)
request_context['port'] = port
request_context['host'] = host
return self.connection_from_context(request_context)
|
[
"def",
"connection_from_host",
"(",
"self",
",",
"host",
",",
"port",
"=",
"None",
",",
"scheme",
"=",
"'http'",
",",
"pool_kwargs",
"=",
"None",
")",
":",
"if",
"not",
"host",
":",
"raise",
"LocationValueError",
"(",
"\"No host specified.\"",
")",
"request_context",
"=",
"self",
".",
"_merge_pool_kwargs",
"(",
"pool_kwargs",
")",
"request_context",
"[",
"'scheme'",
"]",
"=",
"scheme",
"or",
"'http'",
"if",
"not",
"port",
":",
"port",
"=",
"port_by_scheme",
".",
"get",
"(",
"request_context",
"[",
"'scheme'",
"]",
".",
"lower",
"(",
")",
",",
"80",
")",
"request_context",
"[",
"'port'",
"]",
"=",
"port",
"request_context",
"[",
"'host'",
"]",
"=",
"host",
"return",
"self",
".",
"connection_from_context",
"(",
"request_context",
")"
] |
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
provided, it is merged with the instance's ``connection_pool_kw``
variable and used to create the new connection pool, if one is
needed.
|
[
"Get",
"a",
":",
"class",
":",
"ConnectionPool",
"based",
"on",
"the",
"host",
"port",
"and",
"scheme",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L207-L228
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager.connection_from_context
|
def connection_from_context(self, request_context):
"""
Get a :class:`ConnectionPool` based on the request context.
``request_context`` must at least contain the ``scheme`` key and its
value must be a key in ``key_fn_by_scheme`` instance variable.
"""
scheme = request_context['scheme'].lower()
pool_key_constructor = self.key_fn_by_scheme[scheme]
pool_key = pool_key_constructor(request_context)
return self.connection_from_pool_key(pool_key, request_context=request_context)
|
python
|
def connection_from_context(self, request_context):
"""
Get a :class:`ConnectionPool` based on the request context.
``request_context`` must at least contain the ``scheme`` key and its
value must be a key in ``key_fn_by_scheme`` instance variable.
"""
scheme = request_context['scheme'].lower()
pool_key_constructor = self.key_fn_by_scheme[scheme]
pool_key = pool_key_constructor(request_context)
return self.connection_from_pool_key(pool_key, request_context=request_context)
|
[
"def",
"connection_from_context",
"(",
"self",
",",
"request_context",
")",
":",
"scheme",
"=",
"request_context",
"[",
"'scheme'",
"]",
".",
"lower",
"(",
")",
"pool_key_constructor",
"=",
"self",
".",
"key_fn_by_scheme",
"[",
"scheme",
"]",
"pool_key",
"=",
"pool_key_constructor",
"(",
"request_context",
")",
"return",
"self",
".",
"connection_from_pool_key",
"(",
"pool_key",
",",
"request_context",
"=",
"request_context",
")"
] |
Get a :class:`ConnectionPool` based on the request context.
``request_context`` must at least contain the ``scheme`` key and its
value must be a key in ``key_fn_by_scheme`` instance variable.
|
[
"Get",
"a",
":",
"class",
":",
"ConnectionPool",
"based",
"on",
"the",
"request",
"context",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L230-L241
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager.connection_from_pool_key
|
def connection_from_pool_key(self, pool_key, request_context=None):
"""
Get a :class:`ConnectionPool` based on the provided pool key.
``pool_key`` should be a namedtuple that only contains immutable
objects. At a minimum it must have the ``scheme``, ``host``, and
``port`` fields.
"""
with self.pools.lock:
# If the scheme, host, or port doesn't match existing open
# connections, open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
scheme = request_context['scheme']
host = request_context['host']
port = request_context['port']
pool = self._new_pool(scheme, host, port, request_context=request_context)
self.pools[pool_key] = pool
return pool
|
python
|
def connection_from_pool_key(self, pool_key, request_context=None):
"""
Get a :class:`ConnectionPool` based on the provided pool key.
``pool_key`` should be a namedtuple that only contains immutable
objects. At a minimum it must have the ``scheme``, ``host``, and
``port`` fields.
"""
with self.pools.lock:
# If the scheme, host, or port doesn't match existing open
# connections, open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
scheme = request_context['scheme']
host = request_context['host']
port = request_context['port']
pool = self._new_pool(scheme, host, port, request_context=request_context)
self.pools[pool_key] = pool
return pool
|
[
"def",
"connection_from_pool_key",
"(",
"self",
",",
"pool_key",
",",
"request_context",
"=",
"None",
")",
":",
"with",
"self",
".",
"pools",
".",
"lock",
":",
"# If the scheme, host, or port doesn't match existing open",
"# connections, open a new ConnectionPool.",
"pool",
"=",
"self",
".",
"pools",
".",
"get",
"(",
"pool_key",
")",
"if",
"pool",
":",
"return",
"pool",
"# Make a fresh ConnectionPool of the desired type",
"scheme",
"=",
"request_context",
"[",
"'scheme'",
"]",
"host",
"=",
"request_context",
"[",
"'host'",
"]",
"port",
"=",
"request_context",
"[",
"'port'",
"]",
"pool",
"=",
"self",
".",
"_new_pool",
"(",
"scheme",
",",
"host",
",",
"port",
",",
"request_context",
"=",
"request_context",
")",
"self",
".",
"pools",
"[",
"pool_key",
"]",
"=",
"pool",
"return",
"pool"
] |
Get a :class:`ConnectionPool` based on the provided pool key.
``pool_key`` should be a namedtuple that only contains immutable
objects. At a minimum it must have the ``scheme``, ``host``, and
``port`` fields.
|
[
"Get",
"a",
":",
"class",
":",
"ConnectionPool",
"based",
"on",
"the",
"provided",
"pool",
"key",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L243-L265
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager.connection_from_url
|
def connection_from_url(self, url, pool_kwargs=None):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url`.
If ``pool_kwargs`` is not provided and a new pool needs to be
constructed, ``self.connection_pool_kw`` is used to initialize
the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
is provided, it is used instead. Note that if a new pool does not
need to be created for the request, the provided ``pool_kwargs`` are
not used.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme,
pool_kwargs=pool_kwargs)
|
python
|
def connection_from_url(self, url, pool_kwargs=None):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url`.
If ``pool_kwargs`` is not provided and a new pool needs to be
constructed, ``self.connection_pool_kw`` is used to initialize
the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
is provided, it is used instead. Note that if a new pool does not
need to be created for the request, the provided ``pool_kwargs`` are
not used.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme,
pool_kwargs=pool_kwargs)
|
[
"def",
"connection_from_url",
"(",
"self",
",",
"url",
",",
"pool_kwargs",
"=",
"None",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"return",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"=",
"u",
".",
"port",
",",
"scheme",
"=",
"u",
".",
"scheme",
",",
"pool_kwargs",
"=",
"pool_kwargs",
")"
] |
Similar to :func:`urllib3.connectionpool.connection_from_url`.
If ``pool_kwargs`` is not provided and a new pool needs to be
constructed, ``self.connection_pool_kw`` is used to initialize
the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
is provided, it is used instead. Note that if a new pool does not
need to be created for the request, the provided ``pool_kwargs`` are
not used.
|
[
"Similar",
"to",
":",
"func",
":",
"urllib3",
".",
"connectionpool",
".",
"connection_from_url",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L267-L280
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager._merge_pool_kwargs
|
def _merge_pool_kwargs(self, override):
"""
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary.
"""
base_pool_kwargs = self.connection_pool_kw.copy()
if override:
for key, value in override.items():
if value is None:
try:
del base_pool_kwargs[key]
except KeyError:
pass
else:
base_pool_kwargs[key] = value
return base_pool_kwargs
|
python
|
def _merge_pool_kwargs(self, override):
"""
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary.
"""
base_pool_kwargs = self.connection_pool_kw.copy()
if override:
for key, value in override.items():
if value is None:
try:
del base_pool_kwargs[key]
except KeyError:
pass
else:
base_pool_kwargs[key] = value
return base_pool_kwargs
|
[
"def",
"_merge_pool_kwargs",
"(",
"self",
",",
"override",
")",
":",
"base_pool_kwargs",
"=",
"self",
".",
"connection_pool_kw",
".",
"copy",
"(",
")",
"if",
"override",
":",
"for",
"key",
",",
"value",
"in",
"override",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"try",
":",
"del",
"base_pool_kwargs",
"[",
"key",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"base_pool_kwargs",
"[",
"key",
"]",
"=",
"value",
"return",
"base_pool_kwargs"
] |
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary.
|
[
"Merge",
"a",
"dictionary",
"of",
"override",
"values",
"for",
"self",
".",
"connection_pool_kw",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L282-L300
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
PoolManager.urlopen
|
def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers.copy()
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw)
else:
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
# Support relative URLs for redirecting.
redirect_location = urljoin(url, redirect_location)
# RFC 7231, Section 6.4.4
if response.status == 303:
method = 'GET'
retries = kw.get('retries')
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
# Strip headers marked as unsafe to forward to the redirected location.
# Check remove_headers_on_redirect to avoid a potential network call within
# conn.is_same_host() which may use socket.gethostbyname() in the future.
if (retries.remove_headers_on_redirect
and not conn.is_same_host(redirect_location)):
for header in retries.remove_headers_on_redirect:
kw['headers'].pop(header, None)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
kw['retries'] = retries
kw['redirect'] = redirect
log.info("Redirecting %s -> %s", url, redirect_location)
return self.urlopen(method, redirect_location, **kw)
|
python
|
def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers.copy()
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw)
else:
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
# Support relative URLs for redirecting.
redirect_location = urljoin(url, redirect_location)
# RFC 7231, Section 6.4.4
if response.status == 303:
method = 'GET'
retries = kw.get('retries')
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
# Strip headers marked as unsafe to forward to the redirected location.
# Check remove_headers_on_redirect to avoid a potential network call within
# conn.is_same_host() which may use socket.gethostbyname() in the future.
if (retries.remove_headers_on_redirect
and not conn.is_same_host(redirect_location)):
for header in retries.remove_headers_on_redirect:
kw['headers'].pop(header, None)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
kw['retries'] = retries
kw['redirect'] = redirect
log.info("Redirecting %s -> %s", url, redirect_location)
return self.urlopen(method, redirect_location, **kw)
|
[
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"redirect",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"conn",
"=",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"=",
"u",
".",
"port",
",",
"scheme",
"=",
"u",
".",
"scheme",
")",
"kw",
"[",
"'assert_same_host'",
"]",
"=",
"False",
"kw",
"[",
"'redirect'",
"]",
"=",
"False",
"if",
"'headers'",
"not",
"in",
"kw",
":",
"kw",
"[",
"'headers'",
"]",
"=",
"self",
".",
"headers",
".",
"copy",
"(",
")",
"if",
"self",
".",
"proxy",
"is",
"not",
"None",
"and",
"u",
".",
"scheme",
"==",
"\"http\"",
":",
"response",
"=",
"conn",
".",
"urlopen",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kw",
")",
"else",
":",
"response",
"=",
"conn",
".",
"urlopen",
"(",
"method",
",",
"u",
".",
"request_uri",
",",
"*",
"*",
"kw",
")",
"redirect_location",
"=",
"redirect",
"and",
"response",
".",
"get_redirect_location",
"(",
")",
"if",
"not",
"redirect_location",
":",
"return",
"response",
"# Support relative URLs for redirecting.",
"redirect_location",
"=",
"urljoin",
"(",
"url",
",",
"redirect_location",
")",
"# RFC 7231, Section 6.4.4",
"if",
"response",
".",
"status",
"==",
"303",
":",
"method",
"=",
"'GET'",
"retries",
"=",
"kw",
".",
"get",
"(",
"'retries'",
")",
"if",
"not",
"isinstance",
"(",
"retries",
",",
"Retry",
")",
":",
"retries",
"=",
"Retry",
".",
"from_int",
"(",
"retries",
",",
"redirect",
"=",
"redirect",
")",
"# Strip headers marked as unsafe to forward to the redirected location.",
"# Check remove_headers_on_redirect to avoid a potential network call within",
"# conn.is_same_host() which may use socket.gethostbyname() in the future.",
"if",
"(",
"retries",
".",
"remove_headers_on_redirect",
"and",
"not",
"conn",
".",
"is_same_host",
"(",
"redirect_location",
")",
")",
":",
"for",
"header",
"in",
"retries",
".",
"remove_headers_on_redirect",
":",
"kw",
"[",
"'headers'",
"]",
".",
"pop",
"(",
"header",
",",
"None",
")",
"try",
":",
"retries",
"=",
"retries",
".",
"increment",
"(",
"method",
",",
"url",
",",
"response",
"=",
"response",
",",
"_pool",
"=",
"conn",
")",
"except",
"MaxRetryError",
":",
"if",
"retries",
".",
"raise_on_redirect",
":",
"raise",
"return",
"response",
"kw",
"[",
"'retries'",
"]",
"=",
"retries",
"kw",
"[",
"'redirect'",
"]",
"=",
"redirect",
"log",
".",
"info",
"(",
"\"Redirecting %s -> %s\"",
",",
"url",
",",
"redirect_location",
")",
"return",
"self",
".",
"urlopen",
"(",
"method",
",",
"redirect_location",
",",
"*",
"*",
"kw",
")"
] |
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
|
[
"Same",
"as",
":",
"meth",
":",
"urllib3",
".",
"connectionpool",
".",
"HTTPConnectionPool",
".",
"urlopen",
"with",
"custom",
"cross",
"-",
"host",
"redirect",
"logic",
"and",
"only",
"sends",
"the",
"request",
"-",
"uri",
"portion",
"of",
"the",
"url",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L302-L359
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
ProxyManager._set_proxy_headers
|
def _set_proxy_headers(self, url, headers=None):
"""
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
"""
headers_ = {'Accept': '*/*'}
netloc = parse_url(url).netloc
if netloc:
headers_['Host'] = netloc
if headers:
headers_.update(headers)
return headers_
|
python
|
def _set_proxy_headers(self, url, headers=None):
"""
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
"""
headers_ = {'Accept': '*/*'}
netloc = parse_url(url).netloc
if netloc:
headers_['Host'] = netloc
if headers:
headers_.update(headers)
return headers_
|
[
"def",
"_set_proxy_headers",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
")",
":",
"headers_",
"=",
"{",
"'Accept'",
":",
"'*/*'",
"}",
"netloc",
"=",
"parse_url",
"(",
"url",
")",
".",
"netloc",
"if",
"netloc",
":",
"headers_",
"[",
"'Host'",
"]",
"=",
"netloc",
"if",
"headers",
":",
"headers_",
".",
"update",
"(",
"headers",
")",
"return",
"headers_"
] |
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
|
[
"Sets",
"headers",
"needed",
"by",
"proxies",
":",
"specifically",
"the",
"Accept",
"and",
"Host",
"headers",
".",
"Only",
"sets",
"headers",
"not",
"provided",
"by",
"the",
"user",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L420-L433
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/poolmanager.py
|
ProxyManager.urlopen
|
def urlopen(self, method, url, redirect=True, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
u = parse_url(url)
if u.scheme == "http":
# For proxied HTTPS requests, httplib sets the necessary headers
# on the CONNECT to the proxy. For HTTP, we'll definitely
# need to set 'Host' at the very least.
headers = kw.get('headers', self.headers)
kw['headers'] = self._set_proxy_headers(url, headers)
return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
|
python
|
def urlopen(self, method, url, redirect=True, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
u = parse_url(url)
if u.scheme == "http":
# For proxied HTTPS requests, httplib sets the necessary headers
# on the CONNECT to the proxy. For HTTP, we'll definitely
# need to set 'Host' at the very least.
headers = kw.get('headers', self.headers)
kw['headers'] = self._set_proxy_headers(url, headers)
return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
|
[
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"redirect",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"if",
"u",
".",
"scheme",
"==",
"\"http\"",
":",
"# For proxied HTTPS requests, httplib sets the necessary headers",
"# on the CONNECT to the proxy. For HTTP, we'll definitely",
"# need to set 'Host' at the very least.",
"headers",
"=",
"kw",
".",
"get",
"(",
"'headers'",
",",
"self",
".",
"headers",
")",
"kw",
"[",
"'headers'",
"]",
"=",
"self",
".",
"_set_proxy_headers",
"(",
"url",
",",
"headers",
")",
"return",
"super",
"(",
"ProxyManager",
",",
"self",
")",
".",
"urlopen",
"(",
"method",
",",
"url",
",",
"redirect",
"=",
"redirect",
",",
"*",
"*",
"kw",
")"
] |
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.
|
[
"Same",
"as",
"HTTP",
"(",
"S",
")",
"ConnectionPool",
".",
"urlopen",
"url",
"must",
"be",
"absolute",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/poolmanager.py#L435-L446
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/meta.py
|
find_undeclared_variables
|
def find_undeclared_variables(ast):
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
"""
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers
|
python
|
def find_undeclared_variables(ast):
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
"""
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers
|
[
"def",
"find_undeclared_variables",
"(",
"ast",
")",
":",
"codegen",
"=",
"TrackingCodeGenerator",
"(",
"ast",
".",
"environment",
")",
"codegen",
".",
"visit",
"(",
"ast",
")",
"return",
"codegen",
".",
"undeclared_identifiers"
] |
Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
|
[
"Returns",
"a",
"set",
"of",
"all",
"variables",
"in",
"the",
"AST",
"that",
"will",
"be",
"looked",
"up",
"from",
"the",
"context",
"at",
"runtime",
".",
"Because",
"at",
"compile",
"time",
"it",
"s",
"not",
"known",
"which",
"variables",
"will",
"be",
"used",
"depending",
"on",
"the",
"path",
"the",
"execution",
"takes",
"at",
"runtime",
"all",
"variables",
"are",
"returned",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/meta.py#L36-L57
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/meta.py
|
find_referenced_templates
|
def find_referenced_templates(ast):
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
"""
for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
nodes.Include)):
if not isinstance(node.template, nodes.Const):
# a tuple with some non consts in there
if isinstance(node.template, (nodes.Tuple, nodes.List)):
for template_name in node.template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, string_types):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(node.template.value, string_types):
yield node.template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and \
isinstance(node.template.value, (tuple, list)):
for template_name in node.template.value:
if isinstance(template_name, string_types):
yield template_name
# something else we don't care about, we could warn here
else:
yield None
|
python
|
def find_referenced_templates(ast):
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
"""
for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
nodes.Include)):
if not isinstance(node.template, nodes.Const):
# a tuple with some non consts in there
if isinstance(node.template, (nodes.Tuple, nodes.List)):
for template_name in node.template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, string_types):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(node.template.value, string_types):
yield node.template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and \
isinstance(node.template.value, (tuple, list)):
for template_name in node.template.value:
if isinstance(template_name, string_types):
yield template_name
# something else we don't care about, we could warn here
else:
yield None
|
[
"def",
"find_referenced_templates",
"(",
"ast",
")",
":",
"for",
"node",
"in",
"ast",
".",
"find_all",
"(",
"(",
"nodes",
".",
"Extends",
",",
"nodes",
".",
"FromImport",
",",
"nodes",
".",
"Import",
",",
"nodes",
".",
"Include",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"template",
",",
"nodes",
".",
"Const",
")",
":",
"# a tuple with some non consts in there",
"if",
"isinstance",
"(",
"node",
".",
"template",
",",
"(",
"nodes",
".",
"Tuple",
",",
"nodes",
".",
"List",
")",
")",
":",
"for",
"template_name",
"in",
"node",
".",
"template",
".",
"items",
":",
"# something const, only yield the strings and ignore",
"# non-string consts that really just make no sense",
"if",
"isinstance",
"(",
"template_name",
",",
"nodes",
".",
"Const",
")",
":",
"if",
"isinstance",
"(",
"template_name",
".",
"value",
",",
"string_types",
")",
":",
"yield",
"template_name",
".",
"value",
"# something dynamic in there",
"else",
":",
"yield",
"None",
"# something dynamic we don't know about here",
"else",
":",
"yield",
"None",
"continue",
"# constant is a basestring, direct template name",
"if",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"string_types",
")",
":",
"yield",
"node",
".",
"template",
".",
"value",
"# a tuple or list (latter *should* not happen) made of consts,",
"# yield the consts that are strings. We could warn here for",
"# non string values",
"elif",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Include",
")",
"and",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"template_name",
"in",
"node",
".",
"template",
".",
"value",
":",
"if",
"isinstance",
"(",
"template_name",
",",
"string_types",
")",
":",
"yield",
"template_name",
"# something else we don't care about, we could warn here",
"else",
":",
"yield",
"None"
] |
Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
|
[
"Finds",
"all",
"the",
"referenced",
"templates",
"from",
"the",
"AST",
".",
"This",
"will",
"return",
"an",
"iterator",
"over",
"all",
"the",
"hardcoded",
"template",
"extensions",
"inclusions",
"and",
"imports",
".",
"If",
"dynamic",
"inheritance",
"or",
"inclusion",
"is",
"used",
"None",
"will",
"be",
"yielded",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/meta.py#L60-L106
|
train
|
pypa/pipenv
|
pipenv/vendor/jinja2/meta.py
|
TrackingCodeGenerator.enter_frame
|
def enter_frame(self, frame):
"""Remember all undeclared identifiers."""
CodeGenerator.enter_frame(self, frame)
for _, (action, param) in iteritems(frame.symbols.loads):
if action == 'resolve':
self.undeclared_identifiers.add(param)
|
python
|
def enter_frame(self, frame):
"""Remember all undeclared identifiers."""
CodeGenerator.enter_frame(self, frame)
for _, (action, param) in iteritems(frame.symbols.loads):
if action == 'resolve':
self.undeclared_identifiers.add(param)
|
[
"def",
"enter_frame",
"(",
"self",
",",
"frame",
")",
":",
"CodeGenerator",
".",
"enter_frame",
"(",
"self",
",",
"frame",
")",
"for",
"_",
",",
"(",
"action",
",",
"param",
")",
"in",
"iteritems",
"(",
"frame",
".",
"symbols",
".",
"loads",
")",
":",
"if",
"action",
"==",
"'resolve'",
":",
"self",
".",
"undeclared_identifiers",
".",
"add",
"(",
"param",
")"
] |
Remember all undeclared identifiers.
|
[
"Remember",
"all",
"undeclared",
"identifiers",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/meta.py#L28-L33
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
parse_marker
|
def parse_marker(marker_string):
"""
Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).
"""
def marker_var(remaining):
# either identifier, or literal string
m = IDENTIFIER.match(remaining)
if m:
result = m.groups()[0]
remaining = remaining[m.end():]
elif not remaining:
raise SyntaxError('unexpected end of input')
else:
q = remaining[0]
if q not in '\'"':
raise SyntaxError('invalid expression: %s' % remaining)
oq = '\'"'.replace(q, '')
remaining = remaining[1:]
parts = [q]
while remaining:
# either a string chunk, or oq, or q to terminate
if remaining[0] == q:
break
elif remaining[0] == oq:
parts.append(oq)
remaining = remaining[1:]
else:
m = STRING_CHUNK.match(remaining)
if not m:
raise SyntaxError('error in string literal: %s' % remaining)
parts.append(m.groups()[0])
remaining = remaining[m.end():]
else:
s = ''.join(parts)
raise SyntaxError('unterminated string: %s' % s)
parts.append(q)
result = ''.join(parts)
remaining = remaining[1:].lstrip() # skip past closing quote
return result, remaining
def marker_expr(remaining):
if remaining and remaining[0] == '(':
result, remaining = marker(remaining[1:].lstrip())
if remaining[0] != ')':
raise SyntaxError('unterminated parenthesis: %s' % remaining)
remaining = remaining[1:].lstrip()
else:
lhs, remaining = marker_var(remaining)
while remaining:
m = MARKER_OP.match(remaining)
if not m:
break
op = m.groups()[0]
remaining = remaining[m.end():]
rhs, remaining = marker_var(remaining)
lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
result = lhs
return result, remaining
def marker_and(remaining):
lhs, remaining = marker_expr(remaining)
while remaining:
m = AND.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_expr(remaining)
lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
def marker(remaining):
lhs, remaining = marker_and(remaining)
while remaining:
m = OR.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_and(remaining)
lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
return marker(marker_string)
|
python
|
def parse_marker(marker_string):
"""
Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).
"""
def marker_var(remaining):
# either identifier, or literal string
m = IDENTIFIER.match(remaining)
if m:
result = m.groups()[0]
remaining = remaining[m.end():]
elif not remaining:
raise SyntaxError('unexpected end of input')
else:
q = remaining[0]
if q not in '\'"':
raise SyntaxError('invalid expression: %s' % remaining)
oq = '\'"'.replace(q, '')
remaining = remaining[1:]
parts = [q]
while remaining:
# either a string chunk, or oq, or q to terminate
if remaining[0] == q:
break
elif remaining[0] == oq:
parts.append(oq)
remaining = remaining[1:]
else:
m = STRING_CHUNK.match(remaining)
if not m:
raise SyntaxError('error in string literal: %s' % remaining)
parts.append(m.groups()[0])
remaining = remaining[m.end():]
else:
s = ''.join(parts)
raise SyntaxError('unterminated string: %s' % s)
parts.append(q)
result = ''.join(parts)
remaining = remaining[1:].lstrip() # skip past closing quote
return result, remaining
def marker_expr(remaining):
if remaining and remaining[0] == '(':
result, remaining = marker(remaining[1:].lstrip())
if remaining[0] != ')':
raise SyntaxError('unterminated parenthesis: %s' % remaining)
remaining = remaining[1:].lstrip()
else:
lhs, remaining = marker_var(remaining)
while remaining:
m = MARKER_OP.match(remaining)
if not m:
break
op = m.groups()[0]
remaining = remaining[m.end():]
rhs, remaining = marker_var(remaining)
lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
result = lhs
return result, remaining
def marker_and(remaining):
lhs, remaining = marker_expr(remaining)
while remaining:
m = AND.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_expr(remaining)
lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
def marker(remaining):
lhs, remaining = marker_and(remaining)
while remaining:
m = OR.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_and(remaining)
lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
return marker(marker_string)
|
[
"def",
"parse_marker",
"(",
"marker_string",
")",
":",
"def",
"marker_var",
"(",
"remaining",
")",
":",
"# either identifier, or literal string",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"remaining",
")",
"if",
"m",
":",
"result",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"elif",
"not",
"remaining",
":",
"raise",
"SyntaxError",
"(",
"'unexpected end of input'",
")",
"else",
":",
"q",
"=",
"remaining",
"[",
"0",
"]",
"if",
"q",
"not",
"in",
"'\\'\"'",
":",
"raise",
"SyntaxError",
"(",
"'invalid expression: %s'",
"%",
"remaining",
")",
"oq",
"=",
"'\\'\"'",
".",
"replace",
"(",
"q",
",",
"''",
")",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
"parts",
"=",
"[",
"q",
"]",
"while",
"remaining",
":",
"# either a string chunk, or oq, or q to terminate",
"if",
"remaining",
"[",
"0",
"]",
"==",
"q",
":",
"break",
"elif",
"remaining",
"[",
"0",
"]",
"==",
"oq",
":",
"parts",
".",
"append",
"(",
"oq",
")",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
"else",
":",
"m",
"=",
"STRING_CHUNK",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'error in string literal: %s'",
"%",
"remaining",
")",
"parts",
".",
"append",
"(",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
")",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"else",
":",
"s",
"=",
"''",
".",
"join",
"(",
"parts",
")",
"raise",
"SyntaxError",
"(",
"'unterminated string: %s'",
"%",
"s",
")",
"parts",
".",
"append",
"(",
"q",
")",
"result",
"=",
"''",
".",
"join",
"(",
"parts",
")",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"# skip past closing quote",
"return",
"result",
",",
"remaining",
"def",
"marker_expr",
"(",
"remaining",
")",
":",
"if",
"remaining",
"and",
"remaining",
"[",
"0",
"]",
"==",
"'('",
":",
"result",
",",
"remaining",
"=",
"marker",
"(",
"remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
")",
"if",
"remaining",
"[",
"0",
"]",
"!=",
"')'",
":",
"raise",
"SyntaxError",
"(",
"'unterminated parenthesis: %s'",
"%",
"remaining",
")",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"else",
":",
"lhs",
",",
"remaining",
"=",
"marker_var",
"(",
"remaining",
")",
"while",
"remaining",
":",
"m",
"=",
"MARKER_OP",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"break",
"op",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"rhs",
",",
"remaining",
"=",
"marker_var",
"(",
"remaining",
")",
"lhs",
"=",
"{",
"'op'",
":",
"op",
",",
"'lhs'",
":",
"lhs",
",",
"'rhs'",
":",
"rhs",
"}",
"result",
"=",
"lhs",
"return",
"result",
",",
"remaining",
"def",
"marker_and",
"(",
"remaining",
")",
":",
"lhs",
",",
"remaining",
"=",
"marker_expr",
"(",
"remaining",
")",
"while",
"remaining",
":",
"m",
"=",
"AND",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"break",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"rhs",
",",
"remaining",
"=",
"marker_expr",
"(",
"remaining",
")",
"lhs",
"=",
"{",
"'op'",
":",
"'and'",
",",
"'lhs'",
":",
"lhs",
",",
"'rhs'",
":",
"rhs",
"}",
"return",
"lhs",
",",
"remaining",
"def",
"marker",
"(",
"remaining",
")",
":",
"lhs",
",",
"remaining",
"=",
"marker_and",
"(",
"remaining",
")",
"while",
"remaining",
":",
"m",
"=",
"OR",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"break",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"rhs",
",",
"remaining",
"=",
"marker_and",
"(",
"remaining",
")",
"lhs",
"=",
"{",
"'op'",
":",
"'or'",
",",
"'lhs'",
":",
"lhs",
",",
"'rhs'",
":",
"rhs",
"}",
"return",
"lhs",
",",
"remaining",
"return",
"marker",
"(",
"marker_string",
")"
] |
Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).
|
[
"Parse",
"a",
"marker",
"string",
"and",
"return",
"a",
"dictionary",
"containing",
"a",
"marker",
"expression",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L56-L142
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
parse_requirement
|
def parse_requirement(req):
"""
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.
"""
remaining = req.strip()
if not remaining or remaining.startswith('#'):
return None
m = IDENTIFIER.match(remaining)
if not m:
raise SyntaxError('name expected: %s' % remaining)
distname = m.groups()[0]
remaining = remaining[m.end():]
extras = mark_expr = versions = uri = None
if remaining and remaining[0] == '[':
i = remaining.find(']', 1)
if i < 0:
raise SyntaxError('unterminated extra: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
extras = []
while s:
m = IDENTIFIER.match(s)
if not m:
raise SyntaxError('malformed extra: %s' % s)
extras.append(m.groups()[0])
s = s[m.end():]
if not s:
break
if s[0] != ',':
raise SyntaxError('comma expected in extras: %s' % s)
s = s[1:].lstrip()
if not extras:
extras = None
if remaining:
if remaining[0] == '@':
# it's a URI
remaining = remaining[1:].lstrip()
m = NON_SPACE.match(remaining)
if not m:
raise SyntaxError('invalid URI: %s' % remaining)
uri = m.groups()[0]
t = urlparse(uri)
# there are issues with Python and URL parsing, so this test
# is a bit crude. See bpo-20271, bpo-23505. Python doesn't
# always parse invalid URLs correctly - it should raise
# exceptions for malformed URLs
if not (t.scheme and t.netloc):
raise SyntaxError('Invalid URL: %s' % uri)
remaining = remaining[m.end():].lstrip()
else:
def get_versions(ver_remaining):
"""
Return a list of operator, version tuples if any are
specified, else None.
"""
m = COMPARE_OP.match(ver_remaining)
versions = None
if m:
versions = []
while True:
op = m.groups()[0]
ver_remaining = ver_remaining[m.end():]
m = VERSION_IDENTIFIER.match(ver_remaining)
if not m:
raise SyntaxError('invalid version: %s' % ver_remaining)
v = m.groups()[0]
versions.append((op, v))
ver_remaining = ver_remaining[m.end():]
if not ver_remaining or ver_remaining[0] != ',':
break
ver_remaining = ver_remaining[1:].lstrip()
m = COMPARE_OP.match(ver_remaining)
if not m:
raise SyntaxError('invalid constraint: %s' % ver_remaining)
if not versions:
versions = None
return versions, ver_remaining
if remaining[0] != '(':
versions, remaining = get_versions(remaining)
else:
i = remaining.find(')', 1)
if i < 0:
raise SyntaxError('unterminated parenthesis: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
# As a special diversion from PEP 508, allow a version number
# a.b.c in parentheses as a synonym for ~= a.b.c (because this
# is allowed in earlier PEPs)
if COMPARE_OP.match(s):
versions, _ = get_versions(s)
else:
m = VERSION_IDENTIFIER.match(s)
if not m:
raise SyntaxError('invalid constraint: %s' % s)
v = m.groups()[0]
s = s[m.end():].lstrip()
if s:
raise SyntaxError('invalid constraint: %s' % s)
versions = [('~=', v)]
if remaining:
if remaining[0] != ';':
raise SyntaxError('invalid requirement: %s' % remaining)
remaining = remaining[1:].lstrip()
mark_expr, remaining = parse_marker(remaining)
if remaining and remaining[0] != '#':
raise SyntaxError('unexpected trailing data: %s' % remaining)
if not versions:
rs = distname
else:
rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
return Container(name=distname, extras=extras, constraints=versions,
marker=mark_expr, url=uri, requirement=rs)
|
python
|
def parse_requirement(req):
"""
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.
"""
remaining = req.strip()
if not remaining or remaining.startswith('#'):
return None
m = IDENTIFIER.match(remaining)
if not m:
raise SyntaxError('name expected: %s' % remaining)
distname = m.groups()[0]
remaining = remaining[m.end():]
extras = mark_expr = versions = uri = None
if remaining and remaining[0] == '[':
i = remaining.find(']', 1)
if i < 0:
raise SyntaxError('unterminated extra: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
extras = []
while s:
m = IDENTIFIER.match(s)
if not m:
raise SyntaxError('malformed extra: %s' % s)
extras.append(m.groups()[0])
s = s[m.end():]
if not s:
break
if s[0] != ',':
raise SyntaxError('comma expected in extras: %s' % s)
s = s[1:].lstrip()
if not extras:
extras = None
if remaining:
if remaining[0] == '@':
# it's a URI
remaining = remaining[1:].lstrip()
m = NON_SPACE.match(remaining)
if not m:
raise SyntaxError('invalid URI: %s' % remaining)
uri = m.groups()[0]
t = urlparse(uri)
# there are issues with Python and URL parsing, so this test
# is a bit crude. See bpo-20271, bpo-23505. Python doesn't
# always parse invalid URLs correctly - it should raise
# exceptions for malformed URLs
if not (t.scheme and t.netloc):
raise SyntaxError('Invalid URL: %s' % uri)
remaining = remaining[m.end():].lstrip()
else:
def get_versions(ver_remaining):
"""
Return a list of operator, version tuples if any are
specified, else None.
"""
m = COMPARE_OP.match(ver_remaining)
versions = None
if m:
versions = []
while True:
op = m.groups()[0]
ver_remaining = ver_remaining[m.end():]
m = VERSION_IDENTIFIER.match(ver_remaining)
if not m:
raise SyntaxError('invalid version: %s' % ver_remaining)
v = m.groups()[0]
versions.append((op, v))
ver_remaining = ver_remaining[m.end():]
if not ver_remaining or ver_remaining[0] != ',':
break
ver_remaining = ver_remaining[1:].lstrip()
m = COMPARE_OP.match(ver_remaining)
if not m:
raise SyntaxError('invalid constraint: %s' % ver_remaining)
if not versions:
versions = None
return versions, ver_remaining
if remaining[0] != '(':
versions, remaining = get_versions(remaining)
else:
i = remaining.find(')', 1)
if i < 0:
raise SyntaxError('unterminated parenthesis: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
# As a special diversion from PEP 508, allow a version number
# a.b.c in parentheses as a synonym for ~= a.b.c (because this
# is allowed in earlier PEPs)
if COMPARE_OP.match(s):
versions, _ = get_versions(s)
else:
m = VERSION_IDENTIFIER.match(s)
if not m:
raise SyntaxError('invalid constraint: %s' % s)
v = m.groups()[0]
s = s[m.end():].lstrip()
if s:
raise SyntaxError('invalid constraint: %s' % s)
versions = [('~=', v)]
if remaining:
if remaining[0] != ';':
raise SyntaxError('invalid requirement: %s' % remaining)
remaining = remaining[1:].lstrip()
mark_expr, remaining = parse_marker(remaining)
if remaining and remaining[0] != '#':
raise SyntaxError('unexpected trailing data: %s' % remaining)
if not versions:
rs = distname
else:
rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
return Container(name=distname, extras=extras, constraints=versions,
marker=mark_expr, url=uri, requirement=rs)
|
[
"def",
"parse_requirement",
"(",
"req",
")",
":",
"remaining",
"=",
"req",
".",
"strip",
"(",
")",
"if",
"not",
"remaining",
"or",
"remaining",
".",
"startswith",
"(",
"'#'",
")",
":",
"return",
"None",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'name expected: %s'",
"%",
"remaining",
")",
"distname",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"extras",
"=",
"mark_expr",
"=",
"versions",
"=",
"uri",
"=",
"None",
"if",
"remaining",
"and",
"remaining",
"[",
"0",
"]",
"==",
"'['",
":",
"i",
"=",
"remaining",
".",
"find",
"(",
"']'",
",",
"1",
")",
"if",
"i",
"<",
"0",
":",
"raise",
"SyntaxError",
"(",
"'unterminated extra: %s'",
"%",
"remaining",
")",
"s",
"=",
"remaining",
"[",
"1",
":",
"i",
"]",
"remaining",
"=",
"remaining",
"[",
"i",
"+",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"extras",
"=",
"[",
"]",
"while",
"s",
":",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"s",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'malformed extra: %s'",
"%",
"s",
")",
"extras",
".",
"append",
"(",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
")",
"s",
"=",
"s",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"if",
"not",
"s",
":",
"break",
"if",
"s",
"[",
"0",
"]",
"!=",
"','",
":",
"raise",
"SyntaxError",
"(",
"'comma expected in extras: %s'",
"%",
"s",
")",
"s",
"=",
"s",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"if",
"not",
"extras",
":",
"extras",
"=",
"None",
"if",
"remaining",
":",
"if",
"remaining",
"[",
"0",
"]",
"==",
"'@'",
":",
"# it's a URI",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"m",
"=",
"NON_SPACE",
".",
"match",
"(",
"remaining",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'invalid URI: %s'",
"%",
"remaining",
")",
"uri",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"t",
"=",
"urlparse",
"(",
"uri",
")",
"# there are issues with Python and URL parsing, so this test",
"# is a bit crude. See bpo-20271, bpo-23505. Python doesn't",
"# always parse invalid URLs correctly - it should raise",
"# exceptions for malformed URLs",
"if",
"not",
"(",
"t",
".",
"scheme",
"and",
"t",
".",
"netloc",
")",
":",
"raise",
"SyntaxError",
"(",
"'Invalid URL: %s'",
"%",
"uri",
")",
"remaining",
"=",
"remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"else",
":",
"def",
"get_versions",
"(",
"ver_remaining",
")",
":",
"\"\"\"\n Return a list of operator, version tuples if any are\n specified, else None.\n \"\"\"",
"m",
"=",
"COMPARE_OP",
".",
"match",
"(",
"ver_remaining",
")",
"versions",
"=",
"None",
"if",
"m",
":",
"versions",
"=",
"[",
"]",
"while",
"True",
":",
"op",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"ver_remaining",
"=",
"ver_remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"m",
"=",
"VERSION_IDENTIFIER",
".",
"match",
"(",
"ver_remaining",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'invalid version: %s'",
"%",
"ver_remaining",
")",
"v",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"versions",
".",
"append",
"(",
"(",
"op",
",",
"v",
")",
")",
"ver_remaining",
"=",
"ver_remaining",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
"if",
"not",
"ver_remaining",
"or",
"ver_remaining",
"[",
"0",
"]",
"!=",
"','",
":",
"break",
"ver_remaining",
"=",
"ver_remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"m",
"=",
"COMPARE_OP",
".",
"match",
"(",
"ver_remaining",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'invalid constraint: %s'",
"%",
"ver_remaining",
")",
"if",
"not",
"versions",
":",
"versions",
"=",
"None",
"return",
"versions",
",",
"ver_remaining",
"if",
"remaining",
"[",
"0",
"]",
"!=",
"'('",
":",
"versions",
",",
"remaining",
"=",
"get_versions",
"(",
"remaining",
")",
"else",
":",
"i",
"=",
"remaining",
".",
"find",
"(",
"')'",
",",
"1",
")",
"if",
"i",
"<",
"0",
":",
"raise",
"SyntaxError",
"(",
"'unterminated parenthesis: %s'",
"%",
"remaining",
")",
"s",
"=",
"remaining",
"[",
"1",
":",
"i",
"]",
"remaining",
"=",
"remaining",
"[",
"i",
"+",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"# As a special diversion from PEP 508, allow a version number",
"# a.b.c in parentheses as a synonym for ~= a.b.c (because this",
"# is allowed in earlier PEPs)",
"if",
"COMPARE_OP",
".",
"match",
"(",
"s",
")",
":",
"versions",
",",
"_",
"=",
"get_versions",
"(",
"s",
")",
"else",
":",
"m",
"=",
"VERSION_IDENTIFIER",
".",
"match",
"(",
"s",
")",
"if",
"not",
"m",
":",
"raise",
"SyntaxError",
"(",
"'invalid constraint: %s'",
"%",
"s",
")",
"v",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"s",
"=",
"s",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"if",
"s",
":",
"raise",
"SyntaxError",
"(",
"'invalid constraint: %s'",
"%",
"s",
")",
"versions",
"=",
"[",
"(",
"'~='",
",",
"v",
")",
"]",
"if",
"remaining",
":",
"if",
"remaining",
"[",
"0",
"]",
"!=",
"';'",
":",
"raise",
"SyntaxError",
"(",
"'invalid requirement: %s'",
"%",
"remaining",
")",
"remaining",
"=",
"remaining",
"[",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
"mark_expr",
",",
"remaining",
"=",
"parse_marker",
"(",
"remaining",
")",
"if",
"remaining",
"and",
"remaining",
"[",
"0",
"]",
"!=",
"'#'",
":",
"raise",
"SyntaxError",
"(",
"'unexpected trailing data: %s'",
"%",
"remaining",
")",
"if",
"not",
"versions",
":",
"rs",
"=",
"distname",
"else",
":",
"rs",
"=",
"'%s %s'",
"%",
"(",
"distname",
",",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"con",
"for",
"con",
"in",
"versions",
"]",
")",
")",
"return",
"Container",
"(",
"name",
"=",
"distname",
",",
"extras",
"=",
"extras",
",",
"constraints",
"=",
"versions",
",",
"marker",
"=",
"mark_expr",
",",
"url",
"=",
"uri",
",",
"requirement",
"=",
"rs",
")"
] |
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.
|
[
"Parse",
"a",
"requirement",
"passed",
"in",
"as",
"a",
"string",
".",
"Return",
"a",
"Container",
"whose",
"attributes",
"contain",
"the",
"various",
"parts",
"of",
"the",
"requirement",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L145-L263
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
convert_path
|
def convert_path(pathname):
"""Return 'pathname' as a name that will work on the native filesystem.
The path is split on '/' and put back together again using the current
directory separator. Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem. Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.
"""
if os.sep == '/':
return pathname
if not pathname:
return pathname
if pathname[0] == '/':
raise ValueError("path '%s' cannot be absolute" % pathname)
if pathname[-1] == '/':
raise ValueError("path '%s' cannot end with '/'" % pathname)
paths = pathname.split('/')
while os.curdir in paths:
paths.remove(os.curdir)
if not paths:
return os.curdir
return os.path.join(*paths)
|
python
|
def convert_path(pathname):
"""Return 'pathname' as a name that will work on the native filesystem.
The path is split on '/' and put back together again using the current
directory separator. Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem. Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.
"""
if os.sep == '/':
return pathname
if not pathname:
return pathname
if pathname[0] == '/':
raise ValueError("path '%s' cannot be absolute" % pathname)
if pathname[-1] == '/':
raise ValueError("path '%s' cannot end with '/'" % pathname)
paths = pathname.split('/')
while os.curdir in paths:
paths.remove(os.curdir)
if not paths:
return os.curdir
return os.path.join(*paths)
|
[
"def",
"convert_path",
"(",
"pathname",
")",
":",
"if",
"os",
".",
"sep",
"==",
"'/'",
":",
"return",
"pathname",
"if",
"not",
"pathname",
":",
"return",
"pathname",
"if",
"pathname",
"[",
"0",
"]",
"==",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"path '%s' cannot be absolute\"",
"%",
"pathname",
")",
"if",
"pathname",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"path '%s' cannot end with '/'\"",
"%",
"pathname",
")",
"paths",
"=",
"pathname",
".",
"split",
"(",
"'/'",
")",
"while",
"os",
".",
"curdir",
"in",
"paths",
":",
"paths",
".",
"remove",
"(",
"os",
".",
"curdir",
")",
"if",
"not",
"paths",
":",
"return",
"os",
".",
"curdir",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"paths",
")"
] |
Return 'pathname' as a name that will work on the native filesystem.
The path is split on '/' and put back together again using the current
directory separator. Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem. Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.
|
[
"Return",
"pathname",
"as",
"a",
"name",
"that",
"will",
"work",
"on",
"the",
"native",
"filesystem",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L451-L475
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
get_cache_base
|
def get_cache_base(suffix=None):
"""
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.
On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.
The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.
"""
if suffix is None:
suffix = '.distlib'
if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
result = os.path.expandvars('$localappdata')
else:
# Assume posix, or old Windows
result = os.path.expanduser('~')
# we use 'isdir' instead of 'exists', because we want to
# fail if there's a file with that name
if os.path.isdir(result):
usable = os.access(result, os.W_OK)
if not usable:
logger.warning('Directory exists but is not writable: %s', result)
else:
try:
os.makedirs(result)
usable = True
except OSError:
logger.warning('Unable to create %s', result, exc_info=True)
usable = False
if not usable:
result = tempfile.mkdtemp()
logger.warning('Default location unusable, using %s', result)
return os.path.join(result, suffix)
|
python
|
def get_cache_base(suffix=None):
"""
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.
On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.
The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.
"""
if suffix is None:
suffix = '.distlib'
if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
result = os.path.expandvars('$localappdata')
else:
# Assume posix, or old Windows
result = os.path.expanduser('~')
# we use 'isdir' instead of 'exists', because we want to
# fail if there's a file with that name
if os.path.isdir(result):
usable = os.access(result, os.W_OK)
if not usable:
logger.warning('Directory exists but is not writable: %s', result)
else:
try:
os.makedirs(result)
usable = True
except OSError:
logger.warning('Unable to create %s', result, exc_info=True)
usable = False
if not usable:
result = tempfile.mkdtemp()
logger.warning('Default location unusable, using %s', result)
return os.path.join(result, suffix)
|
[
"def",
"get_cache_base",
"(",
"suffix",
"=",
"None",
")",
":",
"if",
"suffix",
"is",
"None",
":",
"suffix",
"=",
"'.distlib'",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"'LOCALAPPDATA'",
"in",
"os",
".",
"environ",
":",
"result",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"'$localappdata'",
")",
"else",
":",
"# Assume posix, or old Windows",
"result",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"# we use 'isdir' instead of 'exists', because we want to",
"# fail if there's a file with that name",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"result",
")",
":",
"usable",
"=",
"os",
".",
"access",
"(",
"result",
",",
"os",
".",
"W_OK",
")",
"if",
"not",
"usable",
":",
"logger",
".",
"warning",
"(",
"'Directory exists but is not writable: %s'",
",",
"result",
")",
"else",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"result",
")",
"usable",
"=",
"True",
"except",
"OSError",
":",
"logger",
".",
"warning",
"(",
"'Unable to create %s'",
",",
"result",
",",
"exc_info",
"=",
"True",
")",
"usable",
"=",
"False",
"if",
"not",
"usable",
":",
"result",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"logger",
".",
"warning",
"(",
"'Default location unusable, using %s'",
",",
"result",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"result",
",",
"suffix",
")"
] |
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.
On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.
The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.
|
[
"Return",
"the",
"default",
"base",
"location",
"for",
"distlib",
"caches",
".",
"If",
"the",
"directory",
"does",
"not",
"exist",
"it",
"is",
"created",
".",
"Use",
"the",
"suffix",
"provided",
"for",
"the",
"base",
"directory",
"and",
"default",
"to",
".",
"distlib",
"if",
"it",
"isn",
"t",
"provided",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L740-L778
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
path_to_cache_dir
|
def path_to_cache_dir(path):
"""
Convert an absolute path to a directory name for use in a cache.
The algorithm used is:
#. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
#. Any occurrence of ``os.sep`` is replaced with ``'--'``.
#. ``'.cache'`` is appended.
"""
d, p = os.path.splitdrive(os.path.abspath(path))
if d:
d = d.replace(':', '---')
p = p.replace(os.sep, '--')
return d + p + '.cache'
|
python
|
def path_to_cache_dir(path):
"""
Convert an absolute path to a directory name for use in a cache.
The algorithm used is:
#. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
#. Any occurrence of ``os.sep`` is replaced with ``'--'``.
#. ``'.cache'`` is appended.
"""
d, p = os.path.splitdrive(os.path.abspath(path))
if d:
d = d.replace(':', '---')
p = p.replace(os.sep, '--')
return d + p + '.cache'
|
[
"def",
"path_to_cache_dir",
"(",
"path",
")",
":",
"d",
",",
"p",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"if",
"d",
":",
"d",
"=",
"d",
".",
"replace",
"(",
"':'",
",",
"'---'",
")",
"p",
"=",
"p",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'--'",
")",
"return",
"d",
"+",
"p",
"+",
"'.cache'"
] |
Convert an absolute path to a directory name for use in a cache.
The algorithm used is:
#. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
#. Any occurrence of ``os.sep`` is replaced with ``'--'``.
#. ``'.cache'`` is appended.
|
[
"Convert",
"an",
"absolute",
"path",
"to",
"a",
"directory",
"name",
"for",
"use",
"in",
"a",
"cache",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L781-L795
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
split_filename
|
def split_filename(filename, project_name=None):
"""
Extract name, version, python version from a filename (no extension)
Return name, version, pyver or None
"""
result = None
pyver = None
filename = unquote(filename).replace(' ', '-')
m = PYTHON_VERSION.search(filename)
if m:
pyver = m.group(1)
filename = filename[:m.start()]
if project_name and len(filename) > len(project_name) + 1:
m = re.match(re.escape(project_name) + r'\b', filename)
if m:
n = m.end()
result = filename[:n], filename[n + 1:], pyver
if result is None:
m = PROJECT_NAME_AND_VERSION.match(filename)
if m:
result = m.group(1), m.group(3), pyver
return result
|
python
|
def split_filename(filename, project_name=None):
"""
Extract name, version, python version from a filename (no extension)
Return name, version, pyver or None
"""
result = None
pyver = None
filename = unquote(filename).replace(' ', '-')
m = PYTHON_VERSION.search(filename)
if m:
pyver = m.group(1)
filename = filename[:m.start()]
if project_name and len(filename) > len(project_name) + 1:
m = re.match(re.escape(project_name) + r'\b', filename)
if m:
n = m.end()
result = filename[:n], filename[n + 1:], pyver
if result is None:
m = PROJECT_NAME_AND_VERSION.match(filename)
if m:
result = m.group(1), m.group(3), pyver
return result
|
[
"def",
"split_filename",
"(",
"filename",
",",
"project_name",
"=",
"None",
")",
":",
"result",
"=",
"None",
"pyver",
"=",
"None",
"filename",
"=",
"unquote",
"(",
"filename",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")",
"m",
"=",
"PYTHON_VERSION",
".",
"search",
"(",
"filename",
")",
"if",
"m",
":",
"pyver",
"=",
"m",
".",
"group",
"(",
"1",
")",
"filename",
"=",
"filename",
"[",
":",
"m",
".",
"start",
"(",
")",
"]",
"if",
"project_name",
"and",
"len",
"(",
"filename",
")",
">",
"len",
"(",
"project_name",
")",
"+",
"1",
":",
"m",
"=",
"re",
".",
"match",
"(",
"re",
".",
"escape",
"(",
"project_name",
")",
"+",
"r'\\b'",
",",
"filename",
")",
"if",
"m",
":",
"n",
"=",
"m",
".",
"end",
"(",
")",
"result",
"=",
"filename",
"[",
":",
"n",
"]",
",",
"filename",
"[",
"n",
"+",
"1",
":",
"]",
",",
"pyver",
"if",
"result",
"is",
"None",
":",
"m",
"=",
"PROJECT_NAME_AND_VERSION",
".",
"match",
"(",
"filename",
")",
"if",
"m",
":",
"result",
"=",
"m",
".",
"group",
"(",
"1",
")",
",",
"m",
".",
"group",
"(",
"3",
")",
",",
"pyver",
"return",
"result"
] |
Extract name, version, python version from a filename (no extension)
Return name, version, pyver or None
|
[
"Extract",
"name",
"version",
"python",
"version",
"from",
"a",
"filename",
"(",
"no",
"extension",
")"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L835-L857
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/util.py
|
parse_name_and_version
|
def parse_name_and_version(p):
"""
A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.
"""
m = NAME_VERSION_RE.match(p)
if not m:
raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
d = m.groupdict()
return d['name'].strip().lower(), d['ver']
|
python
|
def parse_name_and_version(p):
"""
A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.
"""
m = NAME_VERSION_RE.match(p)
if not m:
raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
d = m.groupdict()
return d['name'].strip().lower(), d['ver']
|
[
"def",
"parse_name_and_version",
"(",
"p",
")",
":",
"m",
"=",
"NAME_VERSION_RE",
".",
"match",
"(",
"p",
")",
"if",
"not",
"m",
":",
"raise",
"DistlibException",
"(",
"'Ill-formed name/version string: \\'%s\\''",
"%",
"p",
")",
"d",
"=",
"m",
".",
"groupdict",
"(",
")",
"return",
"d",
"[",
"'name'",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
",",
"d",
"[",
"'ver'",
"]"
] |
A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.
|
[
"A",
"utility",
"method",
"used",
"to",
"get",
"name",
"and",
"version",
"from",
"a",
"string",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L863-L876
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.