id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,100 | pypa/pipenv | pipenv/vendor/distlib/locators.py | Locator._get_digest | def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
"""
result = None
for algo in ('sha256', 'md5'):
key = '%s_digest' % algo
if key in info:
result = (algo, info[key])
break
return result | python | def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
"""
result = None
for algo in ('sha256', 'md5'):
key = '%s_digest' % algo
if key in info:
result = (algo, info[key])
break
return result | [
"def",
"_get_digest",
"(",
"self",
",",
"info",
")",
":",
"result",
"=",
"None",
"for",
"algo",
"in",
"(",
"'sha256'",
",",
"'md5'",
")",
":",
"key",
"=",
"'%s_digest'",
"%",
"algo",
"if",
"key",
"in",
"info",
":",
"result",
"=",
"(",
"algo",
",",
"info",
"[",
"key",
"]",
")",
"break",
"return",
"result"
] | Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5. | [
"Get",
"a",
"digest",
"from",
"a",
"dictionary",
"by",
"looking",
"at",
"keys",
"of",
"the",
"form",
"algo_digest",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L305-L319 |
25,101 | pypa/pipenv | pipenv/vendor/distlib/locators.py | Page.links | def links(self):
"""
Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping.
"""
def clean(url):
"Tidy up an URL."
scheme, netloc, path, params, query, frag = urlparse(url)
return urlunparse((scheme, netloc, quote(path),
params, query, frag))
result = set()
for match in self._href.finditer(self.data):
d = match.groupdict('')
rel = (d['rel1'] or d['rel2'] or d['rel3'] or
d['rel4'] or d['rel5'] or d['rel6'])
url = d['url1'] or d['url2'] or d['url3']
url = urljoin(self.base_url, url)
url = unescape(url)
url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
result.add((url, rel))
# We sort the result, hoping to bring the most recent versions
# to the front
result = sorted(result, key=lambda t: t[0], reverse=True)
return result | python | def links(self):
"""
Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping.
"""
def clean(url):
"Tidy up an URL."
scheme, netloc, path, params, query, frag = urlparse(url)
return urlunparse((scheme, netloc, quote(path),
params, query, frag))
result = set()
for match in self._href.finditer(self.data):
d = match.groupdict('')
rel = (d['rel1'] or d['rel2'] or d['rel3'] or
d['rel4'] or d['rel5'] or d['rel6'])
url = d['url1'] or d['url2'] or d['url3']
url = urljoin(self.base_url, url)
url = unescape(url)
url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
result.add((url, rel))
# We sort the result, hoping to bring the most recent versions
# to the front
result = sorted(result, key=lambda t: t[0], reverse=True)
return result | [
"def",
"links",
"(",
"self",
")",
":",
"def",
"clean",
"(",
"url",
")",
":",
"\"Tidy up an URL.\"",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"frag",
"=",
"urlparse",
"(",
"url",
")",
"return",
"urlunparse",
"(",
"(",
"scheme",
",",
"netloc",
",",
"quote",
"(",
"path",
")",
",",
"params",
",",
"query",
",",
"frag",
")",
")",
"result",
"=",
"set",
"(",
")",
"for",
"match",
"in",
"self",
".",
"_href",
".",
"finditer",
"(",
"self",
".",
"data",
")",
":",
"d",
"=",
"match",
".",
"groupdict",
"(",
"''",
")",
"rel",
"=",
"(",
"d",
"[",
"'rel1'",
"]",
"or",
"d",
"[",
"'rel2'",
"]",
"or",
"d",
"[",
"'rel3'",
"]",
"or",
"d",
"[",
"'rel4'",
"]",
"or",
"d",
"[",
"'rel5'",
"]",
"or",
"d",
"[",
"'rel6'",
"]",
")",
"url",
"=",
"d",
"[",
"'url1'",
"]",
"or",
"d",
"[",
"'url2'",
"]",
"or",
"d",
"[",
"'url3'",
"]",
"url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"url",
"=",
"unescape",
"(",
"url",
")",
"url",
"=",
"self",
".",
"_clean_re",
".",
"sub",
"(",
"lambda",
"m",
":",
"'%%%2x'",
"%",
"ord",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
",",
"url",
")",
"result",
".",
"add",
"(",
"(",
"url",
",",
"rel",
")",
")",
"# We sort the result, hoping to bring the most recent versions",
"# to the front",
"result",
"=",
"sorted",
"(",
"result",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
",",
"reverse",
"=",
"True",
")",
"return",
"result"
] | Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping. | [
"Return",
"the",
"URLs",
"of",
"all",
"the",
"links",
"on",
"a",
"page",
"together",
"with",
"information",
"about",
"their",
"rel",
"attribute",
"for",
"determining",
"which",
"ones",
"to",
"treat",
"as",
"downloads",
"and",
"which",
"ones",
"to",
"queue",
"for",
"further",
"scraping",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L551-L576 |
25,102 | pypa/pipenv | pipenv/vendor/distlib/locators.py | SimpleScrapingLocator._process_download | def _process_download(self, url):
"""
See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value.
"""
if self.platform_check and self._is_platform_dependent(url):
info = None
else:
info = self.convert_url_to_download_info(url, self.project_name)
logger.debug('process_download: %s -> %s', url, info)
if info:
with self._lock: # needed because self.result is shared
self._update_version_data(self.result, info)
return info | python | def _process_download(self, url):
"""
See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value.
"""
if self.platform_check and self._is_platform_dependent(url):
info = None
else:
info = self.convert_url_to_download_info(url, self.project_name)
logger.debug('process_download: %s -> %s', url, info)
if info:
with self._lock: # needed because self.result is shared
self._update_version_data(self.result, info)
return info | [
"def",
"_process_download",
"(",
"self",
",",
"url",
")",
":",
"if",
"self",
".",
"platform_check",
"and",
"self",
".",
"_is_platform_dependent",
"(",
"url",
")",
":",
"info",
"=",
"None",
"else",
":",
"info",
"=",
"self",
".",
"convert_url_to_download_info",
"(",
"url",
",",
"self",
".",
"project_name",
")",
"logger",
".",
"debug",
"(",
"'process_download: %s -> %s'",
",",
"url",
",",
"info",
")",
"if",
"info",
":",
"with",
"self",
".",
"_lock",
":",
"# needed because self.result is shared",
"self",
".",
"_update_version_data",
"(",
"self",
".",
"result",
",",
"info",
")",
"return",
"info"
] | See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value. | [
"See",
"if",
"an",
"URL",
"is",
"a",
"suitable",
"download",
"for",
"a",
"project",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L673-L691 |
25,103 | pypa/pipenv | pipenv/vendor/distlib/locators.py | SimpleScrapingLocator._should_queue | def _should_queue(self, link, referrer, rel):
"""
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.
"""
scheme, netloc, path, _, _, _ = urlparse(link)
if path.endswith(self.source_extensions + self.binary_extensions +
self.excluded_extensions):
result = False
elif self.skip_externals and not link.startswith(self.base_url):
result = False
elif not referrer.startswith(self.base_url):
result = False
elif rel not in ('homepage', 'download'):
result = False
elif scheme not in ('http', 'https', 'ftp'):
result = False
elif self._is_platform_dependent(link):
result = False
else:
host = netloc.split(':', 1)[0]
if host.lower() == 'localhost':
result = False
else:
result = True
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
referrer, result)
return result | python | def _should_queue(self, link, referrer, rel):
"""
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.
"""
scheme, netloc, path, _, _, _ = urlparse(link)
if path.endswith(self.source_extensions + self.binary_extensions +
self.excluded_extensions):
result = False
elif self.skip_externals and not link.startswith(self.base_url):
result = False
elif not referrer.startswith(self.base_url):
result = False
elif rel not in ('homepage', 'download'):
result = False
elif scheme not in ('http', 'https', 'ftp'):
result = False
elif self._is_platform_dependent(link):
result = False
else:
host = netloc.split(':', 1)[0]
if host.lower() == 'localhost':
result = False
else:
result = True
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
referrer, result)
return result | [
"def",
"_should_queue",
"(",
"self",
",",
"link",
",",
"referrer",
",",
"rel",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"_",
",",
"_",
",",
"_",
"=",
"urlparse",
"(",
"link",
")",
"if",
"path",
".",
"endswith",
"(",
"self",
".",
"source_extensions",
"+",
"self",
".",
"binary_extensions",
"+",
"self",
".",
"excluded_extensions",
")",
":",
"result",
"=",
"False",
"elif",
"self",
".",
"skip_externals",
"and",
"not",
"link",
".",
"startswith",
"(",
"self",
".",
"base_url",
")",
":",
"result",
"=",
"False",
"elif",
"not",
"referrer",
".",
"startswith",
"(",
"self",
".",
"base_url",
")",
":",
"result",
"=",
"False",
"elif",
"rel",
"not",
"in",
"(",
"'homepage'",
",",
"'download'",
")",
":",
"result",
"=",
"False",
"elif",
"scheme",
"not",
"in",
"(",
"'http'",
",",
"'https'",
",",
"'ftp'",
")",
":",
"result",
"=",
"False",
"elif",
"self",
".",
"_is_platform_dependent",
"(",
"link",
")",
":",
"result",
"=",
"False",
"else",
":",
"host",
"=",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"host",
".",
"lower",
"(",
")",
"==",
"'localhost'",
":",
"result",
"=",
"False",
"else",
":",
"result",
"=",
"True",
"logger",
".",
"debug",
"(",
"'should_queue: %s (%s) from %s -> %s'",
",",
"link",
",",
"rel",
",",
"referrer",
",",
"result",
")",
"return",
"result"
] | Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping. | [
"Determine",
"whether",
"a",
"link",
"URL",
"from",
"a",
"referring",
"page",
"and",
"with",
"a",
"particular",
"rel",
"attribute",
"should",
"be",
"queued",
"for",
"scraping",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L693-L720 |
25,104 | pypa/pipenv | pipenv/vendor/distlib/locators.py | DependencyFinder.find_providers | def find_providers(self, reqt):
"""
Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.
"""
matcher = self.get_matcher(reqt)
name = matcher.key # case-insensitive
result = set()
provided = self.provided
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
result.add(provider)
break
return result | python | def find_providers(self, reqt):
"""
Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.
"""
matcher = self.get_matcher(reqt)
name = matcher.key # case-insensitive
result = set()
provided = self.provided
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
result.add(provider)
break
return result | [
"def",
"find_providers",
"(",
"self",
",",
"reqt",
")",
":",
"matcher",
"=",
"self",
".",
"get_matcher",
"(",
"reqt",
")",
"name",
"=",
"matcher",
".",
"key",
"# case-insensitive",
"result",
"=",
"set",
"(",
")",
"provided",
"=",
"self",
".",
"provided",
"if",
"name",
"in",
"provided",
":",
"for",
"version",
",",
"provider",
"in",
"provided",
"[",
"name",
"]",
":",
"try",
":",
"match",
"=",
"matcher",
".",
"match",
"(",
"version",
")",
"except",
"UnsupportedVersionError",
":",
"match",
"=",
"False",
"if",
"match",
":",
"result",
".",
"add",
"(",
"provider",
")",
"break",
"return",
"result"
] | Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement. | [
"Find",
"the",
"distributions",
"which",
"can",
"fulfill",
"a",
"requirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L1123-L1145 |
25,105 | pypa/pipenv | pipenv/vendor/pexpect/popen_spawn.py | PopenSpawn._read_incoming | def _read_incoming(self):
"""Run in a thread to move output from a pipe to a queue."""
fileno = self.proc.stdout.fileno()
while 1:
buf = b''
try:
buf = os.read(fileno, 1024)
except OSError as e:
self._log(e, 'read')
if not buf:
# This indicates we have reached EOF
self._read_queue.put(None)
return
self._read_queue.put(buf) | python | def _read_incoming(self):
"""Run in a thread to move output from a pipe to a queue."""
fileno = self.proc.stdout.fileno()
while 1:
buf = b''
try:
buf = os.read(fileno, 1024)
except OSError as e:
self._log(e, 'read')
if not buf:
# This indicates we have reached EOF
self._read_queue.put(None)
return
self._read_queue.put(buf) | [
"def",
"_read_incoming",
"(",
"self",
")",
":",
"fileno",
"=",
"self",
".",
"proc",
".",
"stdout",
".",
"fileno",
"(",
")",
"while",
"1",
":",
"buf",
"=",
"b''",
"try",
":",
"buf",
"=",
"os",
".",
"read",
"(",
"fileno",
",",
"1024",
")",
"except",
"OSError",
"as",
"e",
":",
"self",
".",
"_log",
"(",
"e",
",",
"'read'",
")",
"if",
"not",
"buf",
":",
"# This indicates we have reached EOF",
"self",
".",
"_read_queue",
".",
"put",
"(",
"None",
")",
"return",
"self",
".",
"_read_queue",
".",
"put",
"(",
"buf",
")"
] | Run in a thread to move output from a pipe to a queue. | [
"Run",
"in",
"a",
"thread",
"to",
"move",
"output",
"from",
"a",
"pipe",
"to",
"a",
"queue",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/popen_spawn.py#L100-L115 |
25,106 | pypa/pipenv | pipenv/vendor/pexpect/popen_spawn.py | PopenSpawn.send | def send(self, s):
'''Send data to the subprocess' stdin.
Returns the number of bytes written.
'''
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
if PY3:
return self.proc.stdin.write(b)
else:
# On Python 2, .write() returns None, so we return the length of
# bytes written ourselves. This assumes they all got written.
self.proc.stdin.write(b)
return len(b) | python | def send(self, s):
'''Send data to the subprocess' stdin.
Returns the number of bytes written.
'''
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
if PY3:
return self.proc.stdin.write(b)
else:
# On Python 2, .write() returns None, so we return the length of
# bytes written ourselves. This assumes they all got written.
self.proc.stdin.write(b)
return len(b) | [
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")",
"b",
"=",
"self",
".",
"_encoder",
".",
"encode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"if",
"PY3",
":",
"return",
"self",
".",
"proc",
".",
"stdin",
".",
"write",
"(",
"b",
")",
"else",
":",
"# On Python 2, .write() returns None, so we return the length of",
"# bytes written ourselves. This assumes they all got written.",
"self",
".",
"proc",
".",
"stdin",
".",
"write",
"(",
"b",
")",
"return",
"len",
"(",
"b",
")"
] | Send data to the subprocess' stdin.
Returns the number of bytes written. | [
"Send",
"data",
"to",
"the",
"subprocess",
"stdin",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/popen_spawn.py#L132-L147 |
25,107 | pypa/pipenv | pipenv/vendor/pexpect/popen_spawn.py | PopenSpawn.wait | def wait(self):
'''Wait for the subprocess to finish.
Returns the exit code.
'''
status = self.proc.wait()
if status >= 0:
self.exitstatus = status
self.signalstatus = None
else:
self.exitstatus = None
self.signalstatus = -status
self.terminated = True
return status | python | def wait(self):
'''Wait for the subprocess to finish.
Returns the exit code.
'''
status = self.proc.wait()
if status >= 0:
self.exitstatus = status
self.signalstatus = None
else:
self.exitstatus = None
self.signalstatus = -status
self.terminated = True
return status | [
"def",
"wait",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"proc",
".",
"wait",
"(",
")",
"if",
"status",
">=",
"0",
":",
"self",
".",
"exitstatus",
"=",
"status",
"self",
".",
"signalstatus",
"=",
"None",
"else",
":",
"self",
".",
"exitstatus",
"=",
"None",
"self",
".",
"signalstatus",
"=",
"-",
"status",
"self",
".",
"terminated",
"=",
"True",
"return",
"status"
] | Wait for the subprocess to finish.
Returns the exit code. | [
"Wait",
"for",
"the",
"subprocess",
"to",
"finish",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/popen_spawn.py#L156-L169 |
25,108 | pypa/pipenv | pipenv/vendor/pexpect/popen_spawn.py | PopenSpawn.kill | def kill(self, sig):
'''Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal.
'''
if sys.platform == 'win32':
if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
sig = signal.CTRL_C_EVENT
elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
sig = signal.CTRL_BREAK_EVENT
else:
sig = signal.SIGTERM
os.kill(self.proc.pid, sig) | python | def kill(self, sig):
'''Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal.
'''
if sys.platform == 'win32':
if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
sig = signal.CTRL_C_EVENT
elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
sig = signal.CTRL_BREAK_EVENT
else:
sig = signal.SIGTERM
os.kill(self.proc.pid, sig) | [
"def",
"kill",
"(",
"self",
",",
"sig",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"if",
"sig",
"in",
"[",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"CTRL_C_EVENT",
"]",
":",
"sig",
"=",
"signal",
".",
"CTRL_C_EVENT",
"elif",
"sig",
"in",
"[",
"signal",
".",
"SIGBREAK",
",",
"signal",
".",
"CTRL_BREAK_EVENT",
"]",
":",
"sig",
"=",
"signal",
".",
"CTRL_BREAK_EVENT",
"else",
":",
"sig",
"=",
"signal",
".",
"SIGTERM",
"os",
".",
"kill",
"(",
"self",
".",
"proc",
".",
"pid",
",",
"sig",
")"
] | Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal. | [
"Sends",
"a",
"Unix",
"signal",
"to",
"the",
"subprocess",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/popen_spawn.py#L171-L184 |
25,109 | pypa/pipenv | pipenv/vendor/pep517/build.py | mkdir_p | def mkdir_p(*args, **kwargs):
"""Like `mkdir`, but does not raise an exception if the
directory already exists.
"""
try:
return os.mkdir(*args, **kwargs)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise | python | def mkdir_p(*args, **kwargs):
"""Like `mkdir`, but does not raise an exception if the
directory already exists.
"""
try:
return os.mkdir(*args, **kwargs)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise | [
"def",
"mkdir_p",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"os",
".",
"mkdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise"
] | Like `mkdir`, but does not raise an exception if the
directory already exists. | [
"Like",
"mkdir",
"but",
"does",
"not",
"raise",
"an",
"exception",
"if",
"the",
"directory",
"already",
"exists",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/build.py#L45-L53 |
25,110 | pypa/pipenv | pipenv/vendor/parse.py | with_pattern | def with_pattern(pattern, regex_group_count=None):
"""Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equivalent to:
>>> def parse_number(text):
... return int(text)
>>> parse_number.pattern = r"\d+"
:param pattern: regular expression pattern (as text)
:param regex_group_count: Indicates how many regex-groups are in pattern.
:return: wrapped function
"""
def decorator(func):
func.pattern = pattern
func.regex_group_count = regex_group_count
return func
return decorator | python | def with_pattern(pattern, regex_group_count=None):
"""Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equivalent to:
>>> def parse_number(text):
... return int(text)
>>> parse_number.pattern = r"\d+"
:param pattern: regular expression pattern (as text)
:param regex_group_count: Indicates how many regex-groups are in pattern.
:return: wrapped function
"""
def decorator(func):
func.pattern = pattern
func.regex_group_count = regex_group_count
return func
return decorator | [
"def",
"with_pattern",
"(",
"pattern",
",",
"regex_group_count",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"pattern",
"=",
"pattern",
"func",
".",
"regex_group_count",
"=",
"regex_group_count",
"return",
"func",
"return",
"decorator"
] | Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equivalent to:
>>> def parse_number(text):
... return int(text)
>>> parse_number.pattern = r"\d+"
:param pattern: regular expression pattern (as text)
:param regex_group_count: Indicates how many regex-groups are in pattern.
:return: wrapped function | [
"Attach",
"a",
"regular",
"expression",
"pattern",
"matcher",
"to",
"a",
"custom",
"type",
"converter",
"function",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L433-L459 |
25,111 | pypa/pipenv | pipenv/vendor/parse.py | parse | def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False):
'''Using "format" attempt to pull values from "string".
The format must match the string contents exactly. If the value
you're looking for is instead just a part of the string use
search().
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None.
'''
p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive)
return p.parse(string, evaluate_result=evaluate_result) | python | def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False):
'''Using "format" attempt to pull values from "string".
The format must match the string contents exactly. If the value
you're looking for is instead just a part of the string use
search().
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None.
'''
p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive)
return p.parse(string, evaluate_result=evaluate_result) | [
"def",
"parse",
"(",
"format",
",",
"string",
",",
"extra_types",
"=",
"None",
",",
"evaluate_result",
"=",
"True",
",",
"case_sensitive",
"=",
"False",
")",
":",
"p",
"=",
"Parser",
"(",
"format",
",",
"extra_types",
"=",
"extra_types",
",",
"case_sensitive",
"=",
"case_sensitive",
")",
"return",
"p",
".",
"parse",
"(",
"string",
",",
"evaluate_result",
"=",
"evaluate_result",
")"
] | Using "format" attempt to pull values from "string".
The format must match the string contents exactly. If the value
you're looking for is instead just a part of the string use
search().
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None. | [
"Using",
"format",
"attempt",
"to",
"pull",
"values",
"from",
"string",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L1201-L1228 |
25,112 | pypa/pipenv | pipenv/vendor/parse.py | search | def search(format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True,
case_sensitive=False):
'''Search "string" for the first occurrence of "format".
The format may occur anywhere within the string. If
instead you wish for the format to exactly match the string
use parse().
Optionally start the search at "pos" character index and limit the search
to a maximum index of endpos - equivalent to search(string[:endpos]).
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None.
'''
p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive)
return p.search(string, pos, endpos, evaluate_result=evaluate_result) | python | def search(format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True,
case_sensitive=False):
'''Search "string" for the first occurrence of "format".
The format may occur anywhere within the string. If
instead you wish for the format to exactly match the string
use parse().
Optionally start the search at "pos" character index and limit the search
to a maximum index of endpos - equivalent to search(string[:endpos]).
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None.
'''
p = Parser(format, extra_types=extra_types, case_sensitive=case_sensitive)
return p.search(string, pos, endpos, evaluate_result=evaluate_result) | [
"def",
"search",
"(",
"format",
",",
"string",
",",
"pos",
"=",
"0",
",",
"endpos",
"=",
"None",
",",
"extra_types",
"=",
"None",
",",
"evaluate_result",
"=",
"True",
",",
"case_sensitive",
"=",
"False",
")",
":",
"p",
"=",
"Parser",
"(",
"format",
",",
"extra_types",
"=",
"extra_types",
",",
"case_sensitive",
"=",
"case_sensitive",
")",
"return",
"p",
".",
"search",
"(",
"string",
",",
"pos",
",",
"endpos",
",",
"evaluate_result",
"=",
"evaluate_result",
")"
] | Search "string" for the first occurrence of "format".
The format may occur anywhere within the string. If
instead you wish for the format to exactly match the string
use parse().
Optionally start the search at "pos" character index and limit the search
to a maximum index of endpos - equivalent to search(string[:endpos]).
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tuple of fixed-position values from the string
.named - dict of named values from the string
If ``evaluate_result`` is False the return value will be a Match instance with one method:
.evaluate_result() - This will return a Result instance like you would get
with ``evaluate_result`` set to True
The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.
If the format is invalid a ValueError will be raised.
See the module documentation for the use of "extra_types".
In the case there is no match parse() will return None. | [
"Search",
"string",
"for",
"the",
"first",
"occurrence",
"of",
"format",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L1231-L1262 |
25,113 | pypa/pipenv | pipenv/vendor/parse.py | Parser.parse | def parse(self, string, evaluate_result=True):
'''Match my format to the string exactly.
Return a Result or Match instance or None if there's no match.
'''
m = self._match_re.match(string)
if m is None:
return None
if evaluate_result:
return self.evaluate_result(m)
else:
return Match(self, m) | python | def parse(self, string, evaluate_result=True):
'''Match my format to the string exactly.
Return a Result or Match instance or None if there's no match.
'''
m = self._match_re.match(string)
if m is None:
return None
if evaluate_result:
return self.evaluate_result(m)
else:
return Match(self, m) | [
"def",
"parse",
"(",
"self",
",",
"string",
",",
"evaluate_result",
"=",
"True",
")",
":",
"m",
"=",
"self",
".",
"_match_re",
".",
"match",
"(",
"string",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"if",
"evaluate_result",
":",
"return",
"self",
".",
"evaluate_result",
"(",
"m",
")",
"else",
":",
"return",
"Match",
"(",
"self",
",",
"m",
")"
] | Match my format to the string exactly.
Return a Result or Match instance or None if there's no match. | [
"Match",
"my",
"format",
"to",
"the",
"string",
"exactly",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L773-L785 |
25,114 | pypa/pipenv | pipenv/vendor/parse.py | Parser.search | def search(self, string, pos=0, endpos=None, evaluate_result=True):
'''Search the string for my format.
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
If the ``evaluate_result`` argument is set to ``False`` a
Match instance is returned instead of the actual Result instance.
Return either a Result instance or None if there's no match.
'''
if endpos is None:
endpos = len(string)
m = self._search_re.search(string, pos, endpos)
if m is None:
return None
if evaluate_result:
return self.evaluate_result(m)
else:
return Match(self, m) | python | def search(self, string, pos=0, endpos=None, evaluate_result=True):
'''Search the string for my format.
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
If the ``evaluate_result`` argument is set to ``False`` a
Match instance is returned instead of the actual Result instance.
Return either a Result instance or None if there's no match.
'''
if endpos is None:
endpos = len(string)
m = self._search_re.search(string, pos, endpos)
if m is None:
return None
if evaluate_result:
return self.evaluate_result(m)
else:
return Match(self, m) | [
"def",
"search",
"(",
"self",
",",
"string",
",",
"pos",
"=",
"0",
",",
"endpos",
"=",
"None",
",",
"evaluate_result",
"=",
"True",
")",
":",
"if",
"endpos",
"is",
"None",
":",
"endpos",
"=",
"len",
"(",
"string",
")",
"m",
"=",
"self",
".",
"_search_re",
".",
"search",
"(",
"string",
",",
"pos",
",",
"endpos",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"if",
"evaluate_result",
":",
"return",
"self",
".",
"evaluate_result",
"(",
"m",
")",
"else",
":",
"return",
"Match",
"(",
"self",
",",
"m",
")"
] | Search the string for my format.
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
If the ``evaluate_result`` argument is set to ``False`` a
Match instance is returned instead of the actual Result instance.
Return either a Result instance or None if there's no match. | [
"Search",
"the",
"string",
"for",
"my",
"format",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L787-L808 |
25,115 | pypa/pipenv | pipenv/vendor/parse.py | Parser.findall | def findall(self, string, pos=0, endpos=None, extra_types=None, evaluate_result=True):
'''Search "string" for all occurrences of "format".
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
Returns an iterator that holds Result or Match instances for each format match
found.
'''
if endpos is None:
endpos = len(string)
return ResultIterator(self, string, pos, endpos, evaluate_result=evaluate_result) | python | def findall(self, string, pos=0, endpos=None, extra_types=None, evaluate_result=True):
'''Search "string" for all occurrences of "format".
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
Returns an iterator that holds Result or Match instances for each format match
found.
'''
if endpos is None:
endpos = len(string)
return ResultIterator(self, string, pos, endpos, evaluate_result=evaluate_result) | [
"def",
"findall",
"(",
"self",
",",
"string",
",",
"pos",
"=",
"0",
",",
"endpos",
"=",
"None",
",",
"extra_types",
"=",
"None",
",",
"evaluate_result",
"=",
"True",
")",
":",
"if",
"endpos",
"is",
"None",
":",
"endpos",
"=",
"len",
"(",
"string",
")",
"return",
"ResultIterator",
"(",
"self",
",",
"string",
",",
"pos",
",",
"endpos",
",",
"evaluate_result",
"=",
"evaluate_result",
")"
] | Search "string" for all occurrences of "format".
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
Returns an iterator that holds Result or Match instances for each format match
found. | [
"Search",
"string",
"for",
"all",
"occurrences",
"of",
"format",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L810-L822 |
25,116 | pypa/pipenv | pipenv/vendor/parse.py | Parser.evaluate_result | def evaluate_result(self, m):
'''Generate a Result instance for the given regex match object'''
# ok, figure the fixed fields we've pulled out and type convert them
fixed_fields = list(m.groups())
for n in self._fixed_fields:
if n in self._type_conversions:
fixed_fields[n] = self._type_conversions[n](fixed_fields[n], m)
fixed_fields = tuple(fixed_fields[n] for n in self._fixed_fields)
# grab the named fields, converting where requested
groupdict = m.groupdict()
named_fields = {}
name_map = {}
for k in self._named_fields:
korig = self._group_to_name_map[k]
name_map[korig] = k
if k in self._type_conversions:
value = self._type_conversions[k](groupdict[k], m)
else:
value = groupdict[k]
named_fields[korig] = value
# now figure the match spans
spans = dict((n, m.span(name_map[n])) for n in named_fields)
spans.update((i, m.span(n + 1))
for i, n in enumerate(self._fixed_fields))
# and that's our result
return Result(fixed_fields, self._expand_named_fields(named_fields), spans) | python | def evaluate_result(self, m):
'''Generate a Result instance for the given regex match object'''
# ok, figure the fixed fields we've pulled out and type convert them
fixed_fields = list(m.groups())
for n in self._fixed_fields:
if n in self._type_conversions:
fixed_fields[n] = self._type_conversions[n](fixed_fields[n], m)
fixed_fields = tuple(fixed_fields[n] for n in self._fixed_fields)
# grab the named fields, converting where requested
groupdict = m.groupdict()
named_fields = {}
name_map = {}
for k in self._named_fields:
korig = self._group_to_name_map[k]
name_map[korig] = k
if k in self._type_conversions:
value = self._type_conversions[k](groupdict[k], m)
else:
value = groupdict[k]
named_fields[korig] = value
# now figure the match spans
spans = dict((n, m.span(name_map[n])) for n in named_fields)
spans.update((i, m.span(n + 1))
for i, n in enumerate(self._fixed_fields))
# and that's our result
return Result(fixed_fields, self._expand_named_fields(named_fields), spans) | [
"def",
"evaluate_result",
"(",
"self",
",",
"m",
")",
":",
"# ok, figure the fixed fields we've pulled out and type convert them",
"fixed_fields",
"=",
"list",
"(",
"m",
".",
"groups",
"(",
")",
")",
"for",
"n",
"in",
"self",
".",
"_fixed_fields",
":",
"if",
"n",
"in",
"self",
".",
"_type_conversions",
":",
"fixed_fields",
"[",
"n",
"]",
"=",
"self",
".",
"_type_conversions",
"[",
"n",
"]",
"(",
"fixed_fields",
"[",
"n",
"]",
",",
"m",
")",
"fixed_fields",
"=",
"tuple",
"(",
"fixed_fields",
"[",
"n",
"]",
"for",
"n",
"in",
"self",
".",
"_fixed_fields",
")",
"# grab the named fields, converting where requested",
"groupdict",
"=",
"m",
".",
"groupdict",
"(",
")",
"named_fields",
"=",
"{",
"}",
"name_map",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_named_fields",
":",
"korig",
"=",
"self",
".",
"_group_to_name_map",
"[",
"k",
"]",
"name_map",
"[",
"korig",
"]",
"=",
"k",
"if",
"k",
"in",
"self",
".",
"_type_conversions",
":",
"value",
"=",
"self",
".",
"_type_conversions",
"[",
"k",
"]",
"(",
"groupdict",
"[",
"k",
"]",
",",
"m",
")",
"else",
":",
"value",
"=",
"groupdict",
"[",
"k",
"]",
"named_fields",
"[",
"korig",
"]",
"=",
"value",
"# now figure the match spans",
"spans",
"=",
"dict",
"(",
"(",
"n",
",",
"m",
".",
"span",
"(",
"name_map",
"[",
"n",
"]",
")",
")",
"for",
"n",
"in",
"named_fields",
")",
"spans",
".",
"update",
"(",
"(",
"i",
",",
"m",
".",
"span",
"(",
"n",
"+",
"1",
")",
")",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"self",
".",
"_fixed_fields",
")",
")",
"# and that's our result",
"return",
"Result",
"(",
"fixed_fields",
",",
"self",
".",
"_expand_named_fields",
"(",
"named_fields",
")",
",",
"spans",
")"
] | Generate a Result instance for the given regex match object | [
"Generate",
"a",
"Result",
"instance",
"for",
"the",
"given",
"regex",
"match",
"object"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L844-L873 |
25,117 | pypa/pipenv | pipenv/cli/command.py | uninstall | def uninstall(
ctx,
state,
all_dev=False,
all=False,
**kwargs
):
"""Un-installs a provided package and removes it from Pipfile."""
from ..core import do_uninstall
retcode = do_uninstall(
packages=state.installstate.packages,
editable_packages=state.installstate.editables,
three=state.three,
python=state.python,
system=state.system,
lock=not state.installstate.skip_lock,
all_dev=all_dev,
all=all,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
ctx=ctx
)
if retcode:
sys.exit(retcode) | python | def uninstall(
ctx,
state,
all_dev=False,
all=False,
**kwargs
):
"""Un-installs a provided package and removes it from Pipfile."""
from ..core import do_uninstall
retcode = do_uninstall(
packages=state.installstate.packages,
editable_packages=state.installstate.editables,
three=state.three,
python=state.python,
system=state.system,
lock=not state.installstate.skip_lock,
all_dev=all_dev,
all=all,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
ctx=ctx
)
if retcode:
sys.exit(retcode) | [
"def",
"uninstall",
"(",
"ctx",
",",
"state",
",",
"all_dev",
"=",
"False",
",",
"all",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"do_uninstall",
"retcode",
"=",
"do_uninstall",
"(",
"packages",
"=",
"state",
".",
"installstate",
".",
"packages",
",",
"editable_packages",
"=",
"state",
".",
"installstate",
".",
"editables",
",",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"system",
"=",
"state",
".",
"system",
",",
"lock",
"=",
"not",
"state",
".",
"installstate",
".",
"skip_lock",
",",
"all_dev",
"=",
"all_dev",
",",
"all",
"=",
"all",
",",
"keep_outdated",
"=",
"state",
".",
"installstate",
".",
"keep_outdated",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
"ctx",
"=",
"ctx",
")",
"if",
"retcode",
":",
"sys",
".",
"exit",
"(",
"retcode",
")"
] | Un-installs a provided package and removes it from Pipfile. | [
"Un",
"-",
"installs",
"a",
"provided",
"package",
"and",
"removes",
"it",
"from",
"Pipfile",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L280-L303 |
25,118 | pypa/pipenv | pipenv/cli/command.py | lock | def lock(
ctx,
state,
**kwargs
):
"""Generates Pipfile.lock."""
from ..core import ensure_project, do_init, do_lock
# Ensure that virtualenv is available.
ensure_project(three=state.three, python=state.python, pypi_mirror=state.pypi_mirror)
if state.installstate.requirementstxt:
do_init(
dev=state.installstate.dev,
requirements=state.installstate.requirementstxt,
pypi_mirror=state.pypi_mirror,
pre=state.installstate.pre,
)
do_lock(
ctx=ctx,
clear=state.clear,
pre=state.installstate.pre,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
) | python | def lock(
ctx,
state,
**kwargs
):
"""Generates Pipfile.lock."""
from ..core import ensure_project, do_init, do_lock
# Ensure that virtualenv is available.
ensure_project(three=state.three, python=state.python, pypi_mirror=state.pypi_mirror)
if state.installstate.requirementstxt:
do_init(
dev=state.installstate.dev,
requirements=state.installstate.requirementstxt,
pypi_mirror=state.pypi_mirror,
pre=state.installstate.pre,
)
do_lock(
ctx=ctx,
clear=state.clear,
pre=state.installstate.pre,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
) | [
"def",
"lock",
"(",
"ctx",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"ensure_project",
",",
"do_init",
",",
"do_lock",
"# Ensure that virtualenv is available.",
"ensure_project",
"(",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
")",
"if",
"state",
".",
"installstate",
".",
"requirementstxt",
":",
"do_init",
"(",
"dev",
"=",
"state",
".",
"installstate",
".",
"dev",
",",
"requirements",
"=",
"state",
".",
"installstate",
".",
"requirementstxt",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
"pre",
"=",
"state",
".",
"installstate",
".",
"pre",
",",
")",
"do_lock",
"(",
"ctx",
"=",
"ctx",
",",
"clear",
"=",
"state",
".",
"clear",
",",
"pre",
"=",
"state",
".",
"installstate",
".",
"pre",
",",
"keep_outdated",
"=",
"state",
".",
"installstate",
".",
"keep_outdated",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")"
] | Generates Pipfile.lock. | [
"Generates",
"Pipfile",
".",
"lock",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L310-L333 |
25,119 | pypa/pipenv | pipenv/cli/command.py | shell | def shell(
state,
fancy=False,
shell_args=None,
anyway=False,
):
"""Spawns a shell within the virtualenv."""
from ..core import load_dot_env, do_shell
# Prevent user from activating nested environments.
if "PIPENV_ACTIVE" in os.environ:
# If PIPENV_ACTIVE is set, VIRTUAL_ENV should always be set too.
venv_name = os.environ.get("VIRTUAL_ENV", "UNKNOWN_VIRTUAL_ENVIRONMENT")
if not anyway:
echo(
"{0} {1} {2}\nNo action taken to avoid nested environments.".format(
crayons.normal("Shell for"),
crayons.green(venv_name, bold=True),
crayons.normal("already activated.", bold=True),
),
err=True,
)
sys.exit(1)
# Load .env file.
load_dot_env()
# Use fancy mode for Windows.
if os.name == "nt":
fancy = True
do_shell(
three=state.three,
python=state.python,
fancy=fancy,
shell_args=shell_args,
pypi_mirror=state.pypi_mirror,
) | python | def shell(
state,
fancy=False,
shell_args=None,
anyway=False,
):
"""Spawns a shell within the virtualenv."""
from ..core import load_dot_env, do_shell
# Prevent user from activating nested environments.
if "PIPENV_ACTIVE" in os.environ:
# If PIPENV_ACTIVE is set, VIRTUAL_ENV should always be set too.
venv_name = os.environ.get("VIRTUAL_ENV", "UNKNOWN_VIRTUAL_ENVIRONMENT")
if not anyway:
echo(
"{0} {1} {2}\nNo action taken to avoid nested environments.".format(
crayons.normal("Shell for"),
crayons.green(venv_name, bold=True),
crayons.normal("already activated.", bold=True),
),
err=True,
)
sys.exit(1)
# Load .env file.
load_dot_env()
# Use fancy mode for Windows.
if os.name == "nt":
fancy = True
do_shell(
three=state.three,
python=state.python,
fancy=fancy,
shell_args=shell_args,
pypi_mirror=state.pypi_mirror,
) | [
"def",
"shell",
"(",
"state",
",",
"fancy",
"=",
"False",
",",
"shell_args",
"=",
"None",
",",
"anyway",
"=",
"False",
",",
")",
":",
"from",
".",
".",
"core",
"import",
"load_dot_env",
",",
"do_shell",
"# Prevent user from activating nested environments.",
"if",
"\"PIPENV_ACTIVE\"",
"in",
"os",
".",
"environ",
":",
"# If PIPENV_ACTIVE is set, VIRTUAL_ENV should always be set too.",
"venv_name",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"VIRTUAL_ENV\"",
",",
"\"UNKNOWN_VIRTUAL_ENVIRONMENT\"",
")",
"if",
"not",
"anyway",
":",
"echo",
"(",
"\"{0} {1} {2}\\nNo action taken to avoid nested environments.\"",
".",
"format",
"(",
"crayons",
".",
"normal",
"(",
"\"Shell for\"",
")",
",",
"crayons",
".",
"green",
"(",
"venv_name",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"normal",
"(",
"\"already activated.\"",
",",
"bold",
"=",
"True",
")",
",",
")",
",",
"err",
"=",
"True",
",",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Load .env file.",
"load_dot_env",
"(",
")",
"# Use fancy mode for Windows.",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"fancy",
"=",
"True",
"do_shell",
"(",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"fancy",
"=",
"fancy",
",",
"shell_args",
"=",
"shell_args",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")"
] | Spawns a shell within the virtualenv. | [
"Spawns",
"a",
"shell",
"within",
"the",
"virtualenv",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L357-L391 |
25,120 | pypa/pipenv | pipenv/cli/command.py | run | def run(state, command, args):
"""Spawns a command installed into the virtualenv."""
from ..core import do_run
do_run(
command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror
) | python | def run(state, command, args):
"""Spawns a command installed into the virtualenv."""
from ..core import do_run
do_run(
command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror
) | [
"def",
"run",
"(",
"state",
",",
"command",
",",
"args",
")",
":",
"from",
".",
".",
"core",
"import",
"do_run",
"do_run",
"(",
"command",
"=",
"command",
",",
"args",
"=",
"args",
",",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
")"
] | Spawns a command installed into the virtualenv. | [
"Spawns",
"a",
"command",
"installed",
"into",
"the",
"virtualenv",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L403-L408 |
25,121 | pypa/pipenv | pipenv/cli/command.py | check | def check(
state,
unused=False,
style=False,
ignore=None,
args=None,
**kwargs
):
"""Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile."""
from ..core import do_check
do_check(
three=state.three,
python=state.python,
system=state.system,
unused=unused,
ignore=ignore,
args=args,
pypi_mirror=state.pypi_mirror,
) | python | def check(
state,
unused=False,
style=False,
ignore=None,
args=None,
**kwargs
):
"""Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile."""
from ..core import do_check
do_check(
three=state.three,
python=state.python,
system=state.system,
unused=unused,
ignore=ignore,
args=args,
pypi_mirror=state.pypi_mirror,
) | [
"def",
"check",
"(",
"state",
",",
"unused",
"=",
"False",
",",
"style",
"=",
"False",
",",
"ignore",
"=",
"None",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"do_check",
"do_check",
"(",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"system",
"=",
"state",
".",
"system",
",",
"unused",
"=",
"unused",
",",
"ignore",
"=",
"ignore",
",",
"args",
"=",
"args",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")"
] | Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile. | [
"Checks",
"for",
"security",
"vulnerabilities",
"and",
"against",
"PEP",
"508",
"markers",
"provided",
"in",
"Pipfile",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L431-L450 |
25,122 | pypa/pipenv | pipenv/cli/command.py | update | def update(
ctx,
state,
bare=False,
dry_run=None,
outdated=False,
**kwargs
):
"""Runs lock, then sync."""
from ..core import (
ensure_project,
do_outdated,
do_lock,
do_sync,
project,
)
ensure_project(three=state.three, python=state.python, warn=True, pypi_mirror=state.pypi_mirror)
if not outdated:
outdated = bool(dry_run)
if outdated:
do_outdated(pypi_mirror=state.pypi_mirror)
packages = [p for p in state.installstate.packages if p]
editable = [p for p in state.installstate.editables if p]
if not packages:
echo(
"{0} {1} {2} {3}{4}".format(
crayons.white("Running", bold=True),
crayons.red("$ pipenv lock", bold=True),
crayons.white("then", bold=True),
crayons.red("$ pipenv sync", bold=True),
crayons.white(".", bold=True),
)
)
else:
for package in packages + editable:
if package not in project.all_packages:
echo(
"{0}: {1} was not found in your Pipfile! Aborting."
"".format(
crayons.red("Warning", bold=True),
crayons.green(package, bold=True),
),
err=True,
)
ctx.abort()
do_lock(
clear=state.clear,
pre=state.installstate.pre,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
)
do_sync(
ctx=ctx,
dev=state.installstate.dev,
three=state.three,
python=state.python,
bare=bare,
dont_upgrade=not state.installstate.keep_outdated,
user=False,
clear=state.clear,
unused=False,
sequential=state.installstate.sequential,
pypi_mirror=state.pypi_mirror,
) | python | def update(
ctx,
state,
bare=False,
dry_run=None,
outdated=False,
**kwargs
):
"""Runs lock, then sync."""
from ..core import (
ensure_project,
do_outdated,
do_lock,
do_sync,
project,
)
ensure_project(three=state.three, python=state.python, warn=True, pypi_mirror=state.pypi_mirror)
if not outdated:
outdated = bool(dry_run)
if outdated:
do_outdated(pypi_mirror=state.pypi_mirror)
packages = [p for p in state.installstate.packages if p]
editable = [p for p in state.installstate.editables if p]
if not packages:
echo(
"{0} {1} {2} {3}{4}".format(
crayons.white("Running", bold=True),
crayons.red("$ pipenv lock", bold=True),
crayons.white("then", bold=True),
crayons.red("$ pipenv sync", bold=True),
crayons.white(".", bold=True),
)
)
else:
for package in packages + editable:
if package not in project.all_packages:
echo(
"{0}: {1} was not found in your Pipfile! Aborting."
"".format(
crayons.red("Warning", bold=True),
crayons.green(package, bold=True),
),
err=True,
)
ctx.abort()
do_lock(
clear=state.clear,
pre=state.installstate.pre,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
)
do_sync(
ctx=ctx,
dev=state.installstate.dev,
three=state.three,
python=state.python,
bare=bare,
dont_upgrade=not state.installstate.keep_outdated,
user=False,
clear=state.clear,
unused=False,
sequential=state.installstate.sequential,
pypi_mirror=state.pypi_mirror,
) | [
"def",
"update",
"(",
"ctx",
",",
"state",
",",
"bare",
"=",
"False",
",",
"dry_run",
"=",
"None",
",",
"outdated",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"(",
"ensure_project",
",",
"do_outdated",
",",
"do_lock",
",",
"do_sync",
",",
"project",
",",
")",
"ensure_project",
"(",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"warn",
"=",
"True",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
")",
"if",
"not",
"outdated",
":",
"outdated",
"=",
"bool",
"(",
"dry_run",
")",
"if",
"outdated",
":",
"do_outdated",
"(",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
")",
"packages",
"=",
"[",
"p",
"for",
"p",
"in",
"state",
".",
"installstate",
".",
"packages",
"if",
"p",
"]",
"editable",
"=",
"[",
"p",
"for",
"p",
"in",
"state",
".",
"installstate",
".",
"editables",
"if",
"p",
"]",
"if",
"not",
"packages",
":",
"echo",
"(",
"\"{0} {1} {2} {3}{4}\"",
".",
"format",
"(",
"crayons",
".",
"white",
"(",
"\"Running\"",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"red",
"(",
"\"$ pipenv lock\"",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"white",
"(",
"\"then\"",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"red",
"(",
"\"$ pipenv sync\"",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"white",
"(",
"\".\"",
",",
"bold",
"=",
"True",
")",
",",
")",
")",
"else",
":",
"for",
"package",
"in",
"packages",
"+",
"editable",
":",
"if",
"package",
"not",
"in",
"project",
".",
"all_packages",
":",
"echo",
"(",
"\"{0}: {1} was not found in your Pipfile! Aborting.\"",
"\"\"",
".",
"format",
"(",
"crayons",
".",
"red",
"(",
"\"Warning\"",
",",
"bold",
"=",
"True",
")",
",",
"crayons",
".",
"green",
"(",
"package",
",",
"bold",
"=",
"True",
")",
",",
")",
",",
"err",
"=",
"True",
",",
")",
"ctx",
".",
"abort",
"(",
")",
"do_lock",
"(",
"clear",
"=",
"state",
".",
"clear",
",",
"pre",
"=",
"state",
".",
"installstate",
".",
"pre",
",",
"keep_outdated",
"=",
"state",
".",
"installstate",
".",
"keep_outdated",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")",
"do_sync",
"(",
"ctx",
"=",
"ctx",
",",
"dev",
"=",
"state",
".",
"installstate",
".",
"dev",
",",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"bare",
"=",
"bare",
",",
"dont_upgrade",
"=",
"not",
"state",
".",
"installstate",
".",
"keep_outdated",
",",
"user",
"=",
"False",
",",
"clear",
"=",
"state",
".",
"clear",
",",
"unused",
"=",
"False",
",",
"sequential",
"=",
"state",
".",
"installstate",
".",
"sequential",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")"
] | Runs lock, then sync. | [
"Runs",
"lock",
"then",
"sync",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L462-L527 |
25,123 | pypa/pipenv | pipenv/cli/command.py | graph | def graph(bare=False, json=False, json_tree=False, reverse=False):
"""Displays currently-installed dependency graph information."""
from ..core import do_graph
do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse) | python | def graph(bare=False, json=False, json_tree=False, reverse=False):
"""Displays currently-installed dependency graph information."""
from ..core import do_graph
do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse) | [
"def",
"graph",
"(",
"bare",
"=",
"False",
",",
"json",
"=",
"False",
",",
"json_tree",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"from",
".",
".",
"core",
"import",
"do_graph",
"do_graph",
"(",
"bare",
"=",
"bare",
",",
"json",
"=",
"json",
",",
"json_tree",
"=",
"json_tree",
",",
"reverse",
"=",
"reverse",
")"
] | Displays currently-installed dependency graph information. | [
"Displays",
"currently",
"-",
"installed",
"dependency",
"graph",
"information",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L538-L542 |
25,124 | pypa/pipenv | pipenv/cli/command.py | run_open | def run_open(state, module, *args, **kwargs):
"""View a given module in your editor.
This uses the EDITOR environment variable. You can temporarily override it,
for example:
EDITOR=atom pipenv open requests
"""
from ..core import which, ensure_project, inline_activate_virtual_environment
# Ensure that virtualenv is available.
ensure_project(
three=state.three, python=state.python,
validate=False, pypi_mirror=state.pypi_mirror,
)
c = delegator.run(
'{0} -c "import {1}; print({1}.__file__);"'.format(which("python"), module)
)
try:
assert c.return_code == 0
except AssertionError:
echo(crayons.red("Module not found!"))
sys.exit(1)
if "__init__.py" in c.out:
p = os.path.dirname(c.out.strip().rstrip("cdo"))
else:
p = c.out.strip().rstrip("cdo")
echo(crayons.normal("Opening {0!r} in your EDITOR.".format(p), bold=True))
inline_activate_virtual_environment()
edit(filename=p)
return 0 | python | def run_open(state, module, *args, **kwargs):
"""View a given module in your editor.
This uses the EDITOR environment variable. You can temporarily override it,
for example:
EDITOR=atom pipenv open requests
"""
from ..core import which, ensure_project, inline_activate_virtual_environment
# Ensure that virtualenv is available.
ensure_project(
three=state.three, python=state.python,
validate=False, pypi_mirror=state.pypi_mirror,
)
c = delegator.run(
'{0} -c "import {1}; print({1}.__file__);"'.format(which("python"), module)
)
try:
assert c.return_code == 0
except AssertionError:
echo(crayons.red("Module not found!"))
sys.exit(1)
if "__init__.py" in c.out:
p = os.path.dirname(c.out.strip().rstrip("cdo"))
else:
p = c.out.strip().rstrip("cdo")
echo(crayons.normal("Opening {0!r} in your EDITOR.".format(p), bold=True))
inline_activate_virtual_environment()
edit(filename=p)
return 0 | [
"def",
"run_open",
"(",
"state",
",",
"module",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"which",
",",
"ensure_project",
",",
"inline_activate_virtual_environment",
"# Ensure that virtualenv is available.",
"ensure_project",
"(",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"validate",
"=",
"False",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")",
"c",
"=",
"delegator",
".",
"run",
"(",
"'{0} -c \"import {1}; print({1}.__file__);\"'",
".",
"format",
"(",
"which",
"(",
"\"python\"",
")",
",",
"module",
")",
")",
"try",
":",
"assert",
"c",
".",
"return_code",
"==",
"0",
"except",
"AssertionError",
":",
"echo",
"(",
"crayons",
".",
"red",
"(",
"\"Module not found!\"",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"\"__init__.py\"",
"in",
"c",
".",
"out",
":",
"p",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"c",
".",
"out",
".",
"strip",
"(",
")",
".",
"rstrip",
"(",
"\"cdo\"",
")",
")",
"else",
":",
"p",
"=",
"c",
".",
"out",
".",
"strip",
"(",
")",
".",
"rstrip",
"(",
"\"cdo\"",
")",
"echo",
"(",
"crayons",
".",
"normal",
"(",
"\"Opening {0!r} in your EDITOR.\"",
".",
"format",
"(",
"p",
")",
",",
"bold",
"=",
"True",
")",
")",
"inline_activate_virtual_environment",
"(",
")",
"edit",
"(",
"filename",
"=",
"p",
")",
"return",
"0"
] | View a given module in your editor.
This uses the EDITOR environment variable. You can temporarily override it,
for example:
EDITOR=atom pipenv open requests | [
"View",
"a",
"given",
"module",
"in",
"your",
"editor",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L552-L582 |
25,125 | pypa/pipenv | pipenv/cli/command.py | sync | def sync(
ctx,
state,
bare=False,
user=False,
unused=False,
**kwargs
):
"""Installs all packages specified in Pipfile.lock."""
from ..core import do_sync
retcode = do_sync(
ctx=ctx,
dev=state.installstate.dev,
three=state.three,
python=state.python,
bare=bare,
dont_upgrade=(not state.installstate.keep_outdated),
user=user,
clear=state.clear,
unused=unused,
sequential=state.installstate.sequential,
pypi_mirror=state.pypi_mirror,
)
if retcode:
ctx.abort() | python | def sync(
ctx,
state,
bare=False,
user=False,
unused=False,
**kwargs
):
"""Installs all packages specified in Pipfile.lock."""
from ..core import do_sync
retcode = do_sync(
ctx=ctx,
dev=state.installstate.dev,
three=state.three,
python=state.python,
bare=bare,
dont_upgrade=(not state.installstate.keep_outdated),
user=user,
clear=state.clear,
unused=unused,
sequential=state.installstate.sequential,
pypi_mirror=state.pypi_mirror,
)
if retcode:
ctx.abort() | [
"def",
"sync",
"(",
"ctx",
",",
"state",
",",
"bare",
"=",
"False",
",",
"user",
"=",
"False",
",",
"unused",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"do_sync",
"retcode",
"=",
"do_sync",
"(",
"ctx",
"=",
"ctx",
",",
"dev",
"=",
"state",
".",
"installstate",
".",
"dev",
",",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"bare",
"=",
"bare",
",",
"dont_upgrade",
"=",
"(",
"not",
"state",
".",
"installstate",
".",
"keep_outdated",
")",
",",
"user",
"=",
"user",
",",
"clear",
"=",
"state",
".",
"clear",
",",
"unused",
"=",
"unused",
",",
"sequential",
"=",
"state",
".",
"installstate",
".",
"sequential",
",",
"pypi_mirror",
"=",
"state",
".",
"pypi_mirror",
",",
")",
"if",
"retcode",
":",
"ctx",
".",
"abort",
"(",
")"
] | Installs all packages specified in Pipfile.lock. | [
"Installs",
"all",
"packages",
"specified",
"in",
"Pipfile",
".",
"lock",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L593-L618 |
25,126 | pypa/pipenv | pipenv/cli/command.py | clean | def clean(ctx, state, dry_run=False, bare=False, user=False):
"""Uninstalls all packages not specified in Pipfile.lock."""
from ..core import do_clean
do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run,
system=state.system) | python | def clean(ctx, state, dry_run=False, bare=False, user=False):
"""Uninstalls all packages not specified in Pipfile.lock."""
from ..core import do_clean
do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run,
system=state.system) | [
"def",
"clean",
"(",
"ctx",
",",
"state",
",",
"dry_run",
"=",
"False",
",",
"bare",
"=",
"False",
",",
"user",
"=",
"False",
")",
":",
"from",
".",
".",
"core",
"import",
"do_clean",
"do_clean",
"(",
"ctx",
"=",
"ctx",
",",
"three",
"=",
"state",
".",
"three",
",",
"python",
"=",
"state",
".",
"python",
",",
"dry_run",
"=",
"dry_run",
",",
"system",
"=",
"state",
".",
"system",
")"
] | Uninstalls all packages not specified in Pipfile.lock. | [
"Uninstalls",
"all",
"packages",
"not",
"specified",
"in",
"Pipfile",
".",
"lock",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L632-L636 |
25,127 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_tokenizer.py | HTMLTokenizer.emitCurrentToken | def emitCurrentToken(self):
"""This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted.
"""
token = self.currentToken
# Add token to the queue to be yielded
if (token["type"] in tagTokenTypes):
token["name"] = token["name"].translate(asciiUpper2Lower)
if token["type"] == tokenTypes["EndTag"]:
if token["data"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "attributes-in-end-tag"})
if token["selfClosing"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "self-closing-flag-on-end-tag"})
self.tokenQueue.append(token)
self.state = self.dataState | python | def emitCurrentToken(self):
"""This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted.
"""
token = self.currentToken
# Add token to the queue to be yielded
if (token["type"] in tagTokenTypes):
token["name"] = token["name"].translate(asciiUpper2Lower)
if token["type"] == tokenTypes["EndTag"]:
if token["data"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "attributes-in-end-tag"})
if token["selfClosing"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "self-closing-flag-on-end-tag"})
self.tokenQueue.append(token)
self.state = self.dataState | [
"def",
"emitCurrentToken",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"currentToken",
"# Add token to the queue to be yielded",
"if",
"(",
"token",
"[",
"\"type\"",
"]",
"in",
"tagTokenTypes",
")",
":",
"token",
"[",
"\"name\"",
"]",
"=",
"token",
"[",
"\"name\"",
"]",
".",
"translate",
"(",
"asciiUpper2Lower",
")",
"if",
"token",
"[",
"\"type\"",
"]",
"==",
"tokenTypes",
"[",
"\"EndTag\"",
"]",
":",
"if",
"token",
"[",
"\"data\"",
"]",
":",
"self",
".",
"tokenQueue",
".",
"append",
"(",
"{",
"\"type\"",
":",
"tokenTypes",
"[",
"\"ParseError\"",
"]",
",",
"\"data\"",
":",
"\"attributes-in-end-tag\"",
"}",
")",
"if",
"token",
"[",
"\"selfClosing\"",
"]",
":",
"self",
".",
"tokenQueue",
".",
"append",
"(",
"{",
"\"type\"",
":",
"tokenTypes",
"[",
"\"ParseError\"",
"]",
",",
"\"data\"",
":",
"\"self-closing-flag-on-end-tag\"",
"}",
")",
"self",
".",
"tokenQueue",
".",
"append",
"(",
"token",
")",
"self",
".",
"state",
"=",
"self",
".",
"dataState"
] | This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted. | [
"This",
"method",
"is",
"a",
"generic",
"handler",
"for",
"emitting",
"the",
"tags",
".",
"It",
"also",
"sets",
"the",
"state",
"to",
"data",
"because",
"that",
"s",
"what",
"s",
"needed",
"after",
"a",
"token",
"has",
"been",
"emitted",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_tokenizer.py#L222-L239 |
25,128 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/check.py | create_package_set_from_installed | def create_package_set_from_installed(**kwargs):
# type: (**Any) -> Tuple[PackageSet, bool]
"""Converts a list of distributions into a PackageSet.
"""
# Default to using all packages installed on the system
if kwargs == {}:
kwargs = {"local_only": False, "skip": ()}
package_set = {}
problems = False
for dist in get_installed_distributions(**kwargs):
name = canonicalize_name(dist.project_name)
try:
package_set[name] = PackageDetails(dist.version, dist.requires())
except RequirementParseError as e:
# Don't crash on broken metadata
logging.warning("Error parsing requirements for %s: %s", name, e)
problems = True
return package_set, problems | python | def create_package_set_from_installed(**kwargs):
# type: (**Any) -> Tuple[PackageSet, bool]
"""Converts a list of distributions into a PackageSet.
"""
# Default to using all packages installed on the system
if kwargs == {}:
kwargs = {"local_only": False, "skip": ()}
package_set = {}
problems = False
for dist in get_installed_distributions(**kwargs):
name = canonicalize_name(dist.project_name)
try:
package_set[name] = PackageDetails(dist.version, dist.requires())
except RequirementParseError as e:
# Don't crash on broken metadata
logging.warning("Error parsing requirements for %s: %s", name, e)
problems = True
return package_set, problems | [
"def",
"create_package_set_from_installed",
"(",
"*",
"*",
"kwargs",
")",
":",
"# type: (**Any) -> Tuple[PackageSet, bool]",
"# Default to using all packages installed on the system",
"if",
"kwargs",
"==",
"{",
"}",
":",
"kwargs",
"=",
"{",
"\"local_only\"",
":",
"False",
",",
"\"skip\"",
":",
"(",
")",
"}",
"package_set",
"=",
"{",
"}",
"problems",
"=",
"False",
"for",
"dist",
"in",
"get_installed_distributions",
"(",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"canonicalize_name",
"(",
"dist",
".",
"project_name",
")",
"try",
":",
"package_set",
"[",
"name",
"]",
"=",
"PackageDetails",
"(",
"dist",
".",
"version",
",",
"dist",
".",
"requires",
"(",
")",
")",
"except",
"RequirementParseError",
"as",
"e",
":",
"# Don't crash on broken metadata",
"logging",
".",
"warning",
"(",
"\"Error parsing requirements for %s: %s\"",
",",
"name",
",",
"e",
")",
"problems",
"=",
"True",
"return",
"package_set",
",",
"problems"
] | Converts a list of distributions into a PackageSet. | [
"Converts",
"a",
"list",
"of",
"distributions",
"into",
"a",
"PackageSet",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/check.py#L34-L52 |
25,129 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/check.py | check_package_set | def check_package_set(package_set, should_ignore=None):
# type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
"""Check if a package set is consistent
If should_ignore is passed, it should be a callable that takes a
package name and returns a boolean.
"""
if should_ignore is None:
def should_ignore(name):
return False
missing = dict()
conflicting = dict()
for package_name in package_set:
# Info about dependencies of package_name
missing_deps = set() # type: Set[Missing]
conflicting_deps = set() # type: Set[Conflicting]
if should_ignore(package_name):
continue
for req in package_set[package_name].requires:
name = canonicalize_name(req.project_name) # type: str
# Check if it's missing
if name not in package_set:
missed = True
if req.marker is not None:
missed = req.marker.evaluate()
if missed:
missing_deps.add((name, req))
continue
# Check if there's a conflict
version = package_set[name].version # type: str
if not req.specifier.contains(version, prereleases=True):
conflicting_deps.add((name, version, req))
if missing_deps:
missing[package_name] = sorted(missing_deps, key=str)
if conflicting_deps:
conflicting[package_name] = sorted(conflicting_deps, key=str)
return missing, conflicting | python | def check_package_set(package_set, should_ignore=None):
# type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
"""Check if a package set is consistent
If should_ignore is passed, it should be a callable that takes a
package name and returns a boolean.
"""
if should_ignore is None:
def should_ignore(name):
return False
missing = dict()
conflicting = dict()
for package_name in package_set:
# Info about dependencies of package_name
missing_deps = set() # type: Set[Missing]
conflicting_deps = set() # type: Set[Conflicting]
if should_ignore(package_name):
continue
for req in package_set[package_name].requires:
name = canonicalize_name(req.project_name) # type: str
# Check if it's missing
if name not in package_set:
missed = True
if req.marker is not None:
missed = req.marker.evaluate()
if missed:
missing_deps.add((name, req))
continue
# Check if there's a conflict
version = package_set[name].version # type: str
if not req.specifier.contains(version, prereleases=True):
conflicting_deps.add((name, version, req))
if missing_deps:
missing[package_name] = sorted(missing_deps, key=str)
if conflicting_deps:
conflicting[package_name] = sorted(conflicting_deps, key=str)
return missing, conflicting | [
"def",
"check_package_set",
"(",
"package_set",
",",
"should_ignore",
"=",
"None",
")",
":",
"# type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult",
"if",
"should_ignore",
"is",
"None",
":",
"def",
"should_ignore",
"(",
"name",
")",
":",
"return",
"False",
"missing",
"=",
"dict",
"(",
")",
"conflicting",
"=",
"dict",
"(",
")",
"for",
"package_name",
"in",
"package_set",
":",
"# Info about dependencies of package_name",
"missing_deps",
"=",
"set",
"(",
")",
"# type: Set[Missing]",
"conflicting_deps",
"=",
"set",
"(",
")",
"# type: Set[Conflicting]",
"if",
"should_ignore",
"(",
"package_name",
")",
":",
"continue",
"for",
"req",
"in",
"package_set",
"[",
"package_name",
"]",
".",
"requires",
":",
"name",
"=",
"canonicalize_name",
"(",
"req",
".",
"project_name",
")",
"# type: str",
"# Check if it's missing",
"if",
"name",
"not",
"in",
"package_set",
":",
"missed",
"=",
"True",
"if",
"req",
".",
"marker",
"is",
"not",
"None",
":",
"missed",
"=",
"req",
".",
"marker",
".",
"evaluate",
"(",
")",
"if",
"missed",
":",
"missing_deps",
".",
"add",
"(",
"(",
"name",
",",
"req",
")",
")",
"continue",
"# Check if there's a conflict",
"version",
"=",
"package_set",
"[",
"name",
"]",
".",
"version",
"# type: str",
"if",
"not",
"req",
".",
"specifier",
".",
"contains",
"(",
"version",
",",
"prereleases",
"=",
"True",
")",
":",
"conflicting_deps",
".",
"add",
"(",
"(",
"name",
",",
"version",
",",
"req",
")",
")",
"if",
"missing_deps",
":",
"missing",
"[",
"package_name",
"]",
"=",
"sorted",
"(",
"missing_deps",
",",
"key",
"=",
"str",
")",
"if",
"conflicting_deps",
":",
"conflicting",
"[",
"package_name",
"]",
"=",
"sorted",
"(",
"conflicting_deps",
",",
"key",
"=",
"str",
")",
"return",
"missing",
",",
"conflicting"
] | Check if a package set is consistent
If should_ignore is passed, it should be a callable that takes a
package name and returns a boolean. | [
"Check",
"if",
"a",
"package",
"set",
"is",
"consistent"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/check.py#L55-L99 |
25,130 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/check.py | check_install_conflicts | def check_install_conflicts(to_install):
# type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult]
"""For checking if the dependency graph would be consistent after \
installing given requirements
"""
# Start from the current state
package_set, _ = create_package_set_from_installed()
# Install packages
would_be_installed = _simulate_installation_of(to_install, package_set)
# Only warn about directly-dependent packages; create a whitelist of them
whitelist = _create_whitelist(would_be_installed, package_set)
return (
package_set,
check_package_set(
package_set, should_ignore=lambda name: name not in whitelist
)
) | python | def check_install_conflicts(to_install):
# type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult]
"""For checking if the dependency graph would be consistent after \
installing given requirements
"""
# Start from the current state
package_set, _ = create_package_set_from_installed()
# Install packages
would_be_installed = _simulate_installation_of(to_install, package_set)
# Only warn about directly-dependent packages; create a whitelist of them
whitelist = _create_whitelist(would_be_installed, package_set)
return (
package_set,
check_package_set(
package_set, should_ignore=lambda name: name not in whitelist
)
) | [
"def",
"check_install_conflicts",
"(",
"to_install",
")",
":",
"# type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult]",
"# Start from the current state",
"package_set",
",",
"_",
"=",
"create_package_set_from_installed",
"(",
")",
"# Install packages",
"would_be_installed",
"=",
"_simulate_installation_of",
"(",
"to_install",
",",
"package_set",
")",
"# Only warn about directly-dependent packages; create a whitelist of them",
"whitelist",
"=",
"_create_whitelist",
"(",
"would_be_installed",
",",
"package_set",
")",
"return",
"(",
"package_set",
",",
"check_package_set",
"(",
"package_set",
",",
"should_ignore",
"=",
"lambda",
"name",
":",
"name",
"not",
"in",
"whitelist",
")",
")"
] | For checking if the dependency graph would be consistent after \
installing given requirements | [
"For",
"checking",
"if",
"the",
"dependency",
"graph",
"would",
"be",
"consistent",
"after",
"\\",
"installing",
"given",
"requirements"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/check.py#L102-L120 |
25,131 | pypa/pipenv | pipenv/patched/notpip/_internal/operations/check.py | _simulate_installation_of | def _simulate_installation_of(to_install, package_set):
# type: (List[InstallRequirement], PackageSet) -> Set[str]
"""Computes the version of packages after installing to_install.
"""
# Keep track of packages that were installed
installed = set()
# Modify it as installing requirement_set would (assuming no errors)
for inst_req in to_install:
dist = make_abstract_dist(inst_req).dist()
name = canonicalize_name(dist.key)
package_set[name] = PackageDetails(dist.version, dist.requires())
installed.add(name)
return installed | python | def _simulate_installation_of(to_install, package_set):
# type: (List[InstallRequirement], PackageSet) -> Set[str]
"""Computes the version of packages after installing to_install.
"""
# Keep track of packages that were installed
installed = set()
# Modify it as installing requirement_set would (assuming no errors)
for inst_req in to_install:
dist = make_abstract_dist(inst_req).dist()
name = canonicalize_name(dist.key)
package_set[name] = PackageDetails(dist.version, dist.requires())
installed.add(name)
return installed | [
"def",
"_simulate_installation_of",
"(",
"to_install",
",",
"package_set",
")",
":",
"# type: (List[InstallRequirement], PackageSet) -> Set[str]",
"# Keep track of packages that were installed",
"installed",
"=",
"set",
"(",
")",
"# Modify it as installing requirement_set would (assuming no errors)",
"for",
"inst_req",
"in",
"to_install",
":",
"dist",
"=",
"make_abstract_dist",
"(",
"inst_req",
")",
".",
"dist",
"(",
")",
"name",
"=",
"canonicalize_name",
"(",
"dist",
".",
"key",
")",
"package_set",
"[",
"name",
"]",
"=",
"PackageDetails",
"(",
"dist",
".",
"version",
",",
"dist",
".",
"requires",
"(",
")",
")",
"installed",
".",
"add",
"(",
"name",
")",
"return",
"installed"
] | Computes the version of packages after installing to_install. | [
"Computes",
"the",
"version",
"of",
"packages",
"after",
"installing",
"to_install",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/operations/check.py#L123-L139 |
25,132 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.name | def name(self):
"""The final path component, if any."""
parts = self._parts
if len(parts) == (1 if (self._drv or self._root) else 0):
return ''
return parts[-1] | python | def name(self):
"""The final path component, if any."""
parts = self._parts
if len(parts) == (1 if (self._drv or self._root) else 0):
return ''
return parts[-1] | [
"def",
"name",
"(",
"self",
")",
":",
"parts",
"=",
"self",
".",
"_parts",
"if",
"len",
"(",
"parts",
")",
"==",
"(",
"1",
"if",
"(",
"self",
".",
"_drv",
"or",
"self",
".",
"_root",
")",
"else",
"0",
")",
":",
"return",
"''",
"return",
"parts",
"[",
"-",
"1",
"]"
] | The final path component, if any. | [
"The",
"final",
"path",
"component",
"if",
"any",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L981-L986 |
25,133 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.suffix | def suffix(self):
"""The final component's last suffix, if any."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[i:]
else:
return '' | python | def suffix(self):
"""The final component's last suffix, if any."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[i:]
else:
return '' | [
"def",
"suffix",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"i",
"=",
"name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"0",
"<",
"i",
"<",
"len",
"(",
"name",
")",
"-",
"1",
":",
"return",
"name",
"[",
"i",
":",
"]",
"else",
":",
"return",
"''"
] | The final component's last suffix, if any. | [
"The",
"final",
"component",
"s",
"last",
"suffix",
"if",
"any",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L989-L996 |
25,134 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.suffixes | def suffixes(self):
"""A list of the final component's suffixes, if any."""
name = self.name
if name.endswith('.'):
return []
name = name.lstrip('.')
return ['.' + suffix for suffix in name.split('.')[1:]] | python | def suffixes(self):
"""A list of the final component's suffixes, if any."""
name = self.name
if name.endswith('.'):
return []
name = name.lstrip('.')
return ['.' + suffix for suffix in name.split('.')[1:]] | [
"def",
"suffixes",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"if",
"name",
".",
"endswith",
"(",
"'.'",
")",
":",
"return",
"[",
"]",
"name",
"=",
"name",
".",
"lstrip",
"(",
"'.'",
")",
"return",
"[",
"'.'",
"+",
"suffix",
"for",
"suffix",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
"]"
] | A list of the final component's suffixes, if any. | [
"A",
"list",
"of",
"the",
"final",
"component",
"s",
"suffixes",
"if",
"any",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L999-L1005 |
25,135 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.stem | def stem(self):
"""The final path component, minus its last suffix."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[:i]
else:
return name | python | def stem(self):
"""The final path component, minus its last suffix."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[:i]
else:
return name | [
"def",
"stem",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"i",
"=",
"name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"0",
"<",
"i",
"<",
"len",
"(",
"name",
")",
"-",
"1",
":",
"return",
"name",
"[",
":",
"i",
"]",
"else",
":",
"return",
"name"
] | The final path component, minus its last suffix. | [
"The",
"final",
"path",
"component",
"minus",
"its",
"last",
"suffix",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1008-L1015 |
25,136 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.parts | def parts(self):
"""An object providing sequence-like access to the
components in the filesystem path."""
# We cache the tuple to avoid building a new one each time .parts
# is accessed. XXX is this necessary?
try:
return self._pparts
except AttributeError:
self._pparts = tuple(self._parts)
return self._pparts | python | def parts(self):
"""An object providing sequence-like access to the
components in the filesystem path."""
# We cache the tuple to avoid building a new one each time .parts
# is accessed. XXX is this necessary?
try:
return self._pparts
except AttributeError:
self._pparts = tuple(self._parts)
return self._pparts | [
"def",
"parts",
"(",
"self",
")",
":",
"# We cache the tuple to avoid building a new one each time .parts",
"# is accessed. XXX is this necessary?",
"try",
":",
"return",
"self",
".",
"_pparts",
"except",
"AttributeError",
":",
"self",
".",
"_pparts",
"=",
"tuple",
"(",
"self",
".",
"_parts",
")",
"return",
"self",
".",
"_pparts"
] | An object providing sequence-like access to the
components in the filesystem path. | [
"An",
"object",
"providing",
"sequence",
"-",
"like",
"access",
"to",
"the",
"components",
"in",
"the",
"filesystem",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1082-L1091 |
25,137 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | PurePath.match | def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True | python | def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True | [
"def",
"match",
"(",
"self",
",",
"path_pattern",
")",
":",
"cf",
"=",
"self",
".",
"_flavour",
".",
"casefold",
"path_pattern",
"=",
"cf",
"(",
"path_pattern",
")",
"drv",
",",
"root",
",",
"pat_parts",
"=",
"self",
".",
"_flavour",
".",
"parse_parts",
"(",
"(",
"path_pattern",
",",
")",
")",
"if",
"not",
"pat_parts",
":",
"raise",
"ValueError",
"(",
"\"empty pattern\"",
")",
"if",
"drv",
"and",
"drv",
"!=",
"cf",
"(",
"self",
".",
"_drv",
")",
":",
"return",
"False",
"if",
"root",
"and",
"root",
"!=",
"cf",
"(",
"self",
".",
"_root",
")",
":",
"return",
"False",
"parts",
"=",
"self",
".",
"_cparts",
"if",
"drv",
"or",
"root",
":",
"if",
"len",
"(",
"pat_parts",
")",
"!=",
"len",
"(",
"parts",
")",
":",
"return",
"False",
"pat_parts",
"=",
"pat_parts",
"[",
"1",
":",
"]",
"elif",
"len",
"(",
"pat_parts",
")",
">",
"len",
"(",
"parts",
")",
":",
"return",
"False",
"for",
"part",
",",
"pat",
"in",
"zip",
"(",
"reversed",
"(",
"parts",
")",
",",
"reversed",
"(",
"pat_parts",
")",
")",
":",
"if",
"not",
"fnmatch",
".",
"fnmatchcase",
"(",
"part",
",",
"pat",
")",
":",
"return",
"False",
"return",
"True"
] | Return True if this path matches the given pattern. | [
"Return",
"True",
"if",
"this",
"path",
"matches",
"the",
"given",
"pattern",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1138-L1161 |
25,138 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.touch | def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.
"""
if self._closed:
self._raise_closed()
if exist_ok:
# First try to bump modification time
# Implementation note: GNU touch uses the UTIME_NOW option of
# the utimensat() / futimens() functions.
try:
self._accessor.utime(self, None)
except OSError:
# Avoid exception chaining
pass
else:
return
flags = os.O_CREAT | os.O_WRONLY
if not exist_ok:
flags |= os.O_EXCL
fd = self._raw_open(flags, mode)
os.close(fd) | python | def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.
"""
if self._closed:
self._raise_closed()
if exist_ok:
# First try to bump modification time
# Implementation note: GNU touch uses the UTIME_NOW option of
# the utimensat() / futimens() functions.
try:
self._accessor.utime(self, None)
except OSError:
# Avoid exception chaining
pass
else:
return
flags = os.O_CREAT | os.O_WRONLY
if not exist_ok:
flags |= os.O_EXCL
fd = self._raw_open(flags, mode)
os.close(fd) | [
"def",
"touch",
"(",
"self",
",",
"mode",
"=",
"0o666",
",",
"exist_ok",
"=",
"True",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"if",
"exist_ok",
":",
"# First try to bump modification time",
"# Implementation note: GNU touch uses the UTIME_NOW option of",
"# the utimensat() / futimens() functions.",
"try",
":",
"self",
".",
"_accessor",
".",
"utime",
"(",
"self",
",",
"None",
")",
"except",
"OSError",
":",
"# Avoid exception chaining",
"pass",
"else",
":",
"return",
"flags",
"=",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_WRONLY",
"if",
"not",
"exist_ok",
":",
"flags",
"|=",
"os",
".",
"O_EXCL",
"fd",
"=",
"self",
".",
"_raw_open",
"(",
"flags",
",",
"mode",
")",
"os",
".",
"close",
"(",
"fd",
")"
] | Create this file with the given access mode, if it doesn't exist. | [
"Create",
"this",
"file",
"with",
"the",
"given",
"access",
"mode",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1424-L1445 |
25,139 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.mkdir | def mkdir(self, mode=0o777, parents=False, exist_ok=False):
"""
Create a new directory at this given path.
"""
if self._closed:
self._raise_closed()
def _try_func():
self._accessor.mkdir(self, mode)
def _exc_func(exc):
if not parents or self.parent == self:
raise exc
self.parent.mkdir(parents=True, exist_ok=True)
self.mkdir(mode, parents=False, exist_ok=exist_ok)
try:
_try_except_filenotfounderror(_try_func, _exc_func)
except OSError:
if not exist_ok or not self.is_dir():
raise | python | def mkdir(self, mode=0o777, parents=False, exist_ok=False):
"""
Create a new directory at this given path.
"""
if self._closed:
self._raise_closed()
def _try_func():
self._accessor.mkdir(self, mode)
def _exc_func(exc):
if not parents or self.parent == self:
raise exc
self.parent.mkdir(parents=True, exist_ok=True)
self.mkdir(mode, parents=False, exist_ok=exist_ok)
try:
_try_except_filenotfounderror(_try_func, _exc_func)
except OSError:
if not exist_ok or not self.is_dir():
raise | [
"def",
"mkdir",
"(",
"self",
",",
"mode",
"=",
"0o777",
",",
"parents",
"=",
"False",
",",
"exist_ok",
"=",
"False",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"def",
"_try_func",
"(",
")",
":",
"self",
".",
"_accessor",
".",
"mkdir",
"(",
"self",
",",
"mode",
")",
"def",
"_exc_func",
"(",
"exc",
")",
":",
"if",
"not",
"parents",
"or",
"self",
".",
"parent",
"==",
"self",
":",
"raise",
"exc",
"self",
".",
"parent",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"self",
".",
"mkdir",
"(",
"mode",
",",
"parents",
"=",
"False",
",",
"exist_ok",
"=",
"exist_ok",
")",
"try",
":",
"_try_except_filenotfounderror",
"(",
"_try_func",
",",
"_exc_func",
")",
"except",
"OSError",
":",
"if",
"not",
"exist_ok",
"or",
"not",
"self",
".",
"is_dir",
"(",
")",
":",
"raise"
] | Create a new directory at this given path. | [
"Create",
"a",
"new",
"directory",
"at",
"this",
"given",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1447-L1467 |
25,140 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.rmdir | def rmdir(self):
"""
Remove this directory. The directory must be empty.
"""
if self._closed:
self._raise_closed()
self._accessor.rmdir(self) | python | def rmdir(self):
"""
Remove this directory. The directory must be empty.
"""
if self._closed:
self._raise_closed()
self._accessor.rmdir(self) | [
"def",
"rmdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"rmdir",
"(",
"self",
")"
] | Remove this directory. The directory must be empty. | [
"Remove",
"this",
"directory",
".",
"The",
"directory",
"must",
"be",
"empty",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1495-L1501 |
25,141 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.rename | def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target) | python | def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target) | [
"def",
"rename",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"rename",
"(",
"self",
",",
"target",
")"
] | Rename this path to the given path. | [
"Rename",
"this",
"path",
"to",
"the",
"given",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1512-L1518 |
25,142 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.exists | def exists(self):
"""
Whether this path exists.
"""
try:
self.stat()
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
return False
return True | python | def exists(self):
"""
Whether this path exists.
"""
try:
self.stat()
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
return False
return True | [
"def",
"exists",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"stat",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"return",
"False",
"return",
"True"
] | Whether this path exists. | [
"Whether",
"this",
"path",
"exists",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1544-L1554 |
25,143 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.is_dir | def is_dir(self):
"""
Whether this path is a directory.
"""
try:
return S_ISDIR(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | python | def is_dir(self):
"""
Whether this path is a directory.
"""
try:
return S_ISDIR(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | [
"def",
"is_dir",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISDIR",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] | Whether this path is a directory. | [
"Whether",
"this",
"path",
"is",
"a",
"directory",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1556-L1567 |
25,144 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.is_fifo | def is_fifo(self):
"""
Whether this path is a FIFO.
"""
try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | python | def is_fifo(self):
"""
Whether this path is a FIFO.
"""
try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | [
"def",
"is_fifo",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISFIFO",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] | Whether this path is a FIFO. | [
"Whether",
"this",
"path",
"is",
"a",
"FIFO",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1621-L1632 |
25,145 | pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | Path.is_socket | def is_socket(self):
"""
Whether this path is a socket.
"""
try:
return S_ISSOCK(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | python | def is_socket(self):
"""
Whether this path is a socket.
"""
try:
return S_ISSOCK(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False | [
"def",
"is_socket",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISSOCK",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False"
] | Whether this path is a socket. | [
"Whether",
"this",
"path",
"is",
"a",
"socket",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1634-L1645 |
25,146 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | lookupEncoding | def lookupEncoding(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, binary_type):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding is not None:
try:
return webencodings.lookup(encoding)
except AttributeError:
return None
else:
return None | python | def lookupEncoding(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, binary_type):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding is not None:
try:
return webencodings.lookup(encoding)
except AttributeError:
return None
else:
return None | [
"def",
"lookupEncoding",
"(",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"encoding",
",",
"binary_type",
")",
":",
"try",
":",
"encoding",
"=",
"encoding",
".",
"decode",
"(",
"\"ascii\"",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"None",
"if",
"encoding",
"is",
"not",
"None",
":",
"try",
":",
"return",
"webencodings",
".",
"lookup",
"(",
"encoding",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"return",
"None"
] | Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding. | [
"Return",
"the",
"python",
"codec",
"name",
"corresponding",
"to",
"an",
"encoding",
"or",
"None",
"if",
"the",
"string",
"doesn",
"t",
"correspond",
"to",
"a",
"valid",
"encoding",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L908-L923 |
25,147 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | HTMLUnicodeInputStream.char | def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char | python | def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char | [
"def",
"char",
"(",
"self",
")",
":",
"# Read a new chunk from the input stream if necessary",
"if",
"self",
".",
"chunkOffset",
">=",
"self",
".",
"chunkSize",
":",
"if",
"not",
"self",
".",
"readChunk",
"(",
")",
":",
"return",
"EOF",
"chunkOffset",
"=",
"self",
".",
"chunkOffset",
"char",
"=",
"self",
".",
"chunk",
"[",
"chunkOffset",
"]",
"self",
".",
"chunkOffset",
"=",
"chunkOffset",
"+",
"1",
"return",
"char"
] | Read one character from the stream or queue if available. Return
EOF when EOF is reached. | [
"Read",
"one",
"character",
"from",
"the",
"stream",
"or",
"queue",
"if",
"available",
".",
"Return",
"EOF",
"when",
"EOF",
"is",
"reached",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L240-L253 |
25,148 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | HTMLUnicodeInputStream.charsUntil | def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r | python | def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r | [
"def",
"charsUntil",
"(",
"self",
",",
"characters",
",",
"opposite",
"=",
"False",
")",
":",
"# Use a cache of regexps to find the required characters",
"try",
":",
"chars",
"=",
"charsUntilRegEx",
"[",
"(",
"characters",
",",
"opposite",
")",
"]",
"except",
"KeyError",
":",
"if",
"__debug__",
":",
"for",
"c",
"in",
"characters",
":",
"assert",
"(",
"ord",
"(",
"c",
")",
"<",
"128",
")",
"regex",
"=",
"\"\"",
".",
"join",
"(",
"[",
"\"\\\\x%02x\"",
"%",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"characters",
"]",
")",
"if",
"not",
"opposite",
":",
"regex",
"=",
"\"^%s\"",
"%",
"regex",
"chars",
"=",
"charsUntilRegEx",
"[",
"(",
"characters",
",",
"opposite",
")",
"]",
"=",
"re",
".",
"compile",
"(",
"\"[%s]+\"",
"%",
"regex",
")",
"rv",
"=",
"[",
"]",
"while",
"True",
":",
"# Find the longest matching prefix",
"m",
"=",
"chars",
".",
"match",
"(",
"self",
".",
"chunk",
",",
"self",
".",
"chunkOffset",
")",
"if",
"m",
"is",
"None",
":",
"# If nothing matched, and it wasn't because we ran out of chunk,",
"# then stop",
"if",
"self",
".",
"chunkOffset",
"!=",
"self",
".",
"chunkSize",
":",
"break",
"else",
":",
"end",
"=",
"m",
".",
"end",
"(",
")",
"# If not the whole chunk matched, return everything",
"# up to the part that didn't match",
"if",
"end",
"!=",
"self",
".",
"chunkSize",
":",
"rv",
".",
"append",
"(",
"self",
".",
"chunk",
"[",
"self",
".",
"chunkOffset",
":",
"end",
"]",
")",
"self",
".",
"chunkOffset",
"=",
"end",
"break",
"# If the whole remainder of the chunk matched,",
"# use it all and read the next chunk",
"rv",
".",
"append",
"(",
"self",
".",
"chunk",
"[",
"self",
".",
"chunkOffset",
":",
"]",
")",
"if",
"not",
"self",
".",
"readChunk",
"(",
")",
":",
"# Reached EOF",
"break",
"r",
"=",
"\"\"",
".",
"join",
"(",
"rv",
")",
"return",
"r"
] | Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters. | [
"Returns",
"a",
"string",
"of",
"characters",
"from",
"the",
"stream",
"up",
"to",
"but",
"not",
"including",
"any",
"character",
"in",
"characters",
"or",
"EOF",
".",
"characters",
"must",
"be",
"a",
"container",
"that",
"supports",
"the",
"in",
"method",
"and",
"iteration",
"over",
"its",
"characters",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L320-L365 |
25,149 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | HTMLBinaryInputStream.detectEncodingMeta | def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding is not None and encoding.name in ("utf-16be", "utf-16le"):
encoding = lookupEncoding("utf-8")
return encoding | python | def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding is not None and encoding.name in ("utf-16be", "utf-16le"):
encoding = lookupEncoding("utf-8")
return encoding | [
"def",
"detectEncodingMeta",
"(",
"self",
")",
":",
"buffer",
"=",
"self",
".",
"rawStream",
".",
"read",
"(",
"self",
".",
"numBytesMeta",
")",
"assert",
"isinstance",
"(",
"buffer",
",",
"bytes",
")",
"parser",
"=",
"EncodingParser",
"(",
"buffer",
")",
"self",
".",
"rawStream",
".",
"seek",
"(",
"0",
")",
"encoding",
"=",
"parser",
".",
"getEncoding",
"(",
")",
"if",
"encoding",
"is",
"not",
"None",
"and",
"encoding",
".",
"name",
"in",
"(",
"\"utf-16be\"",
",",
"\"utf-16le\"",
")",
":",
"encoding",
"=",
"lookupEncoding",
"(",
"\"utf-8\"",
")",
"return",
"encoding"
] | Report the encoding declared by the meta element | [
"Report",
"the",
"encoding",
"declared",
"by",
"the",
"meta",
"element"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L569-L581 |
25,150 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | EncodingBytes.skip | def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None | python | def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None | [
"def",
"skip",
"(",
"self",
",",
"chars",
"=",
"spaceCharactersBytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"# use property for the error-checking",
"while",
"p",
"<",
"len",
"(",
"self",
")",
":",
"c",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"1",
"]",
"if",
"c",
"not",
"in",
"chars",
":",
"self",
".",
"_position",
"=",
"p",
"return",
"c",
"p",
"+=",
"1",
"self",
".",
"_position",
"=",
"p",
"return",
"None"
] | Skip past a list of characters | [
"Skip",
"past",
"a",
"list",
"of",
"characters"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L640-L650 |
25,151 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | EncodingBytes.matchBytes | def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv | python | def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv | [
"def",
"matchBytes",
"(",
"self",
",",
"bytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"data",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"len",
"(",
"bytes",
")",
"]",
"rv",
"=",
"data",
".",
"startswith",
"(",
"bytes",
")",
"if",
"rv",
":",
"self",
".",
"position",
"+=",
"len",
"(",
"bytes",
")",
"return",
"rv"
] | Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone | [
"Look",
"for",
"a",
"sequence",
"of",
"bytes",
"at",
"the",
"start",
"of",
"a",
"string",
".",
"If",
"the",
"bytes",
"are",
"found",
"return",
"True",
"and",
"advance",
"the",
"position",
"to",
"the",
"byte",
"after",
"the",
"match",
".",
"Otherwise",
"return",
"False",
"and",
"leave",
"the",
"position",
"alone"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L663-L672 |
25,152 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | EncodingBytes.jumpTo | def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration | python | def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration | [
"def",
"jumpTo",
"(",
"self",
",",
"bytes",
")",
":",
"newPosition",
"=",
"self",
"[",
"self",
".",
"position",
":",
"]",
".",
"find",
"(",
"bytes",
")",
"if",
"newPosition",
">",
"-",
"1",
":",
"# XXX: This is ugly, but I can't see a nicer way to fix this.",
"if",
"self",
".",
"_position",
"==",
"-",
"1",
":",
"self",
".",
"_position",
"=",
"0",
"self",
".",
"_position",
"+=",
"(",
"newPosition",
"+",
"len",
"(",
"bytes",
")",
"-",
"1",
")",
"return",
"True",
"else",
":",
"raise",
"StopIteration"
] | Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match | [
"Look",
"for",
"the",
"next",
"sequence",
"of",
"bytes",
"matching",
"a",
"given",
"sequence",
".",
"If",
"a",
"match",
"is",
"found",
"advance",
"the",
"position",
"to",
"the",
"last",
"byte",
"of",
"the",
"match"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L674-L685 |
25,153 | pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | EncodingParser.getAttribute | def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c) | python | def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c) | [
"def",
"getAttribute",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"# Step 1 (skip chars)",
"c",
"=",
"data",
".",
"skip",
"(",
"spaceCharactersBytes",
"|",
"frozenset",
"(",
"[",
"b\"/\"",
"]",
")",
")",
"assert",
"c",
"is",
"None",
"or",
"len",
"(",
"c",
")",
"==",
"1",
"# Step 2",
"if",
"c",
"in",
"(",
"b\">\"",
",",
"None",
")",
":",
"return",
"None",
"# Step 3",
"attrName",
"=",
"[",
"]",
"attrValue",
"=",
"[",
"]",
"# Step 4 attribute name",
"while",
"True",
":",
"if",
"c",
"==",
"b\"=\"",
"and",
"attrName",
":",
"break",
"elif",
"c",
"in",
"spaceCharactersBytes",
":",
"# Step 6!",
"c",
"=",
"data",
".",
"skip",
"(",
")",
"break",
"elif",
"c",
"in",
"(",
"b\"/\"",
",",
"b\">\"",
")",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrName",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrName",
".",
"append",
"(",
"c",
")",
"# Step 5",
"c",
"=",
"next",
"(",
"data",
")",
"# Step 7",
"if",
"c",
"!=",
"b\"=\"",
":",
"data",
".",
"previous",
"(",
")",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"# Step 8",
"next",
"(",
"data",
")",
"# Step 9",
"c",
"=",
"data",
".",
"skip",
"(",
")",
"# Step 10",
"if",
"c",
"in",
"(",
"b\"'\"",
",",
"b'\"'",
")",
":",
"# 10.1",
"quoteChar",
"=",
"c",
"while",
"True",
":",
"# 10.2",
"c",
"=",
"next",
"(",
"data",
")",
"# 10.3",
"if",
"c",
"==",
"quoteChar",
":",
"next",
"(",
"data",
")",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
".",
"join",
"(",
"attrValue",
")",
"# 10.4",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"# 10.5",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")",
"elif",
"c",
"==",
"b\">\"",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")",
"# Step 11",
"while",
"True",
":",
"c",
"=",
"next",
"(",
"data",
")",
"if",
"c",
"in",
"spacesAngleBrackets",
":",
"return",
"b\"\"",
".",
"join",
"(",
"attrName",
")",
",",
"b\"\"",
".",
"join",
"(",
"attrValue",
")",
"elif",
"c",
"in",
"asciiUppercaseBytes",
":",
"attrValue",
".",
"append",
"(",
"c",
".",
"lower",
"(",
")",
")",
"elif",
"c",
"is",
"None",
":",
"return",
"None",
"else",
":",
"attrValue",
".",
"append",
"(",
"c",
")"
] | Return a name,value pair for the next attribute in the stream,
if one is found, or None | [
"Return",
"a",
"name",
"value",
"pair",
"for",
"the",
"next",
"attribute",
"in",
"the",
"stream",
"if",
"one",
"is",
"found",
"or",
"None"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L792-L866 |
25,154 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | _build_backend | def _build_backend():
"""Find and load the build backend"""
ep = os.environ['PEP517_BUILD_BACKEND']
mod_path, _, obj_path = ep.partition(':')
try:
obj = import_module(mod_path)
except ImportError:
raise BackendUnavailable
if obj_path:
for path_part in obj_path.split('.'):
obj = getattr(obj, path_part)
return obj | python | def _build_backend():
"""Find and load the build backend"""
ep = os.environ['PEP517_BUILD_BACKEND']
mod_path, _, obj_path = ep.partition(':')
try:
obj = import_module(mod_path)
except ImportError:
raise BackendUnavailable
if obj_path:
for path_part in obj_path.split('.'):
obj = getattr(obj, path_part)
return obj | [
"def",
"_build_backend",
"(",
")",
":",
"ep",
"=",
"os",
".",
"environ",
"[",
"'PEP517_BUILD_BACKEND'",
"]",
"mod_path",
",",
"_",
",",
"obj_path",
"=",
"ep",
".",
"partition",
"(",
"':'",
")",
"try",
":",
"obj",
"=",
"import_module",
"(",
"mod_path",
")",
"except",
"ImportError",
":",
"raise",
"BackendUnavailable",
"if",
"obj_path",
":",
"for",
"path_part",
"in",
"obj_path",
".",
"split",
"(",
"'.'",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"path_part",
")",
"return",
"obj"
] | Find and load the build backend | [
"Find",
"and",
"load",
"the",
"build",
"backend"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L29-L40 |
25,155 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | prepare_metadata_for_build_wheel | def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined.
"""
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory,
config_settings)
else:
return hook(metadata_directory, config_settings) | python | def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined.
"""
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory,
config_settings)
else:
return hook(metadata_directory, config_settings) | [
"def",
"prepare_metadata_for_build_wheel",
"(",
"metadata_directory",
",",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"hook",
"=",
"backend",
".",
"prepare_metadata_for_build_wheel",
"except",
"AttributeError",
":",
"return",
"_get_wheel_metadata_from_wheel",
"(",
"backend",
",",
"metadata_directory",
",",
"config_settings",
")",
"else",
":",
"return",
"hook",
"(",
"metadata_directory",
",",
"config_settings",
")"
] | Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined. | [
"Invoke",
"optional",
"prepare_metadata_for_build_wheel"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L57-L69 |
25,156 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | _dist_info_files | def _dist_info_files(whl_zip):
"""Identify the .dist-info folder inside a wheel ZipFile."""
res = []
for path in whl_zip.namelist():
m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)
if m:
res.append(path)
if res:
return res
raise Exception("No .dist-info folder found in wheel") | python | def _dist_info_files(whl_zip):
"""Identify the .dist-info folder inside a wheel ZipFile."""
res = []
for path in whl_zip.namelist():
m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)
if m:
res.append(path)
if res:
return res
raise Exception("No .dist-info folder found in wheel") | [
"def",
"_dist_info_files",
"(",
"whl_zip",
")",
":",
"res",
"=",
"[",
"]",
"for",
"path",
"in",
"whl_zip",
".",
"namelist",
"(",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'[^/\\\\]+-[^/\\\\]+\\.dist-info/'",
",",
"path",
")",
"if",
"m",
":",
"res",
".",
"append",
"(",
"path",
")",
"if",
"res",
":",
"return",
"res",
"raise",
"Exception",
"(",
"\"No .dist-info folder found in wheel\"",
")"
] | Identify the .dist-info folder inside a wheel ZipFile. | [
"Identify",
"the",
".",
"dist",
"-",
"info",
"folder",
"inside",
"a",
"wheel",
"ZipFile",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L75-L84 |
25,157 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | _get_wheel_metadata_from_wheel | def _get_wheel_metadata_from_wheel(
backend, metadata_directory, config_settings):
"""Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook.
"""
from zipfile import ZipFile
whl_basename = backend.build_wheel(metadata_directory, config_settings)
with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
pass # Touch marker file
whl_file = os.path.join(metadata_directory, whl_basename)
with ZipFile(whl_file) as zipf:
dist_info = _dist_info_files(zipf)
zipf.extractall(path=metadata_directory, members=dist_info)
return dist_info[0].split('/')[0] | python | def _get_wheel_metadata_from_wheel(
backend, metadata_directory, config_settings):
"""Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook.
"""
from zipfile import ZipFile
whl_basename = backend.build_wheel(metadata_directory, config_settings)
with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
pass # Touch marker file
whl_file = os.path.join(metadata_directory, whl_basename)
with ZipFile(whl_file) as zipf:
dist_info = _dist_info_files(zipf)
zipf.extractall(path=metadata_directory, members=dist_info)
return dist_info[0].split('/')[0] | [
"def",
"_get_wheel_metadata_from_wheel",
"(",
"backend",
",",
"metadata_directory",
",",
"config_settings",
")",
":",
"from",
"zipfile",
"import",
"ZipFile",
"whl_basename",
"=",
"backend",
".",
"build_wheel",
"(",
"metadata_directory",
",",
"config_settings",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"metadata_directory",
",",
"WHEEL_BUILT_MARKER",
")",
",",
"'wb'",
")",
":",
"pass",
"# Touch marker file",
"whl_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"metadata_directory",
",",
"whl_basename",
")",
"with",
"ZipFile",
"(",
"whl_file",
")",
"as",
"zipf",
":",
"dist_info",
"=",
"_dist_info_files",
"(",
"zipf",
")",
"zipf",
".",
"extractall",
"(",
"path",
"=",
"metadata_directory",
",",
"members",
"=",
"dist_info",
")",
"return",
"dist_info",
"[",
"0",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]"
] | Build a wheel and extract the metadata from it.
Fallback for when the build backend does not
define the 'get_wheel_metadata' hook. | [
"Build",
"a",
"wheel",
"and",
"extract",
"the",
"metadata",
"from",
"it",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L87-L103 |
25,158 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | _find_already_built_wheel | def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
return None
whl_files = glob(os.path.join(metadata_parent, '*.whl'))
if not whl_files:
print('Found wheel built marker, but no .whl files')
return None
if len(whl_files) > 1:
print('Found multiple .whl files; unspecified behaviour. '
'Will call build_wheel.')
return None
# Exactly one .whl file
return whl_files[0] | python | def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
return None
whl_files = glob(os.path.join(metadata_parent, '*.whl'))
if not whl_files:
print('Found wheel built marker, but no .whl files')
return None
if len(whl_files) > 1:
print('Found multiple .whl files; unspecified behaviour. '
'Will call build_wheel.')
return None
# Exactly one .whl file
return whl_files[0] | [
"def",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
":",
"if",
"not",
"metadata_directory",
":",
"return",
"None",
"metadata_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"metadata_directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pjoin",
"(",
"metadata_parent",
",",
"WHEEL_BUILT_MARKER",
")",
")",
":",
"return",
"None",
"whl_files",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"metadata_parent",
",",
"'*.whl'",
")",
")",
"if",
"not",
"whl_files",
":",
"print",
"(",
"'Found wheel built marker, but no .whl files'",
")",
"return",
"None",
"if",
"len",
"(",
"whl_files",
")",
">",
"1",
":",
"print",
"(",
"'Found multiple .whl files; unspecified behaviour. '",
"'Will call build_wheel.'",
")",
"return",
"None",
"# Exactly one .whl file",
"return",
"whl_files",
"[",
"0",
"]"
] | Check for a wheel already built during the get_wheel_metadata hook. | [
"Check",
"for",
"a",
"wheel",
"already",
"built",
"during",
"the",
"get_wheel_metadata",
"hook",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L106-L125 |
25,159 | pypa/pipenv | pipenv/vendor/pep517/_in_process.py | build_wheel | def build_wheel(wheel_directory, config_settings, metadata_directory=None):
"""Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
"""
prebuilt_whl = _find_already_built_wheel(metadata_directory)
if prebuilt_whl:
shutil.copy2(prebuilt_whl, wheel_directory)
return os.path.basename(prebuilt_whl)
return _build_backend().build_wheel(wheel_directory, config_settings,
metadata_directory) | python | def build_wheel(wheel_directory, config_settings, metadata_directory=None):
"""Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
"""
prebuilt_whl = _find_already_built_wheel(metadata_directory)
if prebuilt_whl:
shutil.copy2(prebuilt_whl, wheel_directory)
return os.path.basename(prebuilt_whl)
return _build_backend().build_wheel(wheel_directory, config_settings,
metadata_directory) | [
"def",
"build_wheel",
"(",
"wheel_directory",
",",
"config_settings",
",",
"metadata_directory",
"=",
"None",
")",
":",
"prebuilt_whl",
"=",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
"if",
"prebuilt_whl",
":",
"shutil",
".",
"copy2",
"(",
"prebuilt_whl",
",",
"wheel_directory",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"prebuilt_whl",
")",
"return",
"_build_backend",
"(",
")",
".",
"build_wheel",
"(",
"wheel_directory",
",",
"config_settings",
",",
"metadata_directory",
")"
] | Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel. | [
"Invoke",
"the",
"mandatory",
"build_wheel",
"hook",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L128-L141 |
25,160 | pypa/pipenv | pipenv/vendor/backports/functools_lru_cache.py | update_wrapper | def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
"""
Patch two bugs in functools.update_wrapper.
"""
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper | python | def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
"""
Patch two bugs in functools.update_wrapper.
"""
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper | [
"def",
"update_wrapper",
"(",
"wrapper",
",",
"wrapped",
",",
"assigned",
"=",
"functools",
".",
"WRAPPER_ASSIGNMENTS",
",",
"updated",
"=",
"functools",
".",
"WRAPPER_UPDATES",
")",
":",
"# workaround for http://bugs.python.org/issue3445",
"assigned",
"=",
"tuple",
"(",
"attr",
"for",
"attr",
"in",
"assigned",
"if",
"hasattr",
"(",
"wrapped",
",",
"attr",
")",
")",
"wrapper",
"=",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"wrapped",
",",
"assigned",
",",
"updated",
")",
"# workaround for https://bugs.python.org/issue17482",
"wrapper",
".",
"__wrapped__",
"=",
"wrapped",
"return",
"wrapper"
] | Patch two bugs in functools.update_wrapper. | [
"Patch",
"two",
"bugs",
"in",
"functools",
".",
"update_wrapper",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/functools_lru_cache.py#L11-L23 |
25,161 | pypa/pipenv | pipenv/vendor/jinja2/idtracking.py | FrameSymbolVisitor.visit_Name | def visit_Name(self, node, store_as_param=False, **kwargs):
"""All assignments to names go through this function."""
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name) | python | def visit_Name(self, node, store_as_param=False, **kwargs):
"""All assignments to names go through this function."""
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name) | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
",",
"store_as_param",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"store_as_param",
"or",
"node",
".",
"ctx",
"==",
"'param'",
":",
"self",
".",
"symbols",
".",
"declare_parameter",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'store'",
":",
"self",
".",
"symbols",
".",
"store",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'load'",
":",
"self",
".",
"symbols",
".",
"load",
"(",
"node",
".",
"name",
")"
] | All assignments to names go through this function. | [
"All",
"assignments",
"to",
"names",
"go",
"through",
"this",
"function",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/idtracking.py#L209-L216 |
25,162 | pypa/pipenv | pipenv/vendor/jinja2/idtracking.py | FrameSymbolVisitor.visit_Assign | def visit_Assign(self, node, **kwargs):
"""Visit assignments in the correct order."""
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs) | python | def visit_Assign(self, node, **kwargs):
"""Visit assignments in the correct order."""
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs) | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"node",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"visit",
"(",
"node",
".",
"target",
",",
"*",
"*",
"kwargs",
")"
] | Visit assignments in the correct order. | [
"Visit",
"assignments",
"in",
"the",
"correct",
"order",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/idtracking.py#L254-L257 |
25,163 | pypa/pipenv | pipenv/vendor/attr/_compat.py | make_set_closure_cell | def make_set_closure_cell():
"""
Moved into a function for testability.
"""
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell | python | def make_set_closure_cell():
"""
Moved into a function for testability.
"""
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell | [
"def",
"make_set_closure_cell",
"(",
")",
":",
"if",
"PYPY",
":",
"# pragma: no cover",
"def",
"set_closure_cell",
"(",
"cell",
",",
"value",
")",
":",
"cell",
".",
"__setstate__",
"(",
"(",
"value",
",",
")",
")",
"else",
":",
"try",
":",
"ctypes",
"=",
"import_ctypes",
"(",
")",
"set_closure_cell",
"=",
"ctypes",
".",
"pythonapi",
".",
"PyCell_Set",
"set_closure_cell",
".",
"argtypes",
"=",
"(",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"py_object",
")",
"set_closure_cell",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"except",
"Exception",
":",
"# We try best effort to set the cell, but sometimes it's not",
"# possible. For example on Jython or on GAE.",
"set_closure_cell",
"=",
"just_warn",
"return",
"set_closure_cell"
] | Moved into a function for testability. | [
"Moved",
"into",
"a",
"function",
"for",
"testability",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_compat.py#L136-L156 |
25,164 | pypa/pipenv | pipenv/vendor/pexpect/pty_spawn.py | spawn.read_nonblocking | def read_nonblocking(self, size=1, timeout=-1):
'''This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. '''
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was terminated.
# FIXME So does this mean Irix systems are forced to always have
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
if not r and not self.isalive():
self.flag_eof = True
raise EOF('End Of File (EOF). Slow platform.')
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts(
[self.child_fd], [], [], timeout
)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.child_fd in r:
return super(spawn, self).read_nonblocking(size)
raise ExceptionPexpect('Reached an unexpected state.') | python | def read_nonblocking(self, size=1, timeout=-1):
'''This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. '''
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was terminated.
# FIXME So does this mean Irix systems are forced to always have
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
if not r and not self.isalive():
self.flag_eof = True
raise EOF('End Of File (EOF). Slow platform.')
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts(
[self.child_fd], [], [], timeout
)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.child_fd in r:
return super(spawn, self).read_nonblocking(size)
raise ExceptionPexpect('Reached an unexpected state.') | [
"def",
"read_nonblocking",
"(",
"self",
",",
"size",
"=",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"'I/O operation on closed file.'",
")",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"# Note that some systems such as Solaris do not give an EOF when",
"# the child dies. In fact, you can still try to read",
"# from the child_fd -- it will block forever or until TIMEOUT.",
"# For this case, I test isalive() before doing any reading.",
"# If isalive() is false, then I pretend that this is the same as EOF.",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"# timeout of 0 means \"poll\"",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
")",
"if",
"not",
"r",
":",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Braindead platform.'",
")",
"elif",
"self",
".",
"__irix_hack",
":",
"# Irix takes a long time before it realizes a child was terminated.",
"# FIXME So does this mean Irix systems are forced to always have",
"# FIXME a 2 second delay when calling read_nonblocking? That sucks.",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"2",
")",
"if",
"not",
"r",
"and",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End Of File (EOF). Slow platform.'",
")",
"if",
"self",
".",
"use_poll",
":",
"r",
"=",
"poll_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"timeout",
")",
"else",
":",
"r",
",",
"w",
",",
"e",
"=",
"select_ignore_interrupts",
"(",
"[",
"self",
".",
"child_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"if",
"not",
"r",
":",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"# Some platforms, such as Irix, will claim that their",
"# processes are alive; timeout on the select; and",
"# then finally admit that they are not alive.",
"self",
".",
"flag_eof",
"=",
"True",
"raise",
"EOF",
"(",
"'End of File (EOF). Very slow platform.'",
")",
"else",
":",
"raise",
"TIMEOUT",
"(",
"'Timeout exceeded.'",
")",
"if",
"self",
".",
"child_fd",
"in",
"r",
":",
"return",
"super",
"(",
"spawn",
",",
"self",
")",
".",
"read_nonblocking",
"(",
"size",
")",
"raise",
"ExceptionPexpect",
"(",
"'Reached an unexpected state.'",
")"
] | This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. | [
"This",
"reads",
"at",
"most",
"size",
"characters",
"from",
"the",
"child",
"application",
".",
"It",
"includes",
"a",
"timeout",
".",
"If",
"the",
"read",
"does",
"not",
"complete",
"within",
"the",
"timeout",
"period",
"then",
"a",
"TIMEOUT",
"exception",
"is",
"raised",
".",
"If",
"the",
"end",
"of",
"file",
"is",
"read",
"then",
"an",
"EOF",
"exception",
"will",
"be",
"raised",
".",
"If",
"a",
"logfile",
"is",
"specified",
"a",
"copy",
"is",
"written",
"to",
"that",
"log",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L415-L487 |
25,165 | pypa/pipenv | pipenv/vendor/pexpect/pty_spawn.py | spawn.send | def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
'''
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b) | python | def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
'''
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b) | [
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"delaybeforesend",
"is",
"not",
"None",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"delaybeforesend",
")",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")",
"b",
"=",
"self",
".",
"_encoder",
".",
"encode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"return",
"os",
".",
"write",
"(",
"self",
".",
"child_fd",
",",
"b",
")"
] | Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000) | [
"Sends",
"string",
"s",
"to",
"the",
"child",
"process",
"returning",
"the",
"number",
"of",
"bytes",
"written",
".",
"If",
"a",
"logfile",
"is",
"specified",
"a",
"copy",
"is",
"written",
"to",
"that",
"log",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L504-L546 |
25,166 | pypa/pipenv | pipenv/vendor/pexpect/pty_spawn.py | spawn._log_control | def _log_control(self, s):
"""Write control characters to the appropriate log files"""
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send') | python | def _log_control(self, s):
"""Write control characters to the appropriate log files"""
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send') | [
"def",
"_log_control",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"self",
".",
"encoding",
",",
"'replace'",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")"
] | Write control characters to the appropriate log files | [
"Write",
"control",
"characters",
"to",
"the",
"appropriate",
"log",
"files"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L557-L561 |
25,167 | pypa/pipenv | pipenv/vendor/pexpect/pty_spawn.py | spawn.sendintr | def sendintr(self):
'''This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. '''
n, byte = self.ptyproc.sendintr()
self._log_control(byte) | python | def sendintr(self):
'''This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. '''
n, byte = self.ptyproc.sendintr()
self._log_control(byte) | [
"def",
"sendintr",
"(",
"self",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendintr",
"(",
")",
"self",
".",
"_log_control",
"(",
"byte",
")"
] | This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. | [
"This",
"sends",
"a",
"SIGINT",
"to",
"the",
"child",
".",
"It",
"does",
"not",
"require",
"the",
"SIGINT",
"to",
"be",
"the",
"first",
"character",
"on",
"a",
"line",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/pty_spawn.py#L589-L594 |
25,168 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | extras_to_string | def extras_to_string(extras):
# type: (Iterable[S]) -> S
"""Turn a list of extras into a string"""
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(",".join(sorted(set(extras)))) | python | def extras_to_string(extras):
# type: (Iterable[S]) -> S
"""Turn a list of extras into a string"""
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(",".join(sorted(set(extras)))) | [
"def",
"extras_to_string",
"(",
"extras",
")",
":",
"# type: (Iterable[S]) -> S",
"if",
"isinstance",
"(",
"extras",
",",
"six",
".",
"string_types",
")",
":",
"if",
"extras",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"return",
"extras",
"else",
":",
"extras",
"=",
"[",
"extras",
"]",
"if",
"not",
"extras",
":",
"return",
"\"\"",
"return",
"\"[{0}]\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"set",
"(",
"extras",
")",
")",
")",
")"
] | Turn a list of extras into a string | [
"Turn",
"a",
"list",
"of",
"extras",
"into",
"a",
"string"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L143-L153 |
25,169 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | parse_extras | def parse_extras(extras_str):
# type: (AnyStr) -> List[AnyStr]
"""
Turn a string of extras into a parsed extras list
"""
from pkg_resources import Requirement
extras = Requirement.parse("fakepkg{0}".format(extras_to_string(extras_str))).extras
return sorted(dedup([extra.lower() for extra in extras])) | python | def parse_extras(extras_str):
# type: (AnyStr) -> List[AnyStr]
"""
Turn a string of extras into a parsed extras list
"""
from pkg_resources import Requirement
extras = Requirement.parse("fakepkg{0}".format(extras_to_string(extras_str))).extras
return sorted(dedup([extra.lower() for extra in extras])) | [
"def",
"parse_extras",
"(",
"extras_str",
")",
":",
"# type: (AnyStr) -> List[AnyStr]",
"from",
"pkg_resources",
"import",
"Requirement",
"extras",
"=",
"Requirement",
".",
"parse",
"(",
"\"fakepkg{0}\"",
".",
"format",
"(",
"extras_to_string",
"(",
"extras_str",
")",
")",
")",
".",
"extras",
"return",
"sorted",
"(",
"dedup",
"(",
"[",
"extra",
".",
"lower",
"(",
")",
"for",
"extra",
"in",
"extras",
"]",
")",
")"
] | Turn a string of extras into a parsed extras list | [
"Turn",
"a",
"string",
"of",
"extras",
"into",
"a",
"parsed",
"extras",
"list"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L156-L165 |
25,170 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | specs_to_string | def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
"""
Turn a list of specifier tuples into a string
"""
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return "" | python | def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
"""
Turn a list of specifier tuples into a string
"""
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return "" | [
"def",
"specs_to_string",
"(",
"specs",
")",
":",
"# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr",
"if",
"specs",
":",
"if",
"isinstance",
"(",
"specs",
",",
"six",
".",
"string_types",
")",
":",
"return",
"specs",
"try",
":",
"extras",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"spec",
")",
"for",
"spec",
"in",
"specs",
"]",
")",
"except",
"TypeError",
":",
"extras",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"spec",
".",
"_spec",
")",
"for",
"spec",
"in",
"specs",
"]",
")",
"# type: ignore",
"return",
"extras",
"return",
"\"\""
] | Turn a list of specifier tuples into a string | [
"Turn",
"a",
"list",
"of",
"specifier",
"tuples",
"into",
"a",
"string"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L168-L182 |
25,171 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | get_pyproject | def get_pyproject(path):
# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]
"""
Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]]
"""
if not path:
return
from vistir.compat import Path
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
path = path.parent
pp_toml = path.joinpath("pyproject.toml")
setup_py = path.joinpath("setup.py")
if not pp_toml.exists():
if not setup_py.exists():
return None
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
pyproject_data = {}
with io.open(pp_toml.as_posix(), encoding="utf-8") as fh:
pyproject_data = tomlkit.loads(fh.read())
build_system = pyproject_data.get("build-system", None)
if build_system is None:
if setup_py.exists():
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
build_system = {"requires": requires, "build-backend": backend}
pyproject_data["build_system"] = build_system
else:
requires = build_system.get("requires", ["setuptools>=40.8", "wheel"])
backend = build_system.get("build-backend", get_default_pyproject_backend())
return requires, backend | python | def get_pyproject(path):
# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]
"""
Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]]
"""
if not path:
return
from vistir.compat import Path
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
path = path.parent
pp_toml = path.joinpath("pyproject.toml")
setup_py = path.joinpath("setup.py")
if not pp_toml.exists():
if not setup_py.exists():
return None
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
pyproject_data = {}
with io.open(pp_toml.as_posix(), encoding="utf-8") as fh:
pyproject_data = tomlkit.loads(fh.read())
build_system = pyproject_data.get("build-system", None)
if build_system is None:
if setup_py.exists():
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
build_system = {"requires": requires, "build-backend": backend}
pyproject_data["build_system"] = build_system
else:
requires = build_system.get("requires", ["setuptools>=40.8", "wheel"])
backend = build_system.get("build-backend", get_default_pyproject_backend())
return requires, backend | [
"def",
"get_pyproject",
"(",
"path",
")",
":",
"# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]",
"if",
"not",
"path",
":",
"return",
"from",
"vistir",
".",
"compat",
"import",
"Path",
"if",
"not",
"isinstance",
"(",
"path",
",",
"Path",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"path",
".",
"is_dir",
"(",
")",
":",
"path",
"=",
"path",
".",
"parent",
"pp_toml",
"=",
"path",
".",
"joinpath",
"(",
"\"pyproject.toml\"",
")",
"setup_py",
"=",
"path",
".",
"joinpath",
"(",
"\"setup.py\"",
")",
"if",
"not",
"pp_toml",
".",
"exists",
"(",
")",
":",
"if",
"not",
"setup_py",
".",
"exists",
"(",
")",
":",
"return",
"None",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"else",
":",
"pyproject_data",
"=",
"{",
"}",
"with",
"io",
".",
"open",
"(",
"pp_toml",
".",
"as_posix",
"(",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"fh",
":",
"pyproject_data",
"=",
"tomlkit",
".",
"loads",
"(",
"fh",
".",
"read",
"(",
")",
")",
"build_system",
"=",
"pyproject_data",
".",
"get",
"(",
"\"build-system\"",
",",
"None",
")",
"if",
"build_system",
"is",
"None",
":",
"if",
"setup_py",
".",
"exists",
"(",
")",
":",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"else",
":",
"requires",
"=",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
"backend",
"=",
"get_default_pyproject_backend",
"(",
")",
"build_system",
"=",
"{",
"\"requires\"",
":",
"requires",
",",
"\"build-backend\"",
":",
"backend",
"}",
"pyproject_data",
"[",
"\"build_system\"",
"]",
"=",
"build_system",
"else",
":",
"requires",
"=",
"build_system",
".",
"get",
"(",
"\"requires\"",
",",
"[",
"\"setuptools>=40.8\"",
",",
"\"wheel\"",
"]",
")",
"backend",
"=",
"build_system",
".",
"get",
"(",
"\"build-backend\"",
",",
"get_default_pyproject_backend",
"(",
")",
")",
"return",
"requires",
",",
"backend"
] | Given a base path, look for the corresponding ``pyproject.toml`` file and return its
build_requires and build_backend.
:param AnyStr path: The root path of the project, should be a directory (will be truncated)
:return: A 2 tuple of build requirements and the build backend
:rtype: Optional[Tuple[List[AnyStr], AnyStr]] | [
"Given",
"a",
"base",
"path",
"look",
"for",
"the",
"corresponding",
"pyproject",
".",
"toml",
"file",
"and",
"return",
"its",
"build_requires",
"and",
"build_backend",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L382-L425 |
25,172 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | split_markers_from_line | def split_markers_from_line(line):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""Split markers from a dependency"""
if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):
marker_sep = ";"
else:
marker_sep = "; "
markers = None
if marker_sep in line:
line, markers = line.split(marker_sep, 1)
markers = markers.strip() if markers else None
return line, markers | python | def split_markers_from_line(line):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""Split markers from a dependency"""
if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):
marker_sep = ";"
else:
marker_sep = "; "
markers = None
if marker_sep in line:
line, markers = line.split(marker_sep, 1)
markers = markers.strip() if markers else None
return line, markers | [
"def",
"split_markers_from_line",
"(",
"line",
")",
":",
"# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]",
"if",
"not",
"any",
"(",
"line",
".",
"startswith",
"(",
"uri_prefix",
")",
"for",
"uri_prefix",
"in",
"SCHEME_LIST",
")",
":",
"marker_sep",
"=",
"\";\"",
"else",
":",
"marker_sep",
"=",
"\"; \"",
"markers",
"=",
"None",
"if",
"marker_sep",
"in",
"line",
":",
"line",
",",
"markers",
"=",
"line",
".",
"split",
"(",
"marker_sep",
",",
"1",
")",
"markers",
"=",
"markers",
".",
"strip",
"(",
")",
"if",
"markers",
"else",
"None",
"return",
"line",
",",
"markers"
] | Split markers from a dependency | [
"Split",
"markers",
"from",
"a",
"dependency"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L428-L439 |
25,173 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | split_ref_from_uri | def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""
Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]]
"""
if not isinstance(uri, six.string_types):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = urllib_parse.urlparse(uri)
path = parsed.path
ref = None
if "@" in path:
path, _, ref = path.rpartition("@")
parsed = parsed._replace(path=path)
return (urllib_parse.urlunparse(parsed), ref) | python | def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
"""
Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]]
"""
if not isinstance(uri, six.string_types):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = urllib_parse.urlparse(uri)
path = parsed.path
ref = None
if "@" in path:
path, _, ref = path.rpartition("@")
parsed = parsed._replace(path=path)
return (urllib_parse.urlunparse(parsed), ref) | [
"def",
"split_ref_from_uri",
"(",
"uri",
")",
":",
"# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]",
"if",
"not",
"isinstance",
"(",
"uri",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a string, received {0!r}\"",
".",
"format",
"(",
"uri",
")",
")",
"parsed",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"uri",
")",
"path",
"=",
"parsed",
".",
"path",
"ref",
"=",
"None",
"if",
"\"@\"",
"in",
"path",
":",
"path",
",",
"_",
",",
"ref",
"=",
"path",
".",
"rpartition",
"(",
"\"@\"",
")",
"parsed",
"=",
"parsed",
".",
"_replace",
"(",
"path",
"=",
"path",
")",
"return",
"(",
"urllib_parse",
".",
"urlunparse",
"(",
"parsed",
")",
",",
"ref",
")"
] | Given a path or URI, check for a ref and split it from the path if it is present,
returning a tuple of the original input and the ref or None.
:param AnyStr uri: The path or URI to split
:returns: A 2-tuple of the path or URI and the ref
:rtype: Tuple[AnyStr, Optional[AnyStr]] | [
"Given",
"a",
"path",
"or",
"URI",
"check",
"for",
"a",
"ref",
"and",
"split",
"it",
"from",
"the",
"path",
"if",
"it",
"is",
"present",
"returning",
"a",
"tuple",
"of",
"the",
"original",
"input",
"and",
"the",
"ref",
"or",
"None",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L453-L471 |
25,174 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | key_from_ireq | def key_from_ireq(ireq):
"""Get a standardized key for an InstallRequirement."""
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req) | python | def key_from_ireq(ireq):
"""Get a standardized key for an InstallRequirement."""
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req) | [
"def",
"key_from_ireq",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"req",
"is",
"None",
"and",
"ireq",
".",
"link",
"is",
"not",
"None",
":",
"return",
"str",
"(",
"ireq",
".",
"link",
")",
"else",
":",
"return",
"key_from_req",
"(",
"ireq",
".",
"req",
")"
] | Get a standardized key for an InstallRequirement. | [
"Get",
"a",
"standardized",
"key",
"for",
"an",
"InstallRequirement",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L500-L505 |
25,175 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | _requirement_to_str_lowercase_name | def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113.
"""
parts = [requirement.name.lower()]
if requirement.extras:
parts.append("[{0}]".format(",".join(sorted(requirement.extras))))
if requirement.specifier:
parts.append(str(requirement.specifier))
if requirement.url:
parts.append("@ {0}".format(requirement.url))
if requirement.marker:
parts.append("; {0}".format(requirement.marker))
return "".join(parts) | python | def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113.
"""
parts = [requirement.name.lower()]
if requirement.extras:
parts.append("[{0}]".format(",".join(sorted(requirement.extras))))
if requirement.specifier:
parts.append(str(requirement.specifier))
if requirement.url:
parts.append("@ {0}".format(requirement.url))
if requirement.marker:
parts.append("; {0}".format(requirement.marker))
return "".join(parts) | [
"def",
"_requirement_to_str_lowercase_name",
"(",
"requirement",
")",
":",
"parts",
"=",
"[",
"requirement",
".",
"name",
".",
"lower",
"(",
")",
"]",
"if",
"requirement",
".",
"extras",
":",
"parts",
".",
"append",
"(",
"\"[{0}]\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"requirement",
".",
"extras",
")",
")",
")",
")",
"if",
"requirement",
".",
"specifier",
":",
"parts",
".",
"append",
"(",
"str",
"(",
"requirement",
".",
"specifier",
")",
")",
"if",
"requirement",
".",
"url",
":",
"parts",
".",
"append",
"(",
"\"@ {0}\"",
".",
"format",
"(",
"requirement",
".",
"url",
")",
")",
"if",
"requirement",
".",
"marker",
":",
"parts",
".",
"append",
"(",
"\"; {0}\"",
".",
"format",
"(",
"requirement",
".",
"marker",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"parts",
")"
] | Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were invoking the original Requirement.__str__ method and
lower-casing the entire result, which would lowercase the name, *and* other,
important stuff that should not be lower-cased (such as the marker). See
this issue for more information: https://github.com/pypa/pipenv/issues/2113. | [
"Formats",
"a",
"packaging",
".",
"requirements",
".",
"Requirement",
"with",
"a",
"lowercase",
"name",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L521-L549 |
25,176 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | format_specifier | def format_specifier(ireq):
"""
Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal.
"""
# TODO: Ideally, this is carried over to the pip library itself
specs = ireq.specifier._specs if ireq.req is not None else []
specs = sorted(specs, key=lambda x: x._spec[1])
return ",".join(str(s) for s in specs) or "<any>" | python | def format_specifier(ireq):
"""
Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal.
"""
# TODO: Ideally, this is carried over to the pip library itself
specs = ireq.specifier._specs if ireq.req is not None else []
specs = sorted(specs, key=lambda x: x._spec[1])
return ",".join(str(s) for s in specs) or "<any>" | [
"def",
"format_specifier",
"(",
"ireq",
")",
":",
"# TODO: Ideally, this is carried over to the pip library itself",
"specs",
"=",
"ireq",
".",
"specifier",
".",
"_specs",
"if",
"ireq",
".",
"req",
"is",
"not",
"None",
"else",
"[",
"]",
"specs",
"=",
"sorted",
"(",
"specs",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"_spec",
"[",
"1",
"]",
")",
"return",
"\",\"",
".",
"join",
"(",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"specs",
")",
"or",
"\"<any>\""
] | Generic formatter for pretty printing the specifier part of
InstallRequirements to the terminal. | [
"Generic",
"formatter",
"for",
"pretty",
"printing",
"the",
"specifier",
"part",
"of",
"InstallRequirements",
"to",
"the",
"terminal",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L574-L582 |
25,177 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | clean_requires_python | def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
from_location = attrgetter("location.requires_python")
requires_python = getattr(c, "requires_python", from_location(c))
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates | python | def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
from_location = attrgetter("location.requires_python")
requires_python = getattr(c, "requires_python", from_location(c))
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates | [
"def",
"clean_requires_python",
"(",
"candidates",
")",
":",
"all_candidates",
"=",
"[",
"]",
"sys_version",
"=",
"\".\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
")",
")",
"from",
"packaging",
".",
"version",
"import",
"parse",
"as",
"parse_version",
"py_version",
"=",
"parse_version",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"PIP_PYTHON_VERSION\"",
",",
"sys_version",
")",
")",
"for",
"c",
"in",
"candidates",
":",
"from_location",
"=",
"attrgetter",
"(",
"\"location.requires_python\"",
")",
"requires_python",
"=",
"getattr",
"(",
"c",
",",
"\"requires_python\"",
",",
"from_location",
"(",
"c",
")",
")",
"if",
"requires_python",
":",
"# Old specifications had people setting this to single digits",
"# which is effectively the same as '>=digit,<digit+1'",
"if",
"requires_python",
".",
"isdigit",
"(",
")",
":",
"requires_python",
"=",
"\">={0},<{1}\"",
".",
"format",
"(",
"requires_python",
",",
"int",
"(",
"requires_python",
")",
"+",
"1",
")",
"try",
":",
"specifierset",
"=",
"SpecifierSet",
"(",
"requires_python",
")",
"except",
"InvalidSpecifier",
":",
"continue",
"else",
":",
"if",
"not",
"specifierset",
".",
"contains",
"(",
"py_version",
")",
":",
"continue",
"all_candidates",
".",
"append",
"(",
"c",
")",
"return",
"all_candidates"
] | Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes. | [
"Get",
"a",
"cleaned",
"list",
"of",
"all",
"the",
"candidates",
"with",
"valid",
"specifiers",
"in",
"the",
"requires_python",
"attributes",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L803-L828 |
25,178 | pypa/pipenv | pipenv/vendor/requirementslib/models/utils.py | get_name_variants | def get_name_variants(pkg):
# type: (STRING_TYPE) -> Set[STRING_TYPE]
"""
Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set
"""
if not isinstance(pkg, six.string_types):
raise TypeError("must provide a string to derive package names")
from pkg_resources import safe_name
from packaging.utils import canonicalize_name
pkg = pkg.lower()
names = {safe_name(pkg), canonicalize_name(pkg), pkg.replace("-", "_")}
return names | python | def get_name_variants(pkg):
# type: (STRING_TYPE) -> Set[STRING_TYPE]
"""
Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set
"""
if not isinstance(pkg, six.string_types):
raise TypeError("must provide a string to derive package names")
from pkg_resources import safe_name
from packaging.utils import canonicalize_name
pkg = pkg.lower()
names = {safe_name(pkg), canonicalize_name(pkg), pkg.replace("-", "_")}
return names | [
"def",
"get_name_variants",
"(",
"pkg",
")",
":",
"# type: (STRING_TYPE) -> Set[STRING_TYPE]",
"if",
"not",
"isinstance",
"(",
"pkg",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"must provide a string to derive package names\"",
")",
"from",
"pkg_resources",
"import",
"safe_name",
"from",
"packaging",
".",
"utils",
"import",
"canonicalize_name",
"pkg",
"=",
"pkg",
".",
"lower",
"(",
")",
"names",
"=",
"{",
"safe_name",
"(",
"pkg",
")",
",",
"canonicalize_name",
"(",
"pkg",
")",
",",
"pkg",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"}",
"return",
"names"
] | Given a packager name, get the variants of its name for both the canonicalized
and "safe" forms.
:param AnyStr pkg: The package to lookup
:returns: A list of names.
:rtype: Set | [
"Given",
"a",
"packager",
"name",
"get",
"the",
"variants",
"of",
"its",
"name",
"for",
"both",
"the",
"canonicalized",
"and",
"safe",
"forms",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/utils.py#L870-L888 |
25,179 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | _get_name_and_version | def _get_name_and_version(name, version, for_filename=False):
"""Return the distribution name with version.
If for_filename is true, return a filename-escaped form."""
if for_filename:
# For both name and version any runs of non-alphanumeric or '.'
# characters are replaced with a single '-'. Additionally any
# spaces in the version string become '.'
name = _FILESAFE.sub('-', name)
version = _FILESAFE.sub('-', version.replace(' ', '.'))
return '%s-%s' % (name, version) | python | def _get_name_and_version(name, version, for_filename=False):
"""Return the distribution name with version.
If for_filename is true, return a filename-escaped form."""
if for_filename:
# For both name and version any runs of non-alphanumeric or '.'
# characters are replaced with a single '-'. Additionally any
# spaces in the version string become '.'
name = _FILESAFE.sub('-', name)
version = _FILESAFE.sub('-', version.replace(' ', '.'))
return '%s-%s' % (name, version) | [
"def",
"_get_name_and_version",
"(",
"name",
",",
"version",
",",
"for_filename",
"=",
"False",
")",
":",
"if",
"for_filename",
":",
"# For both name and version any runs of non-alphanumeric or '.'",
"# characters are replaced with a single '-'. Additionally any",
"# spaces in the version string become '.'",
"name",
"=",
"_FILESAFE",
".",
"sub",
"(",
"'-'",
",",
"name",
")",
"version",
"=",
"_FILESAFE",
".",
"sub",
"(",
"'-'",
",",
"version",
".",
"replace",
"(",
"' '",
",",
"'.'",
")",
")",
"return",
"'%s-%s'",
"%",
"(",
"name",
",",
"version",
")"
] | Return the distribution name with version.
If for_filename is true, return a filename-escaped form. | [
"Return",
"the",
"distribution",
"name",
"with",
"version",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L247-L257 |
25,180 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.read | def read(self, filepath):
"""Read the metadata values from a file path."""
fp = codecs.open(filepath, 'r', encoding='utf-8')
try:
self.read_file(fp)
finally:
fp.close() | python | def read(self, filepath):
"""Read the metadata values from a file path."""
fp = codecs.open(filepath, 'r', encoding='utf-8')
try:
self.read_file(fp)
finally:
fp.close() | [
"def",
"read",
"(",
"self",
",",
"filepath",
")",
":",
"fp",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"self",
".",
"read_file",
"(",
"fp",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] | Read the metadata values from a file path. | [
"Read",
"the",
"metadata",
"values",
"from",
"a",
"file",
"path",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L354-L360 |
25,181 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.write | def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close() | python | def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close() | [
"def",
"write",
"(",
"self",
",",
"filepath",
",",
"skip_unknown",
"=",
"False",
")",
":",
"fp",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"self",
".",
"write_file",
"(",
"fp",
",",
"skip_unknown",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] | Write the metadata fields to filepath. | [
"Write",
"the",
"metadata",
"fields",
"to",
"filepath",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L385-L391 |
25,182 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.update | def update(self, other=None, **kwargs):
"""Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped.
"""
def _set(key, value):
if key in _ATTR2FIELD and value:
self.set(self._convert_name(key), value)
if not other:
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
_set(k, v) | python | def update(self, other=None, **kwargs):
"""Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped.
"""
def _set(key, value):
if key in _ATTR2FIELD and value:
self.set(self._convert_name(key), value)
if not other:
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
_set(k, v) | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_set",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"_ATTR2FIELD",
"and",
"value",
":",
"self",
".",
"set",
"(",
"self",
".",
"_convert_name",
"(",
"key",
")",
",",
"value",
")",
"if",
"not",
"other",
":",
"# other is None or empty container",
"pass",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"for",
"k",
"in",
"other",
".",
"keys",
"(",
")",
":",
"_set",
"(",
"k",
",",
"other",
"[",
"k",
"]",
")",
"else",
":",
"for",
"k",
",",
"v",
"in",
"other",
":",
"_set",
"(",
"k",
",",
"v",
")",
"if",
"kwargs",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"_set",
"(",
"k",
",",
"v",
")"
] | Set metadata values from the given iterable `other` and kwargs.
Behavior is like `dict.update`: If `other` has a ``keys`` method,
they are looped over and ``self[key]`` is assigned ``other[key]``.
Else, ``other`` is an iterable of ``(key, value)`` iterables.
Keys that don't match a metadata field or that have an empty value are
dropped. | [
"Set",
"metadata",
"values",
"from",
"the",
"given",
"iterable",
"other",
"and",
"kwargs",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L418-L444 |
25,183 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.set | def set(self, name, value):
"""Control then set a metadata field."""
name = self._convert_name(name)
if ((name in _ELEMENTSFIELD or name == 'Platform') and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [v.strip() for v in value.split(',')]
else:
value = []
elif (name in _LISTFIELDS and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [value]
else:
value = []
if logger.isEnabledFor(logging.WARNING):
project_name = self['Name']
scheme = get_scheme(self.scheme)
if name in _PREDICATE_FIELDS and value is not None:
for v in value:
# check that the values are valid
if not scheme.is_valid_matcher(v.split(';')[0]):
logger.warning(
"'%s': '%s' is not valid (field '%s')",
project_name, v, name)
# FIXME this rejects UNKNOWN, is that right?
elif name in _VERSIONS_FIELDS and value is not None:
if not scheme.is_valid_constraint_list(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
elif name in _VERSION_FIELDS and value is not None:
if not scheme.is_valid_version(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
if name in _UNICODEFIELDS:
if name == 'Description':
value = self._remove_line_prefix(value)
self._fields[name] = value | python | def set(self, name, value):
"""Control then set a metadata field."""
name = self._convert_name(name)
if ((name in _ELEMENTSFIELD or name == 'Platform') and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [v.strip() for v in value.split(',')]
else:
value = []
elif (name in _LISTFIELDS and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [value]
else:
value = []
if logger.isEnabledFor(logging.WARNING):
project_name = self['Name']
scheme = get_scheme(self.scheme)
if name in _PREDICATE_FIELDS and value is not None:
for v in value:
# check that the values are valid
if not scheme.is_valid_matcher(v.split(';')[0]):
logger.warning(
"'%s': '%s' is not valid (field '%s')",
project_name, v, name)
# FIXME this rejects UNKNOWN, is that right?
elif name in _VERSIONS_FIELDS and value is not None:
if not scheme.is_valid_constraint_list(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
elif name in _VERSION_FIELDS and value is not None:
if not scheme.is_valid_version(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
if name in _UNICODEFIELDS:
if name == 'Description':
value = self._remove_line_prefix(value)
self._fields[name] = value | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"if",
"(",
"(",
"name",
"in",
"_ELEMENTSFIELD",
"or",
"name",
"==",
"'Platform'",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"[",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"else",
":",
"value",
"=",
"[",
"]",
"elif",
"(",
"name",
"in",
"_LISTFIELDS",
"and",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"[",
"value",
"]",
"else",
":",
"value",
"=",
"[",
"]",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"WARNING",
")",
":",
"project_name",
"=",
"self",
"[",
"'Name'",
"]",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"scheme",
")",
"if",
"name",
"in",
"_PREDICATE_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"for",
"v",
"in",
"value",
":",
"# check that the values are valid",
"if",
"not",
"scheme",
".",
"is_valid_matcher",
"(",
"v",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not valid (field '%s')\"",
",",
"project_name",
",",
"v",
",",
"name",
")",
"# FIXME this rejects UNKNOWN, is that right?",
"elif",
"name",
"in",
"_VERSIONS_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"scheme",
".",
"is_valid_constraint_list",
"(",
"value",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not a valid version (field '%s')\"",
",",
"project_name",
",",
"value",
",",
"name",
")",
"elif",
"name",
"in",
"_VERSION_FIELDS",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"scheme",
".",
"is_valid_version",
"(",
"value",
")",
":",
"logger",
".",
"warning",
"(",
"\"'%s': '%s' is not a valid version (field '%s')\"",
",",
"project_name",
",",
"value",
",",
"name",
")",
"if",
"name",
"in",
"_UNICODEFIELDS",
":",
"if",
"name",
"==",
"'Description'",
":",
"value",
"=",
"self",
".",
"_remove_line_prefix",
"(",
"value",
")",
"self",
".",
"_fields",
"[",
"name",
"]",
"=",
"value"
] | Control then set a metadata field. | [
"Control",
"then",
"set",
"a",
"metadata",
"field",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L446-L488 |
25,184 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.get | def get(self, name, default=_MISSING):
"""Get a metadata field."""
name = self._convert_name(name)
if name not in self._fields:
if default is _MISSING:
default = self._default_value(name)
return default
if name in _UNICODEFIELDS:
value = self._fields[name]
return value
elif name in _LISTFIELDS:
value = self._fields[name]
if value is None:
return []
res = []
for val in value:
if name not in _LISTTUPLEFIELDS:
res.append(val)
else:
# That's for Project-URL
res.append((val[0], val[1]))
return res
elif name in _ELEMENTSFIELD:
value = self._fields[name]
if isinstance(value, string_types):
return value.split(',')
return self._fields[name] | python | def get(self, name, default=_MISSING):
"""Get a metadata field."""
name = self._convert_name(name)
if name not in self._fields:
if default is _MISSING:
default = self._default_value(name)
return default
if name in _UNICODEFIELDS:
value = self._fields[name]
return value
elif name in _LISTFIELDS:
value = self._fields[name]
if value is None:
return []
res = []
for val in value:
if name not in _LISTTUPLEFIELDS:
res.append(val)
else:
# That's for Project-URL
res.append((val[0], val[1]))
return res
elif name in _ELEMENTSFIELD:
value = self._fields[name]
if isinstance(value, string_types):
return value.split(',')
return self._fields[name] | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"_MISSING",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_fields",
":",
"if",
"default",
"is",
"_MISSING",
":",
"default",
"=",
"self",
".",
"_default_value",
"(",
"name",
")",
"return",
"default",
"if",
"name",
"in",
"_UNICODEFIELDS",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"return",
"value",
"elif",
"name",
"in",
"_LISTFIELDS",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"res",
"=",
"[",
"]",
"for",
"val",
"in",
"value",
":",
"if",
"name",
"not",
"in",
"_LISTTUPLEFIELDS",
":",
"res",
".",
"append",
"(",
"val",
")",
"else",
":",
"# That's for Project-URL",
"res",
".",
"append",
"(",
"(",
"val",
"[",
"0",
"]",
",",
"val",
"[",
"1",
"]",
")",
")",
"return",
"res",
"elif",
"name",
"in",
"_ELEMENTSFIELD",
":",
"value",
"=",
"self",
".",
"_fields",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"value",
".",
"split",
"(",
"','",
")",
"return",
"self",
".",
"_fields",
"[",
"name",
"]"
] | Get a metadata field. | [
"Get",
"a",
"metadata",
"field",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L490-L517 |
25,185 | pypa/pipenv | pipenv/vendor/distlib/metadata.py | LegacyMetadata.todict | def todict(self, skip_missing=False):
"""Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page).
"""
self.set_metadata_version()
mapping_1_0 = (
('metadata_version', 'Metadata-Version'),
('name', 'Name'),
('version', 'Version'),
('summary', 'Summary'),
('home_page', 'Home-page'),
('author', 'Author'),
('author_email', 'Author-email'),
('license', 'License'),
('description', 'Description'),
('keywords', 'Keywords'),
('platform', 'Platform'),
('classifiers', 'Classifier'),
('download_url', 'Download-URL'),
)
data = {}
for key, field_name in mapping_1_0:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
if self['Metadata-Version'] == '1.2':
mapping_1_2 = (
('requires_dist', 'Requires-Dist'),
('requires_python', 'Requires-Python'),
('requires_external', 'Requires-External'),
('provides_dist', 'Provides-Dist'),
('obsoletes_dist', 'Obsoletes-Dist'),
('project_url', 'Project-URL'),
('maintainer', 'Maintainer'),
('maintainer_email', 'Maintainer-email'),
)
for key, field_name in mapping_1_2:
if not skip_missing or field_name in self._fields:
if key != 'project_url':
data[key] = self[field_name]
else:
data[key] = [','.join(u) for u in self[field_name]]
elif self['Metadata-Version'] == '1.1':
mapping_1_1 = (
('provides', 'Provides'),
('requires', 'Requires'),
('obsoletes', 'Obsoletes'),
)
for key, field_name in mapping_1_1:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
return data | python | def todict(self, skip_missing=False):
"""Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page).
"""
self.set_metadata_version()
mapping_1_0 = (
('metadata_version', 'Metadata-Version'),
('name', 'Name'),
('version', 'Version'),
('summary', 'Summary'),
('home_page', 'Home-page'),
('author', 'Author'),
('author_email', 'Author-email'),
('license', 'License'),
('description', 'Description'),
('keywords', 'Keywords'),
('platform', 'Platform'),
('classifiers', 'Classifier'),
('download_url', 'Download-URL'),
)
data = {}
for key, field_name in mapping_1_0:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
if self['Metadata-Version'] == '1.2':
mapping_1_2 = (
('requires_dist', 'Requires-Dist'),
('requires_python', 'Requires-Python'),
('requires_external', 'Requires-External'),
('provides_dist', 'Provides-Dist'),
('obsoletes_dist', 'Obsoletes-Dist'),
('project_url', 'Project-URL'),
('maintainer', 'Maintainer'),
('maintainer_email', 'Maintainer-email'),
)
for key, field_name in mapping_1_2:
if not skip_missing or field_name in self._fields:
if key != 'project_url':
data[key] = self[field_name]
else:
data[key] = [','.join(u) for u in self[field_name]]
elif self['Metadata-Version'] == '1.1':
mapping_1_1 = (
('provides', 'Provides'),
('requires', 'Requires'),
('obsoletes', 'Obsoletes'),
)
for key, field_name in mapping_1_1:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
return data | [
"def",
"todict",
"(",
"self",
",",
"skip_missing",
"=",
"False",
")",
":",
"self",
".",
"set_metadata_version",
"(",
")",
"mapping_1_0",
"=",
"(",
"(",
"'metadata_version'",
",",
"'Metadata-Version'",
")",
",",
"(",
"'name'",
",",
"'Name'",
")",
",",
"(",
"'version'",
",",
"'Version'",
")",
",",
"(",
"'summary'",
",",
"'Summary'",
")",
",",
"(",
"'home_page'",
",",
"'Home-page'",
")",
",",
"(",
"'author'",
",",
"'Author'",
")",
",",
"(",
"'author_email'",
",",
"'Author-email'",
")",
",",
"(",
"'license'",
",",
"'License'",
")",
",",
"(",
"'description'",
",",
"'Description'",
")",
",",
"(",
"'keywords'",
",",
"'Keywords'",
")",
",",
"(",
"'platform'",
",",
"'Platform'",
")",
",",
"(",
"'classifiers'",
",",
"'Classifier'",
")",
",",
"(",
"'download_url'",
",",
"'Download-URL'",
")",
",",
")",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_0",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"if",
"self",
"[",
"'Metadata-Version'",
"]",
"==",
"'1.2'",
":",
"mapping_1_2",
"=",
"(",
"(",
"'requires_dist'",
",",
"'Requires-Dist'",
")",
",",
"(",
"'requires_python'",
",",
"'Requires-Python'",
")",
",",
"(",
"'requires_external'",
",",
"'Requires-External'",
")",
",",
"(",
"'provides_dist'",
",",
"'Provides-Dist'",
")",
",",
"(",
"'obsoletes_dist'",
",",
"'Obsoletes-Dist'",
")",
",",
"(",
"'project_url'",
",",
"'Project-URL'",
")",
",",
"(",
"'maintainer'",
",",
"'Maintainer'",
")",
",",
"(",
"'maintainer_email'",
",",
"'Maintainer-email'",
")",
",",
")",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_2",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"if",
"key",
"!=",
"'project_url'",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"else",
":",
"data",
"[",
"key",
"]",
"=",
"[",
"','",
".",
"join",
"(",
"u",
")",
"for",
"u",
"in",
"self",
"[",
"field_name",
"]",
"]",
"elif",
"self",
"[",
"'Metadata-Version'",
"]",
"==",
"'1.1'",
":",
"mapping_1_1",
"=",
"(",
"(",
"'provides'",
",",
"'Provides'",
")",
",",
"(",
"'requires'",
",",
"'Requires'",
")",
",",
"(",
"'obsoletes'",
",",
"'Obsoletes'",
")",
",",
")",
"for",
"key",
",",
"field_name",
"in",
"mapping_1_1",
":",
"if",
"not",
"skip_missing",
"or",
"field_name",
"in",
"self",
".",
"_fields",
":",
"data",
"[",
"key",
"]",
"=",
"self",
"[",
"field_name",
"]",
"return",
"data"
] | Return fields as a dict.
Field names will be converted to use the underscore-lowercase style
instead of hyphen-mixed case (i.e. home_page instead of Home-page). | [
"Return",
"fields",
"as",
"a",
"dict",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/metadata.py#L563-L620 |
25,186 | pypa/pipenv | pipenv/vendor/six.py | remove_move | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | python | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
"(",
"\"no such move, %r\"",
"%",
"(",
"name",
",",
")",
")"
] | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L497-L505 |
25,187 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_file.py | parse_requirements | def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
"""Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
"""
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req | python | def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
"""Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
"""
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req | [
"def",
"parse_requirements",
"(",
"filename",
",",
"# type: str",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"comes_from",
"=",
"None",
",",
"# type: Optional[str]",
"options",
"=",
"None",
",",
"# type: Optional[optparse.Values]",
"session",
"=",
"None",
",",
"# type: Optional[PipSession]",
"constraint",
"=",
"False",
",",
"# type: bool",
"wheel_cache",
"=",
"None",
",",
"# type: Optional[WheelCache]",
"use_pep517",
"=",
"None",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> Iterator[InstallRequirement]",
"if",
"session",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"parse_requirements() missing 1 required keyword argument: \"",
"\"'session'\"",
")",
"_",
",",
"content",
"=",
"get_file_content",
"(",
"filename",
",",
"comes_from",
"=",
"comes_from",
",",
"session",
"=",
"session",
")",
"lines_enum",
"=",
"preprocess",
"(",
"content",
",",
"options",
")",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"req_iter",
"=",
"process_line",
"(",
"line",
",",
"filename",
",",
"line_number",
",",
"finder",
",",
"comes_from",
",",
"options",
",",
"session",
",",
"wheel_cache",
",",
"use_pep517",
"=",
"use_pep517",
",",
"constraint",
"=",
"constraint",
")",
"for",
"req",
"in",
"req_iter",
":",
"yield",
"req"
] | Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option. | [
"Parse",
"a",
"requirements",
"file",
"and",
"yield",
"InstallRequirement",
"instances",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L73-L113 |
25,188 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_file.py | preprocess | def preprocess(content, options):
# type: (Text, Optional[optparse.Values]) -> ReqFileLines
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options
"""
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = skip_regex(lines_enum, options)
lines_enum = expand_env_variables(lines_enum)
return lines_enum | python | def preprocess(content, options):
# type: (Text, Optional[optparse.Values]) -> ReqFileLines
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options
"""
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = skip_regex(lines_enum, options)
lines_enum = expand_env_variables(lines_enum)
return lines_enum | [
"def",
"preprocess",
"(",
"content",
",",
"options",
")",
":",
"# type: (Text, Optional[optparse.Values]) -> ReqFileLines",
"lines_enum",
"=",
"enumerate",
"(",
"content",
".",
"splitlines",
"(",
")",
",",
"start",
"=",
"1",
")",
"# type: ReqFileLines",
"lines_enum",
"=",
"join_lines",
"(",
"lines_enum",
")",
"lines_enum",
"=",
"ignore_comments",
"(",
"lines_enum",
")",
"lines_enum",
"=",
"skip_regex",
"(",
"lines_enum",
",",
"options",
")",
"lines_enum",
"=",
"expand_env_variables",
"(",
"lines_enum",
")",
"return",
"lines_enum"
] | Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
:param options: cli options | [
"Split",
"filter",
"and",
"join",
"lines",
"and",
"return",
"a",
"line",
"iterator"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L116-L128 |
25,189 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_file.py | build_parser | def build_parser(line):
# type: (Text) -> optparse.OptionParser
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
# By default optparse sys.exits on parsing errors. We want to wrap
# that in our own exception.
def parser_exit(self, msg):
# add offending line
msg = 'Invalid requirement: %s\n%s' % (line, msg)
raise RequirementsFileParseError(msg)
# NOTE: mypy disallows assigning to a method
# https://github.com/python/mypy/issues/2427
parser.exit = parser_exit # type: ignore
return parser | python | def build_parser(line):
# type: (Text) -> optparse.OptionParser
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
# By default optparse sys.exits on parsing errors. We want to wrap
# that in our own exception.
def parser_exit(self, msg):
# add offending line
msg = 'Invalid requirement: %s\n%s' % (line, msg)
raise RequirementsFileParseError(msg)
# NOTE: mypy disallows assigning to a method
# https://github.com/python/mypy/issues/2427
parser.exit = parser_exit # type: ignore
return parser | [
"def",
"build_parser",
"(",
"line",
")",
":",
"# type: (Text) -> optparse.OptionParser",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"add_help_option",
"=",
"False",
")",
"option_factories",
"=",
"SUPPORTED_OPTIONS",
"+",
"SUPPORTED_OPTIONS_REQ",
"for",
"option_factory",
"in",
"option_factories",
":",
"option",
"=",
"option_factory",
"(",
")",
"parser",
".",
"add_option",
"(",
"option",
")",
"# By default optparse sys.exits on parsing errors. We want to wrap",
"# that in our own exception.",
"def",
"parser_exit",
"(",
"self",
",",
"msg",
")",
":",
"# add offending line",
"msg",
"=",
"'Invalid requirement: %s\\n%s'",
"%",
"(",
"line",
",",
"msg",
")",
"raise",
"RequirementsFileParseError",
"(",
"msg",
")",
"# NOTE: mypy disallows assigning to a method",
"# https://github.com/python/mypy/issues/2427",
"parser",
".",
"exit",
"=",
"parser_exit",
"# type: ignore",
"return",
"parser"
] | Return a parser for parsing requirement lines | [
"Return",
"a",
"parser",
"for",
"parsing",
"requirement",
"lines"
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L276-L298 |
25,190 | pypa/pipenv | pipenv/patched/notpip/_internal/req/req_file.py | expand_env_variables | def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore).
"""
for line_number, line in lines_enum:
for env_var, var_name in ENV_VAR_RE.findall(line):
value = os.getenv(var_name)
if not value:
continue
line = line.replace(env_var, value)
yield line_number, line | python | def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore).
"""
for line_number, line in lines_enum:
for env_var, var_name in ENV_VAR_RE.findall(line):
value = os.getenv(var_name)
if not value:
continue
line = line.replace(env_var, value)
yield line_number, line | [
"def",
"expand_env_variables",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"for",
"env_var",
",",
"var_name",
"in",
"ENV_VAR_RE",
".",
"findall",
"(",
"line",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"var_name",
")",
"if",
"not",
"value",
":",
"continue",
"line",
"=",
"line",
".",
"replace",
"(",
"env_var",
",",
"value",
")",
"yield",
"line_number",
",",
"line"
] | Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across platforms for requirement files.
These points are the result of a discusssion on the `github pull
request #3514 <https://github.com/pypa/pip/pull/3514>`_.
Valid characters in variable names follow the `POSIX standard
<http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
to uppercase letter, digits and the `_` (underscore). | [
"Replace",
"all",
"environment",
"variables",
"that",
"can",
"be",
"retrieved",
"via",
"os",
".",
"getenv",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L357-L382 |
25,191 | pypa/pipenv | pipenv/patched/notpip/_internal/utils/ui.py | InterruptibleMixin.finish | def finish(self):
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler) | python | def finish(self):
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler) | [
"def",
"finish",
"(",
"self",
")",
":",
"super",
"(",
"InterruptibleMixin",
",",
"self",
")",
".",
"finish",
"(",
")",
"signal",
"(",
"SIGINT",
",",
"self",
".",
"original_handler",
")"
] | Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted. | [
"Restore",
"the",
"original",
"SIGINT",
"handler",
"after",
"finishing",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/ui.py#L100-L108 |
25,192 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Node.iter_child_nodes | def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item | python | def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item | [
"def",
"iter_child_nodes",
"(",
"self",
",",
"exclude",
"=",
"None",
",",
"only",
"=",
"None",
")",
":",
"for",
"field",
",",
"item",
"in",
"self",
".",
"iter_fields",
"(",
"exclude",
",",
"only",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"n",
"in",
"item",
":",
"if",
"isinstance",
"(",
"n",
",",
"Node",
")",
":",
"yield",
"n",
"elif",
"isinstance",
"(",
"item",
",",
"Node",
")",
":",
"yield",
"item"
] | Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned. | [
"Iterates",
"over",
"all",
"direct",
"child",
"nodes",
"of",
"the",
"node",
".",
"This",
"iterates",
"over",
"all",
"fields",
"and",
"yields",
"the",
"values",
"of",
"they",
"are",
"nodes",
".",
"If",
"the",
"value",
"of",
"a",
"field",
"is",
"a",
"list",
"all",
"the",
"nodes",
"in",
"that",
"list",
"are",
"returned",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L164-L175 |
25,193 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Node.find_all | def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result | python | def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result | [
"def",
"find_all",
"(",
"self",
",",
"node_type",
")",
":",
"for",
"child",
"in",
"self",
".",
"iter_child_nodes",
"(",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"node_type",
")",
":",
"yield",
"child",
"for",
"result",
"in",
"child",
".",
"find_all",
"(",
"node_type",
")",
":",
"yield",
"result"
] | Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items. | [
"Find",
"all",
"the",
"nodes",
"of",
"a",
"given",
"type",
".",
"If",
"the",
"type",
"is",
"a",
"tuple",
"the",
"check",
"is",
"performed",
"for",
"any",
"of",
"the",
"tuple",
"items",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L184-L192 |
25,194 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Node.set_ctx | def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self | python | def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self | [
"def",
"set_ctx",
"(",
"self",
",",
"ctx",
")",
":",
"todo",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"if",
"'ctx'",
"in",
"node",
".",
"fields",
":",
"node",
".",
"ctx",
"=",
"ctx",
"todo",
".",
"extend",
"(",
"node",
".",
"iter_child_nodes",
"(",
")",
")",
"return",
"self"
] | Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context. | [
"Reset",
"the",
"context",
"of",
"a",
"node",
"and",
"all",
"child",
"nodes",
".",
"Per",
"default",
"the",
"parser",
"will",
"all",
"generate",
"nodes",
"that",
"have",
"a",
"load",
"context",
"as",
"it",
"s",
"the",
"most",
"common",
"one",
".",
"This",
"method",
"is",
"used",
"in",
"the",
"parser",
"to",
"set",
"assignment",
"targets",
"and",
"other",
"nodes",
"to",
"a",
"store",
"context",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L194-L206 |
25,195 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Node.set_lineno | def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self | python | def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self | [
"def",
"set_lineno",
"(",
"self",
",",
"lineno",
",",
"override",
"=",
"False",
")",
":",
"todo",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"if",
"'lineno'",
"in",
"node",
".",
"attributes",
":",
"if",
"node",
".",
"lineno",
"is",
"None",
"or",
"override",
":",
"node",
".",
"lineno",
"=",
"lineno",
"todo",
".",
"extend",
"(",
"node",
".",
"iter_child_nodes",
"(",
")",
")",
"return",
"self"
] | Set the line numbers of the node and children. | [
"Set",
"the",
"line",
"numbers",
"of",
"the",
"node",
"and",
"children",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L208-L217 |
25,196 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Node.set_environment | def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self | python | def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self | [
"def",
"set_environment",
"(",
"self",
",",
"environment",
")",
":",
"todo",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"node",
".",
"environment",
"=",
"environment",
"todo",
".",
"extend",
"(",
"node",
".",
"iter_child_nodes",
"(",
")",
")",
"return",
"self"
] | Set the environment for all nodes. | [
"Set",
"the",
"environment",
"for",
"all",
"nodes",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L219-L226 |
25,197 | pypa/pipenv | pipenv/vendor/jinja2/nodes.py | Const.from_untrusted | def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment) | python | def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment) | [
"def",
"from_untrusted",
"(",
"cls",
",",
"value",
",",
"lineno",
"=",
"None",
",",
"environment",
"=",
"None",
")",
":",
"from",
".",
"compiler",
"import",
"has_safe_repr",
"if",
"not",
"has_safe_repr",
"(",
"value",
")",
":",
"raise",
"Impossible",
"(",
")",
"return",
"cls",
"(",
"value",
",",
"lineno",
"=",
"lineno",
",",
"environment",
"=",
"environment",
")"
] | Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception. | [
"Return",
"a",
"const",
"object",
"if",
"the",
"value",
"is",
"representable",
"as",
"constant",
"value",
"in",
"the",
"generated",
"code",
"otherwise",
"it",
"will",
"raise",
"an",
"Impossible",
"exception",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nodes.py#L504-L512 |
25,198 | pypa/pipenv | pipenv/vendor/pep517/envbuild.py | build_wheel | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements.
"""
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_wheel(config_settings)
env.pip_install(reqs)
return hooks.build_wheel(wheel_dir, config_settings) | python | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements.
"""
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_wheel(config_settings)
env.pip_install(reqs)
return hooks.build_wheel(wheel_dir, config_settings) | [
"def",
"build_wheel",
"(",
"source_dir",
",",
"wheel_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
"=",
"_load_pyproject",
"(",
"source_dir",
")",
"hooks",
"=",
"Pep517HookCaller",
"(",
"source_dir",
",",
"backend",
")",
"with",
"BuildEnvironment",
"(",
")",
"as",
"env",
":",
"env",
".",
"pip_install",
"(",
"requires",
")",
"reqs",
"=",
"hooks",
".",
"get_requires_for_build_wheel",
"(",
"config_settings",
")",
"env",
".",
"pip_install",
"(",
"reqs",
")",
"return",
"hooks",
".",
"build_wheel",
"(",
"wheel_dir",
",",
"config_settings",
")"
] | Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements. | [
"Build",
"a",
"wheel",
"from",
"a",
"source",
"directory",
"using",
"PEP",
"517",
"hooks",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/envbuild.py#L117-L136 |
25,199 | pypa/pipenv | pipenv/vendor/pep517/envbuild.py | build_sdist | def build_sdist(source_dir, sdist_dir, config_settings=None):
"""Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements.
"""
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_sdist(config_settings)
env.pip_install(reqs)
return hooks.build_sdist(sdist_dir, config_settings) | python | def build_sdist(source_dir, sdist_dir, config_settings=None):
"""Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements.
"""
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_sdist(config_settings)
env.pip_install(reqs)
return hooks.build_sdist(sdist_dir, config_settings) | [
"def",
"build_sdist",
"(",
"source_dir",
",",
"sdist_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
"=",
"_load_pyproject",
"(",
"source_dir",
")",
"hooks",
"=",
"Pep517HookCaller",
"(",
"source_dir",
",",
"backend",
")",
"with",
"BuildEnvironment",
"(",
")",
"as",
"env",
":",
"env",
".",
"pip_install",
"(",
"requires",
")",
"reqs",
"=",
"hooks",
".",
"get_requires_for_build_sdist",
"(",
"config_settings",
")",
"env",
".",
"pip_install",
"(",
"reqs",
")",
"return",
"hooks",
".",
"build_sdist",
"(",
"sdist_dir",
",",
"config_settings",
")"
] | Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subprocess to install
build requirements. | [
"Build",
"an",
"sdist",
"from",
"a",
"source",
"directory",
"using",
"PEP",
"517",
"hooks",
"."
] | cae8d76c210b9777e90aab76e9c4b0e53bb19cde | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/envbuild.py#L139-L158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.