id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,800
pypa/pipenv
pipenv/patched/notpip/_internal/commands/show.py
print_results
def print_results(distributions, list_files=False, verbose=False): """ Print the informations from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if i > 0: logger.info("---") name = dist.get('name', '') required_by = [ pkg.project_name for pkg in pkg_resources.working_set if name in [required.name for required in pkg.requires()] ] logger.info("Name: %s", name) logger.info("Version: %s", dist.get('version', '')) logger.info("Summary: %s", dist.get('summary', '')) logger.info("Home-page: %s", dist.get('home-page', '')) logger.info("Author: %s", dist.get('author', '')) logger.info("Author-email: %s", dist.get('author-email', '')) logger.info("License: %s", dist.get('license', '')) logger.info("Location: %s", dist.get('location', '')) logger.info("Requires: %s", ', '.join(dist.get('requires', []))) logger.info("Required-by: %s", ', '.join(required_by)) if verbose: logger.info("Metadata-Version: %s", dist.get('metadata-version', '')) logger.info("Installer: %s", dist.get('installer', '')) logger.info("Classifiers:") for classifier in dist.get('classifiers', []): logger.info(" %s", classifier) logger.info("Entry-points:") for entry in dist.get('entry_points', []): logger.info(" %s", entry.strip()) if list_files: logger.info("Files:") for line in dist.get('files', []): logger.info(" %s", line.strip()) if "files" not in dist: logger.info("Cannot locate installed-files.txt") return results_printed
python
def print_results(distributions, list_files=False, verbose=False): """ Print the informations from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if i > 0: logger.info("---") name = dist.get('name', '') required_by = [ pkg.project_name for pkg in pkg_resources.working_set if name in [required.name for required in pkg.requires()] ] logger.info("Name: %s", name) logger.info("Version: %s", dist.get('version', '')) logger.info("Summary: %s", dist.get('summary', '')) logger.info("Home-page: %s", dist.get('home-page', '')) logger.info("Author: %s", dist.get('author', '')) logger.info("Author-email: %s", dist.get('author-email', '')) logger.info("License: %s", dist.get('license', '')) logger.info("Location: %s", dist.get('location', '')) logger.info("Requires: %s", ', '.join(dist.get('requires', []))) logger.info("Required-by: %s", ', '.join(required_by)) if verbose: logger.info("Metadata-Version: %s", dist.get('metadata-version', '')) logger.info("Installer: %s", dist.get('installer', '')) logger.info("Classifiers:") for classifier in dist.get('classifiers', []): logger.info(" %s", classifier) logger.info("Entry-points:") for entry in dist.get('entry_points', []): logger.info(" %s", entry.strip()) if list_files: logger.info("Files:") for line in dist.get('files', []): logger.info(" %s", line.strip()) if "files" not in dist: logger.info("Cannot locate installed-files.txt") return results_printed
[ "def", "print_results", "(", "distributions", ",", "list_files", "=", "False", ",", "verbose", "=", "False", ")", ":", "results_printed", "=", "False", "for", "i", ",", "dist", "in", "enumerate", "(", "distributions", ")", ":", "results_printed", "=", "True", "if", "i", ">", "0", ":", "logger", ".", "info", "(", "\"---\"", ")", "name", "=", "dist", ".", "get", "(", "'name'", ",", "''", ")", "required_by", "=", "[", "pkg", ".", "project_name", "for", "pkg", "in", "pkg_resources", ".", "working_set", "if", "name", "in", "[", "required", ".", "name", "for", "required", "in", "pkg", ".", "requires", "(", ")", "]", "]", "logger", ".", "info", "(", "\"Name: %s\"", ",", "name", ")", "logger", ".", "info", "(", "\"Version: %s\"", ",", "dist", ".", "get", "(", "'version'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Summary: %s\"", ",", "dist", ".", "get", "(", "'summary'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Home-page: %s\"", ",", "dist", ".", "get", "(", "'home-page'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Author: %s\"", ",", "dist", ".", "get", "(", "'author'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Author-email: %s\"", ",", "dist", ".", "get", "(", "'author-email'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"License: %s\"", ",", "dist", ".", "get", "(", "'license'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Location: %s\"", ",", "dist", ".", "get", "(", "'location'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Requires: %s\"", ",", "', '", ".", "join", "(", "dist", ".", "get", "(", "'requires'", ",", "[", "]", ")", ")", ")", "logger", ".", "info", "(", "\"Required-by: %s\"", ",", "', '", ".", "join", "(", "required_by", ")", ")", "if", "verbose", ":", "logger", ".", "info", "(", "\"Metadata-Version: %s\"", ",", "dist", ".", "get", "(", "'metadata-version'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Installer: %s\"", ",", "dist", ".", "get", "(", "'installer'", ",", "''", ")", ")", "logger", ".", "info", "(", "\"Classifiers:\"", ")", "for", "classifier", "in", "dist", ".", "get", "(", "'classifiers'", ",", "[", "]", ")", ":", "logger", ".", "info", "(", "\" %s\"", ",", "classifier", ")", "logger", ".", "info", "(", "\"Entry-points:\"", ")", "for", "entry", "in", "dist", ".", "get", "(", "'entry_points'", ",", "[", "]", ")", ":", "logger", ".", "info", "(", "\" %s\"", ",", "entry", ".", "strip", "(", ")", ")", "if", "list_files", ":", "logger", ".", "info", "(", "\"Files:\"", ")", "for", "line", "in", "dist", ".", "get", "(", "'files'", ",", "[", "]", ")", ":", "logger", ".", "info", "(", "\" %s\"", ",", "line", ".", "strip", "(", ")", ")", "if", "\"files\"", "not", "in", "dist", ":", "logger", ".", "info", "(", "\"Cannot locate installed-files.txt\"", ")", "return", "results_printed" ]
Print the informations from installed distributions found.
[ "Print", "the", "informations", "from", "installed", "distributions", "found", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/show.py#L125-L168
24,801
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.fail
def fail(self, msg, lineno=None, exc=TemplateSyntaxError): """Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename. """ if lineno is None: lineno = self.stream.current.lineno raise exc(msg, lineno, self.name, self.filename)
python
def fail(self, msg, lineno=None, exc=TemplateSyntaxError): """Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename. """ if lineno is None: lineno = self.stream.current.lineno raise exc(msg, lineno, self.name, self.filename)
[ "def", "fail", "(", "self", ",", "msg", ",", "lineno", "=", "None", ",", "exc", "=", "TemplateSyntaxError", ")", ":", "if", "lineno", "is", "None", ":", "lineno", "=", "self", ".", "stream", ".", "current", ".", "lineno", "raise", "exc", "(", "msg", ",", "lineno", ",", "self", ".", "name", ",", "self", ".", "filename", ")" ]
Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename.
[ "Convenience", "method", "that", "raises", "exc", "with", "the", "message", "passed", "line", "number", "or", "last", "line", "number", "as", "well", "as", "the", "current", "name", "and", "filename", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L52-L59
24,802
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.fail_unknown_tag
def fail_unknown_tag(self, name, lineno=None): """Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem. """ return self._fail_ut_eof(name, self._end_token_stack, lineno)
python
def fail_unknown_tag(self, name, lineno=None): """Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem. """ return self._fail_ut_eof(name, self._end_token_stack, lineno)
[ "def", "fail_unknown_tag", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "self", ".", "_fail_ut_eof", "(", "name", ",", "self", ".", "_end_token_stack", ",", "lineno", ")" ]
Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem.
[ "Called", "if", "the", "parser", "encounters", "an", "unknown", "tag", ".", "Tries", "to", "fail", "with", "a", "human", "readable", "error", "message", "that", "could", "help", "to", "identify", "the", "problem", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L92-L97
24,803
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.fail_eof
def fail_eof(self, end_tokens=None, lineno=None): """Like fail_unknown_tag but for end of template situations.""" stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
python
def fail_eof(self, end_tokens=None, lineno=None): """Like fail_unknown_tag but for end of template situations.""" stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
[ "def", "fail_eof", "(", "self", ",", "end_tokens", "=", "None", ",", "lineno", "=", "None", ")", ":", "stack", "=", "list", "(", "self", ".", "_end_token_stack", ")", "if", "end_tokens", "is", "not", "None", ":", "stack", ".", "append", "(", "end_tokens", ")", "return", "self", ".", "_fail_ut_eof", "(", "None", ",", "stack", ",", "lineno", ")" ]
Like fail_unknown_tag but for end of template situations.
[ "Like", "fail_unknown_tag", "but", "for", "end", "of", "template", "situations", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L99-L104
24,804
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.is_tuple_end
def is_tuple_end(self, extra_end_rules=None): """Are we at the end of a tuple?""" if self.stream.current.type in ('variable_end', 'block_end', 'rparen'): return True elif extra_end_rules is not None: return self.stream.current.test_any(extra_end_rules) return False
python
def is_tuple_end(self, extra_end_rules=None): """Are we at the end of a tuple?""" if self.stream.current.type in ('variable_end', 'block_end', 'rparen'): return True elif extra_end_rules is not None: return self.stream.current.test_any(extra_end_rules) return False
[ "def", "is_tuple_end", "(", "self", ",", "extra_end_rules", "=", "None", ")", ":", "if", "self", ".", "stream", ".", "current", ".", "type", "in", "(", "'variable_end'", ",", "'block_end'", ",", "'rparen'", ")", ":", "return", "True", "elif", "extra_end_rules", "is", "not", "None", ":", "return", "self", ".", "stream", ".", "current", ".", "test_any", "(", "extra_end_rules", ")", "return", "False" ]
Are we at the end of a tuple?
[ "Are", "we", "at", "the", "end", "of", "a", "tuple?" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L106-L112
24,805
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse_statement
def parse_statement(self): """Parse a single statement.""" token = self.stream.current if token.type != 'name': self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if token.value in _statement_keywords: return getattr(self, 'parse_' + self.stream.current.value)() if token.value == 'call': return self.parse_call_block() if token.value == 'filter': return self.parse_filter_block() ext = self.extensions.get(token.value) if ext is not None: return ext(self) # did not work out, remove the token we pushed by accident # from the stack so that the unknown tag fail function can # produce a proper error message. self._tag_stack.pop() pop_tag = False self.fail_unknown_tag(token.value, token.lineno) finally: if pop_tag: self._tag_stack.pop()
python
def parse_statement(self): """Parse a single statement.""" token = self.stream.current if token.type != 'name': self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if token.value in _statement_keywords: return getattr(self, 'parse_' + self.stream.current.value)() if token.value == 'call': return self.parse_call_block() if token.value == 'filter': return self.parse_filter_block() ext = self.extensions.get(token.value) if ext is not None: return ext(self) # did not work out, remove the token we pushed by accident # from the stack so that the unknown tag fail function can # produce a proper error message. self._tag_stack.pop() pop_tag = False self.fail_unknown_tag(token.value, token.lineno) finally: if pop_tag: self._tag_stack.pop()
[ "def", "parse_statement", "(", "self", ")", ":", "token", "=", "self", ".", "stream", ".", "current", "if", "token", ".", "type", "!=", "'name'", ":", "self", ".", "fail", "(", "'tag name expected'", ",", "token", ".", "lineno", ")", "self", ".", "_tag_stack", ".", "append", "(", "token", ".", "value", ")", "pop_tag", "=", "True", "try", ":", "if", "token", ".", "value", "in", "_statement_keywords", ":", "return", "getattr", "(", "self", ",", "'parse_'", "+", "self", ".", "stream", ".", "current", ".", "value", ")", "(", ")", "if", "token", ".", "value", "==", "'call'", ":", "return", "self", ".", "parse_call_block", "(", ")", "if", "token", ".", "value", "==", "'filter'", ":", "return", "self", ".", "parse_filter_block", "(", ")", "ext", "=", "self", ".", "extensions", ".", "get", "(", "token", ".", "value", ")", "if", "ext", "is", "not", "None", ":", "return", "ext", "(", "self", ")", "# did not work out, remove the token we pushed by accident", "# from the stack so that the unknown tag fail function can", "# produce a proper error message.", "self", ".", "_tag_stack", ".", "pop", "(", ")", "pop_tag", "=", "False", "self", ".", "fail_unknown_tag", "(", "token", ".", "value", ",", "token", ".", "lineno", ")", "finally", ":", "if", "pop_tag", ":", "self", ".", "_tag_stack", ".", "pop", "(", ")" ]
Parse a single statement.
[ "Parse", "a", "single", "statement", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L121-L147
24,806
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse_statements
def parse_statements(self, end_tokens, drop_needle=False): """Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed. """ # the first token may be a colon for python compatibility self.stream.skip_if('colon') # in the future it would be possible to add whole code sections # by adding some sort of end of statement token and parsing those here. self.stream.expect('block_end') result = self.subparse(end_tokens) # we reached the end of the template too early, the subparser # does not check for this, so we do that now if self.stream.current.type == 'eof': self.fail_eof(end_tokens) if drop_needle: next(self.stream) return result
python
def parse_statements(self, end_tokens, drop_needle=False): """Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed. """ # the first token may be a colon for python compatibility self.stream.skip_if('colon') # in the future it would be possible to add whole code sections # by adding some sort of end of statement token and parsing those here. self.stream.expect('block_end') result = self.subparse(end_tokens) # we reached the end of the template too early, the subparser # does not check for this, so we do that now if self.stream.current.type == 'eof': self.fail_eof(end_tokens) if drop_needle: next(self.stream) return result
[ "def", "parse_statements", "(", "self", ",", "end_tokens", ",", "drop_needle", "=", "False", ")", ":", "# the first token may be a colon for python compatibility", "self", ".", "stream", ".", "skip_if", "(", "'colon'", ")", "# in the future it would be possible to add whole code sections", "# by adding some sort of end of statement token and parsing those here.", "self", ".", "stream", ".", "expect", "(", "'block_end'", ")", "result", "=", "self", ".", "subparse", "(", "end_tokens", ")", "# we reached the end of the template too early, the subparser", "# does not check for this, so we do that now", "if", "self", ".", "stream", ".", "current", ".", "type", "==", "'eof'", ":", "self", ".", "fail_eof", "(", "end_tokens", ")", "if", "drop_needle", ":", "next", "(", "self", ".", "stream", ")", "return", "result" ]
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed.
[ "Parse", "multiple", "statements", "into", "a", "list", "until", "one", "of", "the", "end", "tokens", "is", "reached", ".", "This", "is", "used", "to", "parse", "the", "body", "of", "statements", "as", "it", "also", "parses", "template", "data", "if", "appropriate", ".", "The", "parser", "checks", "first", "if", "the", "current", "token", "is", "a", "colon", "and", "skips", "it", "if", "there", "is", "one", ".", "Then", "it", "checks", "for", "the", "block", "end", "and", "parses", "until", "if", "one", "of", "the", "end_tokens", "is", "reached", ".", "Per", "default", "the", "active", "token", "in", "the", "stream", "at", "the", "end", "of", "the", "call", "is", "the", "matched", "end", "token", ".", "If", "this", "is", "not", "wanted", "drop_needle", "can", "be", "set", "to", "True", "and", "the", "end", "token", "is", "removed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L149-L174
24,807
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse_for
def parse_for(self): """Parse a for loop.""" lineno = self.stream.expect('name:for').lineno target = self.parse_assign_target(extra_end_rules=('name:in',)) self.stream.expect('name:in') iter = self.parse_tuple(with_condexpr=False, extra_end_rules=('name:recursive',)) test = None if self.stream.skip_if('name:if'): test = self.parse_expression() recursive = self.stream.skip_if('name:recursive') body = self.parse_statements(('name:endfor', 'name:else')) if next(self.stream).value == 'endfor': else_ = [] else: else_ = self.parse_statements(('name:endfor',), drop_needle=True) return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)
python
def parse_for(self): """Parse a for loop.""" lineno = self.stream.expect('name:for').lineno target = self.parse_assign_target(extra_end_rules=('name:in',)) self.stream.expect('name:in') iter = self.parse_tuple(with_condexpr=False, extra_end_rules=('name:recursive',)) test = None if self.stream.skip_if('name:if'): test = self.parse_expression() recursive = self.stream.skip_if('name:recursive') body = self.parse_statements(('name:endfor', 'name:else')) if next(self.stream).value == 'endfor': else_ = [] else: else_ = self.parse_statements(('name:endfor',), drop_needle=True) return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)
[ "def", "parse_for", "(", "self", ")", ":", "lineno", "=", "self", ".", "stream", ".", "expect", "(", "'name:for'", ")", ".", "lineno", "target", "=", "self", ".", "parse_assign_target", "(", "extra_end_rules", "=", "(", "'name:in'", ",", ")", ")", "self", ".", "stream", ".", "expect", "(", "'name:in'", ")", "iter", "=", "self", ".", "parse_tuple", "(", "with_condexpr", "=", "False", ",", "extra_end_rules", "=", "(", "'name:recursive'", ",", ")", ")", "test", "=", "None", "if", "self", ".", "stream", ".", "skip_if", "(", "'name:if'", ")", ":", "test", "=", "self", ".", "parse_expression", "(", ")", "recursive", "=", "self", ".", "stream", ".", "skip_if", "(", "'name:recursive'", ")", "body", "=", "self", ".", "parse_statements", "(", "(", "'name:endfor'", ",", "'name:else'", ")", ")", "if", "next", "(", "self", ".", "stream", ")", ".", "value", "==", "'endfor'", ":", "else_", "=", "[", "]", "else", ":", "else_", "=", "self", ".", "parse_statements", "(", "(", "'name:endfor'", ",", ")", ",", "drop_needle", "=", "True", ")", "return", "nodes", ".", "For", "(", "target", ",", "iter", ",", "body", ",", "else_", ",", "test", ",", "recursive", ",", "lineno", "=", "lineno", ")" ]
Parse a for loop.
[ "Parse", "a", "for", "loop", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L188-L205
24,808
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse_if
def parse_if(self): """Parse an if construct.""" node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', 'name:endif')) node.elif_ = [] node.else_ = [] token = next(self.stream) if token.test('name:elif'): node = nodes.If(lineno=self.stream.current.lineno) result.elif_.append(node) continue elif token.test('name:else'): result.else_ = self.parse_statements(('name:endif',), drop_needle=True) break return result
python
def parse_if(self): """Parse an if construct.""" node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', 'name:endif')) node.elif_ = [] node.else_ = [] token = next(self.stream) if token.test('name:elif'): node = nodes.If(lineno=self.stream.current.lineno) result.elif_.append(node) continue elif token.test('name:else'): result.else_ = self.parse_statements(('name:endif',), drop_needle=True) break return result
[ "def", "parse_if", "(", "self", ")", ":", "node", "=", "result", "=", "nodes", ".", "If", "(", "lineno", "=", "self", ".", "stream", ".", "expect", "(", "'name:if'", ")", ".", "lineno", ")", "while", "1", ":", "node", ".", "test", "=", "self", ".", "parse_tuple", "(", "with_condexpr", "=", "False", ")", "node", ".", "body", "=", "self", ".", "parse_statements", "(", "(", "'name:elif'", ",", "'name:else'", ",", "'name:endif'", ")", ")", "node", ".", "elif_", "=", "[", "]", "node", ".", "else_", "=", "[", "]", "token", "=", "next", "(", "self", ".", "stream", ")", "if", "token", ".", "test", "(", "'name:elif'", ")", ":", "node", "=", "nodes", ".", "If", "(", "lineno", "=", "self", ".", "stream", ".", "current", ".", "lineno", ")", "result", ".", "elif_", ".", "append", "(", "node", ")", "continue", "elif", "token", ".", "test", "(", "'name:else'", ")", ":", "result", ".", "else_", "=", "self", ".", "parse_statements", "(", "(", "'name:endif'", ",", ")", ",", "drop_needle", "=", "True", ")", "break", "return", "result" ]
Parse an if construct.
[ "Parse", "an", "if", "construct", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L207-L225
24,809
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse_assign_target
def parse_assign_target(self, with_tuple=True, name_only=False, extra_end_rules=None, with_namespace=False): """Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function. If `with_namespace` is enabled, a namespace assignment may be parsed. """ if with_namespace and self.stream.look().type == 'dot': token = self.stream.expect('name') next(self.stream) # dot attr = self.stream.expect('name') target = nodes.NSRef(token.value, attr.value, lineno=token.lineno) elif name_only: token = self.stream.expect('name') target = nodes.Name(token.value, 'store', lineno=token.lineno) else: if with_tuple: target = self.parse_tuple(simplified=True, extra_end_rules=extra_end_rules) else: target = self.parse_primary() target.set_ctx('store') if not target.can_assign(): self.fail('can\'t assign to %r' % target.__class__. __name__.lower(), target.lineno) return target
python
def parse_assign_target(self, with_tuple=True, name_only=False, extra_end_rules=None, with_namespace=False): """Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function. If `with_namespace` is enabled, a namespace assignment may be parsed. """ if with_namespace and self.stream.look().type == 'dot': token = self.stream.expect('name') next(self.stream) # dot attr = self.stream.expect('name') target = nodes.NSRef(token.value, attr.value, lineno=token.lineno) elif name_only: token = self.stream.expect('name') target = nodes.Name(token.value, 'store', lineno=token.lineno) else: if with_tuple: target = self.parse_tuple(simplified=True, extra_end_rules=extra_end_rules) else: target = self.parse_primary() target.set_ctx('store') if not target.can_assign(): self.fail('can\'t assign to %r' % target.__class__. __name__.lower(), target.lineno) return target
[ "def", "parse_assign_target", "(", "self", ",", "with_tuple", "=", "True", ",", "name_only", "=", "False", ",", "extra_end_rules", "=", "None", ",", "with_namespace", "=", "False", ")", ":", "if", "with_namespace", "and", "self", ".", "stream", ".", "look", "(", ")", ".", "type", "==", "'dot'", ":", "token", "=", "self", ".", "stream", ".", "expect", "(", "'name'", ")", "next", "(", "self", ".", "stream", ")", "# dot", "attr", "=", "self", ".", "stream", ".", "expect", "(", "'name'", ")", "target", "=", "nodes", ".", "NSRef", "(", "token", ".", "value", ",", "attr", ".", "value", ",", "lineno", "=", "token", ".", "lineno", ")", "elif", "name_only", ":", "token", "=", "self", ".", "stream", ".", "expect", "(", "'name'", ")", "target", "=", "nodes", ".", "Name", "(", "token", ".", "value", ",", "'store'", ",", "lineno", "=", "token", ".", "lineno", ")", "else", ":", "if", "with_tuple", ":", "target", "=", "self", ".", "parse_tuple", "(", "simplified", "=", "True", ",", "extra_end_rules", "=", "extra_end_rules", ")", "else", ":", "target", "=", "self", ".", "parse_primary", "(", ")", "target", ".", "set_ctx", "(", "'store'", ")", "if", "not", "target", ".", "can_assign", "(", ")", ":", "self", ".", "fail", "(", "'can\\'t assign to %r'", "%", "target", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "target", ".", "lineno", ")", "return", "target" ]
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function. If `with_namespace` is enabled, a namespace assignment may be parsed.
[ "Parse", "an", "assignment", "target", ".", "As", "Jinja2", "allows", "assignments", "to", "tuples", "this", "function", "can", "parse", "all", "allowed", "assignment", "targets", ".", "Per", "default", "assignments", "to", "tuples", "are", "parsed", "that", "can", "be", "disable", "however", "by", "setting", "with_tuple", "to", "False", ".", "If", "only", "assignments", "to", "names", "are", "wanted", "name_only", "can", "be", "set", "to", "True", ".", "The", "extra_end_rules", "parameter", "is", "forwarded", "to", "the", "tuple", "parsing", "function", ".", "If", "with_namespace", "is", "enabled", "a", "namespace", "assignment", "may", "be", "parsed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L396-L424
24,810
pypa/pipenv
pipenv/vendor/jinja2/parser.py
Parser.parse
def parse(self): """Parse the whole template into a `Template` node.""" result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
python
def parse(self): """Parse the whole template into a `Template` node.""" result = nodes.Template(self.subparse(), lineno=1) result.set_environment(self.environment) return result
[ "def", "parse", "(", "self", ")", ":", "result", "=", "nodes", ".", "Template", "(", "self", ".", "subparse", "(", ")", ",", "lineno", "=", "1", ")", "result", ".", "set_environment", "(", "self", ".", "environment", ")", "return", "result" ]
Parse the whole template into a `Template` node.
[ "Parse", "the", "whole", "template", "into", "a", "Template", "node", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/parser.py#L899-L903
24,811
pypa/pipenv
pipenv/vendor/pexpect/exceptions.py
ExceptionPexpect.get_trace
def get_trace(self): '''This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included. ''' tblist = traceback.extract_tb(sys.exc_info()[2]) tblist = [item for item in tblist if ('pexpect/__init__' not in item[0]) and ('pexpect/expect' not in item[0])] tblist = traceback.format_list(tblist) return ''.join(tblist)
python
def get_trace(self): '''This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included. ''' tblist = traceback.extract_tb(sys.exc_info()[2]) tblist = [item for item in tblist if ('pexpect/__init__' not in item[0]) and ('pexpect/expect' not in item[0])] tblist = traceback.format_list(tblist) return ''.join(tblist)
[ "def", "get_trace", "(", "self", ")", ":", "tblist", "=", "traceback", ".", "extract_tb", "(", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "tblist", "=", "[", "item", "for", "item", "in", "tblist", "if", "(", "'pexpect/__init__'", "not", "in", "item", "[", "0", "]", ")", "and", "(", "'pexpect/expect'", "not", "in", "item", "[", "0", "]", ")", "]", "tblist", "=", "traceback", ".", "format_list", "(", "tblist", ")", "return", "''", ".", "join", "(", "tblist", ")" ]
This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included.
[ "This", "returns", "an", "abbreviated", "stack", "trace", "with", "lines", "that", "only", "concern", "the", "caller", ".", "In", "other", "words", "the", "stack", "trace", "inside", "the", "Pexpect", "module", "is", "not", "included", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/exceptions.py#L17-L26
24,812
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
parse_uri
def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8])
python
def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8])
[ "def", "parse_uri", "(", "uri", ")", ":", "groups", "=", "URI", ".", "match", "(", "uri", ")", ".", "groups", "(", ")", "return", "(", "groups", "[", "1", "]", ",", "groups", "[", "3", "]", ",", "groups", "[", "4", "]", ",", "groups", "[", "6", "]", ",", "groups", "[", "8", "]", ")" ]
Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri)
[ "Parses", "a", "URI", "using", "the", "regex", "given", "in", "Appendix", "B", "of", "RFC", "3986", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L21-L27
24,813
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
CacheController._urlnorm
def _urlnorm(cls, uri): """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = %s" % uri) scheme = scheme.lower() authority = authority.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path defrag_uri = scheme + "://" + authority + request_uri return defrag_uri
python
def _urlnorm(cls, uri): """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = %s" % uri) scheme = scheme.lower() authority = authority.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path defrag_uri = scheme + "://" + authority + request_uri return defrag_uri
[ "def", "_urlnorm", "(", "cls", ",", "uri", ")", ":", "(", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", ")", "=", "parse_uri", "(", "uri", ")", "if", "not", "scheme", "or", "not", "authority", ":", "raise", "Exception", "(", "\"Only absolute URIs are allowed. uri = %s\"", "%", "uri", ")", "scheme", "=", "scheme", ".", "lower", "(", ")", "authority", "=", "authority", ".", "lower", "(", ")", "if", "not", "path", ":", "path", "=", "\"/\"", "# Could do syntax based normalization of the URI before", "# computing the digest. See Section 6.2.2 of Std 66.", "request_uri", "=", "query", "and", "\"?\"", ".", "join", "(", "[", "path", ",", "query", "]", ")", "or", "path", "defrag_uri", "=", "scheme", "+", "\"://\"", "+", "authority", "+", "request_uri", "return", "defrag_uri" ]
Normalize the URL to create a safe key for the cache
[ "Normalize", "the", "URL", "to", "create", "a", "safe", "key", "for", "the", "cache" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L43-L60
24,814
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
CacheController.cached_request
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) # Bail out if the request insists on fresh data if "no-cache" in cc: logger.debug('Request header has "no-cache", cache bypassed') return False if "max-age" in cc and cc["max-age"] == 0: logger.debug('Request header has "max_age" as 0, cache bypassed') return False # Request allows serving from the cache, let's see if we find something cache_data = self.cache.get(cache_url) if cache_data is None: logger.debug("No cache entry available") return False # Check whether it can be deserialized resp = self.serializer.loads(request, cache_data) if not resp: logger.warning("Cache entry deserialization failed, entry ignored") return False # If we have a cached 301, return it immediately. We don't # need to test our response for other headers b/c it is # intrinsically "cacheable" as it is Permanent. # See: # https://tools.ietf.org/html/rfc7231#section-6.4.2 # # Client can try to refresh the value by repeating the request # with cache busting headers as usual (ie no-cache). if resp.status == 301: msg = ( 'Returning cached "301 Moved Permanently" response ' "(ignoring date and etag information)" ) logger.debug(msg) return resp headers = CaseInsensitiveDict(resp.headers) if not headers or "date" not in headers: if "etag" not in headers: # Without date or etag, the cached response can never be used # and should be deleted. logger.debug("Purging cached response: no date or etag") self.cache.delete(cache_url) logger.debug("Ignoring cached response: no date") return False now = time.time() date = calendar.timegm(parsedate_tz(headers["date"])) current_age = max(0, now - date) logger.debug("Current age based on date: %i", current_age) # TODO: There is an assumption that the result will be a # urllib3 response object. This may not be best since we # could probably avoid instantiating or constructing the # response until we know we need it. resp_cc = self.parse_cache_control(headers) # determine freshness freshness_lifetime = 0 # Check the max-age pragma in the cache control header if "max-age" in resp_cc: freshness_lifetime = resp_cc["max-age"] logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime) # If there isn't a max-age, check for an expires header elif "expires" in headers: expires = parsedate_tz(headers["expires"]) if expires is not None: expire_time = calendar.timegm(expires) - date freshness_lifetime = max(0, expire_time) logger.debug("Freshness lifetime from expires: %i", freshness_lifetime) # Determine if we are setting freshness limit in the # request. Note, this overrides what was in the response. if "max-age" in cc: freshness_lifetime = cc["max-age"] logger.debug( "Freshness lifetime from request max-age: %i", freshness_lifetime ) if "min-fresh" in cc: min_fresh = cc["min-fresh"] # adjust our current age by our min fresh current_age += min_fresh logger.debug("Adjusted current age from min-fresh: %i", current_age) # Return entry if it is fresh enough if freshness_lifetime > current_age: logger.debug('The response is "fresh", returning cached response') logger.debug("%i > %i", freshness_lifetime, current_age) return resp # we're not fresh. If we don't have an Etag, clear it out if "etag" not in headers: logger.debug('The cached response is "stale" with no etag, purging') self.cache.delete(cache_url) # return the original handler return False
python
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) # Bail out if the request insists on fresh data if "no-cache" in cc: logger.debug('Request header has "no-cache", cache bypassed') return False if "max-age" in cc and cc["max-age"] == 0: logger.debug('Request header has "max_age" as 0, cache bypassed') return False # Request allows serving from the cache, let's see if we find something cache_data = self.cache.get(cache_url) if cache_data is None: logger.debug("No cache entry available") return False # Check whether it can be deserialized resp = self.serializer.loads(request, cache_data) if not resp: logger.warning("Cache entry deserialization failed, entry ignored") return False # If we have a cached 301, return it immediately. We don't # need to test our response for other headers b/c it is # intrinsically "cacheable" as it is Permanent. # See: # https://tools.ietf.org/html/rfc7231#section-6.4.2 # # Client can try to refresh the value by repeating the request # with cache busting headers as usual (ie no-cache). if resp.status == 301: msg = ( 'Returning cached "301 Moved Permanently" response ' "(ignoring date and etag information)" ) logger.debug(msg) return resp headers = CaseInsensitiveDict(resp.headers) if not headers or "date" not in headers: if "etag" not in headers: # Without date or etag, the cached response can never be used # and should be deleted. logger.debug("Purging cached response: no date or etag") self.cache.delete(cache_url) logger.debug("Ignoring cached response: no date") return False now = time.time() date = calendar.timegm(parsedate_tz(headers["date"])) current_age = max(0, now - date) logger.debug("Current age based on date: %i", current_age) # TODO: There is an assumption that the result will be a # urllib3 response object. This may not be best since we # could probably avoid instantiating or constructing the # response until we know we need it. resp_cc = self.parse_cache_control(headers) # determine freshness freshness_lifetime = 0 # Check the max-age pragma in the cache control header if "max-age" in resp_cc: freshness_lifetime = resp_cc["max-age"] logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime) # If there isn't a max-age, check for an expires header elif "expires" in headers: expires = parsedate_tz(headers["expires"]) if expires is not None: expire_time = calendar.timegm(expires) - date freshness_lifetime = max(0, expire_time) logger.debug("Freshness lifetime from expires: %i", freshness_lifetime) # Determine if we are setting freshness limit in the # request. Note, this overrides what was in the response. if "max-age" in cc: freshness_lifetime = cc["max-age"] logger.debug( "Freshness lifetime from request max-age: %i", freshness_lifetime ) if "min-fresh" in cc: min_fresh = cc["min-fresh"] # adjust our current age by our min fresh current_age += min_fresh logger.debug("Adjusted current age from min-fresh: %i", current_age) # Return entry if it is fresh enough if freshness_lifetime > current_age: logger.debug('The response is "fresh", returning cached response') logger.debug("%i > %i", freshness_lifetime, current_age) return resp # we're not fresh. If we don't have an Etag, clear it out if "etag" not in headers: logger.debug('The cached response is "stale" with no etag, purging') self.cache.delete(cache_url) # return the original handler return False
[ "def", "cached_request", "(", "self", ",", "request", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "logger", ".", "debug", "(", "'Looking up \"%s\" in the cache'", ",", "cache_url", ")", "cc", "=", "self", ".", "parse_cache_control", "(", "request", ".", "headers", ")", "# Bail out if the request insists on fresh data", "if", "\"no-cache\"", "in", "cc", ":", "logger", ".", "debug", "(", "'Request header has \"no-cache\", cache bypassed'", ")", "return", "False", "if", "\"max-age\"", "in", "cc", "and", "cc", "[", "\"max-age\"", "]", "==", "0", ":", "logger", ".", "debug", "(", "'Request header has \"max_age\" as 0, cache bypassed'", ")", "return", "False", "# Request allows serving from the cache, let's see if we find something", "cache_data", "=", "self", ".", "cache", ".", "get", "(", "cache_url", ")", "if", "cache_data", "is", "None", ":", "logger", ".", "debug", "(", "\"No cache entry available\"", ")", "return", "False", "# Check whether it can be deserialized", "resp", "=", "self", ".", "serializer", ".", "loads", "(", "request", ",", "cache_data", ")", "if", "not", "resp", ":", "logger", ".", "warning", "(", "\"Cache entry deserialization failed, entry ignored\"", ")", "return", "False", "# If we have a cached 301, return it immediately. We don't", "# need to test our response for other headers b/c it is", "# intrinsically \"cacheable\" as it is Permanent.", "# See:", "# https://tools.ietf.org/html/rfc7231#section-6.4.2", "#", "# Client can try to refresh the value by repeating the request", "# with cache busting headers as usual (ie no-cache).", "if", "resp", ".", "status", "==", "301", ":", "msg", "=", "(", "'Returning cached \"301 Moved Permanently\" response '", "\"(ignoring date and etag information)\"", ")", "logger", ".", "debug", "(", "msg", ")", "return", "resp", "headers", "=", "CaseInsensitiveDict", "(", "resp", ".", "headers", ")", "if", "not", "headers", "or", "\"date\"", "not", "in", "headers", ":", "if", "\"etag\"", "not", "in", "headers", ":", "# Without date or etag, the cached response can never be used", "# and should be deleted.", "logger", ".", "debug", "(", "\"Purging cached response: no date or etag\"", ")", "self", ".", "cache", ".", "delete", "(", "cache_url", ")", "logger", ".", "debug", "(", "\"Ignoring cached response: no date\"", ")", "return", "False", "now", "=", "time", ".", "time", "(", ")", "date", "=", "calendar", ".", "timegm", "(", "parsedate_tz", "(", "headers", "[", "\"date\"", "]", ")", ")", "current_age", "=", "max", "(", "0", ",", "now", "-", "date", ")", "logger", ".", "debug", "(", "\"Current age based on date: %i\"", ",", "current_age", ")", "# TODO: There is an assumption that the result will be a", "# urllib3 response object. This may not be best since we", "# could probably avoid instantiating or constructing the", "# response until we know we need it.", "resp_cc", "=", "self", ".", "parse_cache_control", "(", "headers", ")", "# determine freshness", "freshness_lifetime", "=", "0", "# Check the max-age pragma in the cache control header", "if", "\"max-age\"", "in", "resp_cc", ":", "freshness_lifetime", "=", "resp_cc", "[", "\"max-age\"", "]", "logger", ".", "debug", "(", "\"Freshness lifetime from max-age: %i\"", ",", "freshness_lifetime", ")", "# If there isn't a max-age, check for an expires header", "elif", "\"expires\"", "in", "headers", ":", "expires", "=", "parsedate_tz", "(", "headers", "[", "\"expires\"", "]", ")", "if", "expires", "is", "not", "None", ":", "expire_time", "=", "calendar", ".", "timegm", "(", "expires", ")", "-", "date", "freshness_lifetime", "=", "max", "(", "0", ",", "expire_time", ")", "logger", ".", "debug", "(", "\"Freshness lifetime from expires: %i\"", ",", "freshness_lifetime", ")", "# Determine if we are setting freshness limit in the", "# request. Note, this overrides what was in the response.", "if", "\"max-age\"", "in", "cc", ":", "freshness_lifetime", "=", "cc", "[", "\"max-age\"", "]", "logger", ".", "debug", "(", "\"Freshness lifetime from request max-age: %i\"", ",", "freshness_lifetime", ")", "if", "\"min-fresh\"", "in", "cc", ":", "min_fresh", "=", "cc", "[", "\"min-fresh\"", "]", "# adjust our current age by our min fresh", "current_age", "+=", "min_fresh", "logger", ".", "debug", "(", "\"Adjusted current age from min-fresh: %i\"", ",", "current_age", ")", "# Return entry if it is fresh enough", "if", "freshness_lifetime", ">", "current_age", ":", "logger", ".", "debug", "(", "'The response is \"fresh\", returning cached response'", ")", "logger", ".", "debug", "(", "\"%i > %i\"", ",", "freshness_lifetime", ",", "current_age", ")", "return", "resp", "# we're not fresh. If we don't have an Etag, clear it out", "if", "\"etag\"", "not", "in", "headers", ":", "logger", ".", "debug", "(", "'The cached response is \"stale\" with no etag, purging'", ")", "self", ".", "cache", ".", "delete", "(", "cache_url", ")", "# return the original handler", "return", "False" ]
Return a cached response if it exists in the cache, otherwise return False.
[ "Return", "a", "cached", "response", "if", "it", "exists", "in", "the", "cache", "otherwise", "return", "False", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L120-L229
24,815
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
CacheController.cache_response
def cache_response(self, request, response, body=None, status_codes=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests cacheable_status_codes = status_codes or self.cacheable_status_codes if response.status not in cacheable_status_codes: logger.debug( "Status code %s not in %s", response.status, cacheable_status_codes ) return response_headers = CaseInsensitiveDict(response.headers) # If we've been given a body, our response has a Content-Length, that # Content-Length is valid then we can check to see if the body we've # been given matches the expected size, and if it doesn't we'll just # skip trying to cache it. if ( body is not None and "content-length" in response_headers and response_headers["content-length"].isdigit() and int(response_headers["content-length"]) != len(body) ): return cc_req = self.parse_cache_control(request.headers) cc = self.parse_cache_control(response_headers) cache_url = self.cache_url(request.url) logger.debug('Updating cache with response from "%s"', cache_url) # Delete it from the cache if we happen to have it stored there no_store = False if "no-store" in cc: no_store = True logger.debug('Response header has "no-store"') if "no-store" in cc_req: no_store = True logger.debug('Request header has "no-store"') if no_store and self.cache.get(cache_url): logger.debug('Purging existing cache entry to honor "no-store"') self.cache.delete(cache_url) if no_store: return # If we've been given an etag, then keep the response if self.cache_etags and "etag" in response_headers: logger.debug("Caching due to etag") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) ) # Add to the cache any 301s. We do this before looking that # the Date headers. elif response.status == 301: logger.debug("Caching permanant redirect") self.cache.set(cache_url, self.serializer.dumps(request, response)) # Add to the cache if the response headers demand it. If there # is no date header then we can't do anything about expiring # the cache. elif "date" in response_headers: # cache when there is a max-age > 0 if "max-age" in cc and cc["max-age"] > 0: logger.debug("Caching b/c date exists and max-age > 0") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) ) # If the request can expire, it means we should cache it # in the meantime. elif "expires" in response_headers: if response_headers["expires"]: logger.debug("Caching b/c of expires header") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) )
python
def cache_response(self, request, response, body=None, status_codes=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests cacheable_status_codes = status_codes or self.cacheable_status_codes if response.status not in cacheable_status_codes: logger.debug( "Status code %s not in %s", response.status, cacheable_status_codes ) return response_headers = CaseInsensitiveDict(response.headers) # If we've been given a body, our response has a Content-Length, that # Content-Length is valid then we can check to see if the body we've # been given matches the expected size, and if it doesn't we'll just # skip trying to cache it. if ( body is not None and "content-length" in response_headers and response_headers["content-length"].isdigit() and int(response_headers["content-length"]) != len(body) ): return cc_req = self.parse_cache_control(request.headers) cc = self.parse_cache_control(response_headers) cache_url = self.cache_url(request.url) logger.debug('Updating cache with response from "%s"', cache_url) # Delete it from the cache if we happen to have it stored there no_store = False if "no-store" in cc: no_store = True logger.debug('Response header has "no-store"') if "no-store" in cc_req: no_store = True logger.debug('Request header has "no-store"') if no_store and self.cache.get(cache_url): logger.debug('Purging existing cache entry to honor "no-store"') self.cache.delete(cache_url) if no_store: return # If we've been given an etag, then keep the response if self.cache_etags and "etag" in response_headers: logger.debug("Caching due to etag") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) ) # Add to the cache any 301s. We do this before looking that # the Date headers. elif response.status == 301: logger.debug("Caching permanant redirect") self.cache.set(cache_url, self.serializer.dumps(request, response)) # Add to the cache if the response headers demand it. If there # is no date header then we can't do anything about expiring # the cache. elif "date" in response_headers: # cache when there is a max-age > 0 if "max-age" in cc and cc["max-age"] > 0: logger.debug("Caching b/c date exists and max-age > 0") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) ) # If the request can expire, it means we should cache it # in the meantime. elif "expires" in response_headers: if response_headers["expires"]: logger.debug("Caching b/c of expires header") self.cache.set( cache_url, self.serializer.dumps(request, response, body=body) )
[ "def", "cache_response", "(", "self", ",", "request", ",", "response", ",", "body", "=", "None", ",", "status_codes", "=", "None", ")", ":", "# From httplib2: Don't cache 206's since we aren't going to", "# handle byte range requests", "cacheable_status_codes", "=", "status_codes", "or", "self", ".", "cacheable_status_codes", "if", "response", ".", "status", "not", "in", "cacheable_status_codes", ":", "logger", ".", "debug", "(", "\"Status code %s not in %s\"", ",", "response", ".", "status", ",", "cacheable_status_codes", ")", "return", "response_headers", "=", "CaseInsensitiveDict", "(", "response", ".", "headers", ")", "# If we've been given a body, our response has a Content-Length, that", "# Content-Length is valid then we can check to see if the body we've", "# been given matches the expected size, and if it doesn't we'll just", "# skip trying to cache it.", "if", "(", "body", "is", "not", "None", "and", "\"content-length\"", "in", "response_headers", "and", "response_headers", "[", "\"content-length\"", "]", ".", "isdigit", "(", ")", "and", "int", "(", "response_headers", "[", "\"content-length\"", "]", ")", "!=", "len", "(", "body", ")", ")", ":", "return", "cc_req", "=", "self", ".", "parse_cache_control", "(", "request", ".", "headers", ")", "cc", "=", "self", ".", "parse_cache_control", "(", "response_headers", ")", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "logger", ".", "debug", "(", "'Updating cache with response from \"%s\"'", ",", "cache_url", ")", "# Delete it from the cache if we happen to have it stored there", "no_store", "=", "False", "if", "\"no-store\"", "in", "cc", ":", "no_store", "=", "True", "logger", ".", "debug", "(", "'Response header has \"no-store\"'", ")", "if", "\"no-store\"", "in", "cc_req", ":", "no_store", "=", "True", "logger", ".", "debug", "(", "'Request header has \"no-store\"'", ")", "if", "no_store", "and", "self", ".", "cache", ".", "get", "(", "cache_url", ")", ":", "logger", ".", "debug", "(", "'Purging existing cache entry to honor \"no-store\"'", ")", "self", ".", "cache", ".", "delete", "(", "cache_url", ")", "if", "no_store", ":", "return", "# If we've been given an etag, then keep the response", "if", "self", ".", "cache_etags", "and", "\"etag\"", "in", "response_headers", ":", "logger", ".", "debug", "(", "\"Caching due to etag\"", ")", "self", ".", "cache", ".", "set", "(", "cache_url", ",", "self", ".", "serializer", ".", "dumps", "(", "request", ",", "response", ",", "body", "=", "body", ")", ")", "# Add to the cache any 301s. We do this before looking that", "# the Date headers.", "elif", "response", ".", "status", "==", "301", ":", "logger", ".", "debug", "(", "\"Caching permanant redirect\"", ")", "self", ".", "cache", ".", "set", "(", "cache_url", ",", "self", ".", "serializer", ".", "dumps", "(", "request", ",", "response", ")", ")", "# Add to the cache if the response headers demand it. If there", "# is no date header then we can't do anything about expiring", "# the cache.", "elif", "\"date\"", "in", "response_headers", ":", "# cache when there is a max-age > 0", "if", "\"max-age\"", "in", "cc", "and", "cc", "[", "\"max-age\"", "]", ">", "0", ":", "logger", ".", "debug", "(", "\"Caching b/c date exists and max-age > 0\"", ")", "self", ".", "cache", ".", "set", "(", "cache_url", ",", "self", ".", "serializer", ".", "dumps", "(", "request", ",", "response", ",", "body", "=", "body", ")", ")", "# If the request can expire, it means we should cache it", "# in the meantime.", "elif", "\"expires\"", "in", "response_headers", ":", "if", "response_headers", "[", "\"expires\"", "]", ":", "logger", ".", "debug", "(", "\"Caching b/c of expires header\"", ")", "self", ".", "cache", ".", "set", "(", "cache_url", ",", "self", ".", "serializer", ".", "dumps", "(", "request", ",", "response", ",", "body", "=", "body", ")", ")" ]
Algorithm for caching requests. This assumes a requests Response object.
[ "Algorithm", "for", "caching", "requests", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L247-L327
24,816
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/controller.py
CacheController.update_cached_response
def update_cached_response(self, request, response): """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ cache_url = self.cache_url(request.url) cached_response = self.serializer.loads(request, self.cache.get(cache_url)) if not cached_response: # we didn't have a cached response return response # Lets update our headers with the headers from the new request: # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1 # # The server isn't supposed to send headers that would make # the cached body invalid. But... just in case, we'll be sure # to strip out ones we know that might be problmatic due to # typical assumptions. excluded_headers = ["content-length"] cached_response.headers.update( dict( (k, v) for k, v in response.headers.items() if k.lower() not in excluded_headers ) ) # we want a 200 b/c we have content via the cache cached_response.status = 200 # update our cache self.cache.set(cache_url, self.serializer.dumps(request, cached_response)) return cached_response
python
def update_cached_response(self, request, response): """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ cache_url = self.cache_url(request.url) cached_response = self.serializer.loads(request, self.cache.get(cache_url)) if not cached_response: # we didn't have a cached response return response # Lets update our headers with the headers from the new request: # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1 # # The server isn't supposed to send headers that would make # the cached body invalid. But... just in case, we'll be sure # to strip out ones we know that might be problmatic due to # typical assumptions. excluded_headers = ["content-length"] cached_response.headers.update( dict( (k, v) for k, v in response.headers.items() if k.lower() not in excluded_headers ) ) # we want a 200 b/c we have content via the cache cached_response.status = 200 # update our cache self.cache.set(cache_url, self.serializer.dumps(request, cached_response)) return cached_response
[ "def", "update_cached_response", "(", "self", ",", "request", ",", "response", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "cached_response", "=", "self", ".", "serializer", ".", "loads", "(", "request", ",", "self", ".", "cache", ".", "get", "(", "cache_url", ")", ")", "if", "not", "cached_response", ":", "# we didn't have a cached response", "return", "response", "# Lets update our headers with the headers from the new request:", "# http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1", "#", "# The server isn't supposed to send headers that would make", "# the cached body invalid. But... just in case, we'll be sure", "# to strip out ones we know that might be problmatic due to", "# typical assumptions.", "excluded_headers", "=", "[", "\"content-length\"", "]", "cached_response", ".", "headers", ".", "update", "(", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "response", ".", "headers", ".", "items", "(", ")", "if", "k", ".", "lower", "(", ")", "not", "in", "excluded_headers", ")", ")", "# we want a 200 b/c we have content via the cache", "cached_response", ".", "status", "=", "200", "# update our cache", "self", ".", "cache", ".", "set", "(", "cache_url", ",", "self", ".", "serializer", ".", "dumps", "(", "request", ",", "cached_response", ")", ")", "return", "cached_response" ]
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response.
[ "On", "a", "304", "we", "will", "get", "a", "new", "set", "of", "headers", "that", "we", "want", "to", "update", "our", "cached", "value", "with", "assuming", "we", "have", "one", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/controller.py#L329-L367
24,817
pypa/pipenv
pipenv/vendor/pexpect/fdpexpect.py
fdspawn.close
def close (self): """Close the file descriptor. Calling this method a second time does nothing, but if the file descriptor was closed elsewhere, :class:`OSError` will be raised. """ if self.child_fd == -1: return self.flush() os.close(self.child_fd) self.child_fd = -1 self.closed = True
python
def close (self): """Close the file descriptor. Calling this method a second time does nothing, but if the file descriptor was closed elsewhere, :class:`OSError` will be raised. """ if self.child_fd == -1: return self.flush() os.close(self.child_fd) self.child_fd = -1 self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "child_fd", "==", "-", "1", ":", "return", "self", ".", "flush", "(", ")", "os", ".", "close", "(", "self", ".", "child_fd", ")", "self", ".", "child_fd", "=", "-", "1", "self", ".", "closed", "=", "True" ]
Close the file descriptor. Calling this method a second time does nothing, but if the file descriptor was closed elsewhere, :class:`OSError` will be raised.
[ "Close", "the", "file", "descriptor", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/fdpexpect.py#L63-L75
24,818
pypa/pipenv
pipenv/vendor/pexpect/fdpexpect.py
fdspawn.read_nonblocking
def read_nonblocking(self, size=1, timeout=-1): """ Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:`select.select`, timeout is implemented conditionally for POSIX systems. :param int size: Read at most *size* bytes. :param int timeout: Wait timeout seconds for file descriptor to be ready to read. When -1 (default), use self.timeout. When 0, poll. :return: String containing the bytes read """ if os.name == 'posix': if timeout == -1: timeout = self.timeout rlist = [self.child_fd] wlist = [] xlist = [] if self.use_poll: rlist = poll_ignore_interrupts(rlist, timeout) else: rlist, wlist, xlist = select_ignore_interrupts( rlist, wlist, xlist, timeout ) if self.child_fd not in rlist: raise TIMEOUT('Timeout exceeded.') return super(fdspawn, self).read_nonblocking(size)
python
def read_nonblocking(self, size=1, timeout=-1): """ Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:`select.select`, timeout is implemented conditionally for POSIX systems. :param int size: Read at most *size* bytes. :param int timeout: Wait timeout seconds for file descriptor to be ready to read. When -1 (default), use self.timeout. When 0, poll. :return: String containing the bytes read """ if os.name == 'posix': if timeout == -1: timeout = self.timeout rlist = [self.child_fd] wlist = [] xlist = [] if self.use_poll: rlist = poll_ignore_interrupts(rlist, timeout) else: rlist, wlist, xlist = select_ignore_interrupts( rlist, wlist, xlist, timeout ) if self.child_fd not in rlist: raise TIMEOUT('Timeout exceeded.') return super(fdspawn, self).read_nonblocking(size)
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "-", "1", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "rlist", "=", "[", "self", ".", "child_fd", "]", "wlist", "=", "[", "]", "xlist", "=", "[", "]", "if", "self", ".", "use_poll", ":", "rlist", "=", "poll_ignore_interrupts", "(", "rlist", ",", "timeout", ")", "else", ":", "rlist", ",", "wlist", ",", "xlist", "=", "select_ignore_interrupts", "(", "rlist", ",", "wlist", ",", "xlist", ",", "timeout", ")", "if", "self", ".", "child_fd", "not", "in", "rlist", ":", "raise", "TIMEOUT", "(", "'Timeout exceeded.'", ")", "return", "super", "(", "fdspawn", ",", "self", ")", ".", "read_nonblocking", "(", "size", ")" ]
Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:`select.select`, timeout is implemented conditionally for POSIX systems. :param int size: Read at most *size* bytes. :param int timeout: Wait timeout seconds for file descriptor to be ready to read. When -1 (default), use self.timeout. When 0, poll. :return: String containing the bytes read
[ "Read", "from", "the", "file", "descriptor", "and", "return", "the", "result", "as", "a", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/fdpexpect.py#L118-L148
24,819
pypa/pipenv
pipenv/vendor/jinja2/utils.py
clear_caches
def clear_caches(): """Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. """ from jinja2.environment import _spontaneous_environments from jinja2.lexer import _lexer_cache _spontaneous_environments.clear() _lexer_cache.clear()
python
def clear_caches(): """Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. """ from jinja2.environment import _spontaneous_environments from jinja2.lexer import _lexer_cache _spontaneous_environments.clear() _lexer_cache.clear()
[ "def", "clear_caches", "(", ")", ":", "from", "jinja2", ".", "environment", "import", "_spontaneous_environments", "from", "jinja2", ".", "lexer", "import", "_lexer_cache", "_spontaneous_environments", ".", "clear", "(", ")", "_lexer_cache", ".", "clear", "(", ")" ]
Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches.
[ "Jinja2", "keeps", "internal", "caches", "for", "environments", "and", "lexers", ".", "These", "are", "used", "so", "that", "Jinja2", "doesn", "t", "have", "to", "recreate", "environments", "and", "lexers", "all", "the", "time", ".", "Normally", "you", "don", "t", "have", "to", "care", "about", "that", "but", "if", "you", "are", "measuring", "memory", "consumption", "you", "may", "want", "to", "clean", "the", "caches", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L111-L120
24,820
pypa/pipenv
pipenv/vendor/jinja2/utils.py
pformat
def pformat(obj, verbose=False): """Prettyprint an object. Either use the `pretty` library or the builtin `pprint`. """ try: from pretty import pretty return pretty(obj, verbose=verbose) except ImportError: from pprint import pformat return pformat(obj)
python
def pformat(obj, verbose=False): """Prettyprint an object. Either use the `pretty` library or the builtin `pprint`. """ try: from pretty import pretty return pretty(obj, verbose=verbose) except ImportError: from pprint import pformat return pformat(obj)
[ "def", "pformat", "(", "obj", ",", "verbose", "=", "False", ")", ":", "try", ":", "from", "pretty", "import", "pretty", "return", "pretty", "(", "obj", ",", "verbose", "=", "verbose", ")", "except", "ImportError", ":", "from", "pprint", "import", "pformat", "return", "pformat", "(", "obj", ")" ]
Prettyprint an object. Either use the `pretty` library or the builtin `pprint`.
[ "Prettyprint", "an", "object", ".", "Either", "use", "the", "pretty", "library", "or", "the", "builtin", "pprint", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L177-L186
24,821
pypa/pipenv
pipenv/vendor/jinja2/utils.py
unicode_urlencode
def unicode_urlencode(obj, charset='utf-8', for_qs=False): """URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first. """ if not isinstance(obj, string_types): obj = text_type(obj) if isinstance(obj, text_type): obj = obj.encode(charset) safe = not for_qs and b'/' or b'' rv = text_type(url_quote(obj, safe)) if for_qs: rv = rv.replace('%20', '+') return rv
python
def unicode_urlencode(obj, charset='utf-8', for_qs=False): """URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first. """ if not isinstance(obj, string_types): obj = text_type(obj) if isinstance(obj, text_type): obj = obj.encode(charset) safe = not for_qs and b'/' or b'' rv = text_type(url_quote(obj, safe)) if for_qs: rv = rv.replace('%20', '+') return rv
[ "def", "unicode_urlencode", "(", "obj", ",", "charset", "=", "'utf-8'", ",", "for_qs", "=", "False", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "string_types", ")", ":", "obj", "=", "text_type", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "text_type", ")", ":", "obj", "=", "obj", ".", "encode", "(", "charset", ")", "safe", "=", "not", "for_qs", "and", "b'/'", "or", "b''", "rv", "=", "text_type", "(", "url_quote", "(", "obj", ",", "safe", ")", ")", "if", "for_qs", ":", "rv", "=", "rv", ".", "replace", "(", "'%20'", ",", "'+'", ")", "return", "rv" ]
URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first.
[ "URL", "escapes", "a", "single", "bytestring", "or", "unicode", "string", "with", "the", "given", "charset", "if", "applicable", "to", "URL", "safe", "quoting", "under", "all", "rules", "that", "need", "to", "be", "considered", "under", "all", "supported", "Python", "versions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L287-L303
24,822
pypa/pipenv
pipenv/vendor/jinja2/utils.py
select_autoescape
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False): """Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9 """ enabled_patterns = tuple('.' + x.lstrip('.').lower() for x in enabled_extensions) disabled_patterns = tuple('.' + x.lstrip('.').lower() for x in disabled_extensions) def autoescape(template_name): if template_name is None: return default_for_string template_name = template_name.lower() if template_name.endswith(enabled_patterns): return True if template_name.endswith(disabled_patterns): return False return default return autoescape
python
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False): """Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9 """ enabled_patterns = tuple('.' + x.lstrip('.').lower() for x in enabled_extensions) disabled_patterns = tuple('.' + x.lstrip('.').lower() for x in disabled_extensions) def autoescape(template_name): if template_name is None: return default_for_string template_name = template_name.lower() if template_name.endswith(enabled_patterns): return True if template_name.endswith(disabled_patterns): return False return default return autoescape
[ "def", "select_autoescape", "(", "enabled_extensions", "=", "(", "'html'", ",", "'htm'", ",", "'xml'", ")", ",", "disabled_extensions", "=", "(", ")", ",", "default_for_string", "=", "True", ",", "default", "=", "False", ")", ":", "enabled_patterns", "=", "tuple", "(", "'.'", "+", "x", ".", "lstrip", "(", "'.'", ")", ".", "lower", "(", ")", "for", "x", "in", "enabled_extensions", ")", "disabled_patterns", "=", "tuple", "(", "'.'", "+", "x", ".", "lstrip", "(", "'.'", ")", ".", "lower", "(", ")", "for", "x", "in", "disabled_extensions", ")", "def", "autoescape", "(", "template_name", ")", ":", "if", "template_name", "is", "None", ":", "return", "default_for_string", "template_name", "=", "template_name", ".", "lower", "(", ")", "if", "template_name", ".", "endswith", "(", "enabled_patterns", ")", ":", "return", "True", "if", "template_name", ".", "endswith", "(", "disabled_patterns", ")", ":", "return", "False", "return", "default", "return", "autoescape" ]
Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9
[ "Intelligently", "sets", "the", "initial", "value", "of", "autoescaping", "based", "on", "the", "filename", "of", "the", "template", ".", "This", "is", "the", "recommended", "way", "to", "configure", "autoescaping", "if", "you", "do", "not", "want", "to", "write", "a", "custom", "function", "yourself", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L491-L542
24,823
pypa/pipenv
pipenv/vendor/jinja2/utils.py
LRUCache.copy
def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
python
def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
[ "def", "copy", "(", "self", ")", ":", "rv", "=", "self", ".", "__class__", "(", "self", ".", "capacity", ")", "rv", ".", "_mapping", ".", "update", "(", "self", ".", "_mapping", ")", "rv", ".", "_queue", "=", "deque", "(", "self", ".", "_queue", ")", "return", "rv" ]
Return a shallow copy of the instance.
[ "Return", "a", "shallow", "copy", "of", "the", "instance", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L341-L346
24,824
pypa/pipenv
pipenv/vendor/jinja2/utils.py
LRUCache.setdefault
def setdefault(self, key, default=None): """Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. """ self._wlock.acquire() try: try: return self[key] except KeyError: self[key] = default return default finally: self._wlock.release()
python
def setdefault(self, key, default=None): """Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. """ self._wlock.acquire() try: try: return self[key] except KeyError: self[key] = default return default finally: self._wlock.release()
[ "def", "setdefault", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "self", ".", "_wlock", ".", "acquire", "(", ")", "try", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "self", "[", "key", "]", "=", "default", "return", "default", "finally", ":", "self", ".", "_wlock", ".", "release", "(", ")" ]
Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key.
[ "Set", "default", "if", "the", "key", "is", "not", "in", "the", "cache", "otherwise", "leave", "unchanged", ".", "Return", "the", "value", "of", "this", "key", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L355-L367
24,825
pypa/pipenv
pipenv/vendor/jinja2/utils.py
LRUCache.items
def items(self): """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
python
def items(self): """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
[ "def", "items", "(", "self", ")", ":", "result", "=", "[", "(", "key", ",", "self", ".", "_mapping", "[", "key", "]", ")", "for", "key", "in", "list", "(", "self", ".", "_queue", ")", "]", "result", ".", "reverse", "(", ")", "return", "result" ]
Return a list of items.
[ "Return", "a", "list", "of", "items", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L444-L448
24,826
pypa/pipenv
tasks/vendoring/__init__.py
license_fallback
def license_fallback(vendor_dir, sdist_name): """Hardcoded license URLs. Check when updating if those are still needed""" libname = libname_from_dir(sdist_name) if libname not in HARDCODED_LICENSE_URLS: raise ValueError('No hardcoded URL for {} license'.format(libname)) url = HARDCODED_LICENSE_URLS[libname] _, _, name = url.rpartition('/') dest = license_destination(vendor_dir, libname, name) r = requests.get(url, allow_redirects=True) log('Downloading {}'.format(url)) r.raise_for_status() dest.write_bytes(r.content)
python
def license_fallback(vendor_dir, sdist_name): """Hardcoded license URLs. Check when updating if those are still needed""" libname = libname_from_dir(sdist_name) if libname not in HARDCODED_LICENSE_URLS: raise ValueError('No hardcoded URL for {} license'.format(libname)) url = HARDCODED_LICENSE_URLS[libname] _, _, name = url.rpartition('/') dest = license_destination(vendor_dir, libname, name) r = requests.get(url, allow_redirects=True) log('Downloading {}'.format(url)) r.raise_for_status() dest.write_bytes(r.content)
[ "def", "license_fallback", "(", "vendor_dir", ",", "sdist_name", ")", ":", "libname", "=", "libname_from_dir", "(", "sdist_name", ")", "if", "libname", "not", "in", "HARDCODED_LICENSE_URLS", ":", "raise", "ValueError", "(", "'No hardcoded URL for {} license'", ".", "format", "(", "libname", ")", ")", "url", "=", "HARDCODED_LICENSE_URLS", "[", "libname", "]", "_", ",", "_", ",", "name", "=", "url", ".", "rpartition", "(", "'/'", ")", "dest", "=", "license_destination", "(", "vendor_dir", ",", "libname", ",", "name", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "allow_redirects", "=", "True", ")", "log", "(", "'Downloading {}'", ".", "format", "(", "url", ")", ")", "r", ".", "raise_for_status", "(", ")", "dest", ".", "write_bytes", "(", "r", ".", "content", ")" ]
Hardcoded license URLs. Check when updating if those are still needed
[ "Hardcoded", "license", "URLs", ".", "Check", "when", "updating", "if", "those", "are", "still", "needed" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/tasks/vendoring/__init__.py#L588-L600
24,827
pypa/pipenv
tasks/vendoring/__init__.py
libname_from_dir
def libname_from_dir(dirname): """Reconstruct the library name without it's version""" parts = [] for part in dirname.split('-'): if part[0].isdigit(): break parts.append(part) return '-'.join(parts)
python
def libname_from_dir(dirname): """Reconstruct the library name without it's version""" parts = [] for part in dirname.split('-'): if part[0].isdigit(): break parts.append(part) return '-'.join(parts)
[ "def", "libname_from_dir", "(", "dirname", ")", ":", "parts", "=", "[", "]", "for", "part", "in", "dirname", ".", "split", "(", "'-'", ")", ":", "if", "part", "[", "0", "]", ".", "isdigit", "(", ")", ":", "break", "parts", ".", "append", "(", "part", ")", "return", "'-'", ".", "join", "(", "parts", ")" ]
Reconstruct the library name without it's version
[ "Reconstruct", "the", "library", "name", "without", "it", "s", "version" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/tasks/vendoring/__init__.py#L603-L610
24,828
pypa/pipenv
pipenv/vendor/passa/internals/_pip.py
_convert_hashes
def _convert_hashes(values): """Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm. """ hashes = {} if not values: return hashes for value in values: try: name, value = value.split(":", 1) except ValueError: name = "sha256" if name not in hashes: hashes[name] = [] hashes[name].append(value) return hashes
python
def _convert_hashes(values): """Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm. """ hashes = {} if not values: return hashes for value in values: try: name, value = value.split(":", 1) except ValueError: name = "sha256" if name not in hashes: hashes[name] = [] hashes[name].append(value) return hashes
[ "def", "_convert_hashes", "(", "values", ")", ":", "hashes", "=", "{", "}", "if", "not", "values", ":", "return", "hashes", "for", "value", "in", "values", ":", "try", ":", "name", ",", "value", "=", "value", ".", "split", "(", "\":\"", ",", "1", ")", "except", "ValueError", ":", "name", "=", "\"sha256\"", "if", "name", "not", "in", "hashes", ":", "hashes", "[", "name", "]", "=", "[", "]", "hashes", "[", "name", "]", ".", "append", "(", "value", ")", "return", "hashes" ]
Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm.
[ "Convert", "Pipfile", ".", "lock", "hash", "lines", "into", "InstallRequirement", "option", "format", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L113-L130
24,829
pypa/pipenv
pipenv/vendor/passa/internals/_pip.py
_suppress_distutils_logs
def _suppress_distutils_logs(): """Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392. """ f = distutils.log.Log._log def _log(log, level, msg, args): if level >= distutils.log.ERROR: f(log, level, msg, args) distutils.log.Log._log = _log yield distutils.log.Log._log = f
python
def _suppress_distutils_logs(): """Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392. """ f = distutils.log.Log._log def _log(log, level, msg, args): if level >= distutils.log.ERROR: f(log, level, msg, args) distutils.log.Log._log = _log yield distutils.log.Log._log = f
[ "def", "_suppress_distutils_logs", "(", ")", ":", "f", "=", "distutils", ".", "log", ".", "Log", ".", "_log", "def", "_log", "(", "log", ",", "level", ",", "msg", ",", "args", ")", ":", "if", "level", ">=", "distutils", ".", "log", ".", "ERROR", ":", "f", "(", "log", ",", "level", ",", "msg", ",", "args", ")", "distutils", ".", "log", ".", "Log", ".", "_log", "=", "_log", "yield", "distutils", ".", "log", ".", "Log", ".", "_log", "=", "f" ]
Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392.
[ "Hack", "to", "hide", "noise", "generated", "by", "setup", ".", "py", "develop", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L258-L272
24,830
pypa/pipenv
pipenv/vendor/passa/internals/_pip.py
_find_egg_info
def _find_egg_info(ireq): """Find this package's .egg-info directory. Due to how sdists are designed, the .egg-info directory cannot be reliably found without running setup.py to aggregate all configurations. This function instead uses some heuristics to locate the egg-info directory that most likely represents this package. The best .egg-info directory's path is returned as a string. None is returned if no matches can be found. """ root = ireq.setup_py_dir directory_iterator = _iter_egg_info_directories(root, ireq.name) try: top_egg_info = next(directory_iterator) except StopIteration: # No egg-info found. Wat. return None directory_iterator = itertools.chain([top_egg_info], directory_iterator) # Read the sdist's PKG-INFO to determine which egg_info is best. pkg_info = _read_pkg_info(root) # PKG-INFO not readable. Just return whatever comes first, I guess. if pkg_info is None: return top_egg_info # Walk the sdist to find the egg-info with matching PKG-INFO. for directory in directory_iterator: egg_pkg_info = _read_pkg_info(directory) if egg_pkg_info == pkg_info: return directory # Nothing matches...? Use the first one we found, I guess. return top_egg_info
python
def _find_egg_info(ireq): """Find this package's .egg-info directory. Due to how sdists are designed, the .egg-info directory cannot be reliably found without running setup.py to aggregate all configurations. This function instead uses some heuristics to locate the egg-info directory that most likely represents this package. The best .egg-info directory's path is returned as a string. None is returned if no matches can be found. """ root = ireq.setup_py_dir directory_iterator = _iter_egg_info_directories(root, ireq.name) try: top_egg_info = next(directory_iterator) except StopIteration: # No egg-info found. Wat. return None directory_iterator = itertools.chain([top_egg_info], directory_iterator) # Read the sdist's PKG-INFO to determine which egg_info is best. pkg_info = _read_pkg_info(root) # PKG-INFO not readable. Just return whatever comes first, I guess. if pkg_info is None: return top_egg_info # Walk the sdist to find the egg-info with matching PKG-INFO. for directory in directory_iterator: egg_pkg_info = _read_pkg_info(directory) if egg_pkg_info == pkg_info: return directory # Nothing matches...? Use the first one we found, I guess. return top_egg_info
[ "def", "_find_egg_info", "(", "ireq", ")", ":", "root", "=", "ireq", ".", "setup_py_dir", "directory_iterator", "=", "_iter_egg_info_directories", "(", "root", ",", "ireq", ".", "name", ")", "try", ":", "top_egg_info", "=", "next", "(", "directory_iterator", ")", "except", "StopIteration", ":", "# No egg-info found. Wat.", "return", "None", "directory_iterator", "=", "itertools", ".", "chain", "(", "[", "top_egg_info", "]", ",", "directory_iterator", ")", "# Read the sdist's PKG-INFO to determine which egg_info is best.", "pkg_info", "=", "_read_pkg_info", "(", "root", ")", "# PKG-INFO not readable. Just return whatever comes first, I guess.", "if", "pkg_info", "is", "None", ":", "return", "top_egg_info", "# Walk the sdist to find the egg-info with matching PKG-INFO.", "for", "directory", "in", "directory_iterator", ":", "egg_pkg_info", "=", "_read_pkg_info", "(", "directory", ")", "if", "egg_pkg_info", "==", "pkg_info", ":", "return", "directory", "# Nothing matches...? Use the first one we found, I guess.", "return", "top_egg_info" ]
Find this package's .egg-info directory. Due to how sdists are designed, the .egg-info directory cannot be reliably found without running setup.py to aggregate all configurations. This function instead uses some heuristics to locate the egg-info directory that most likely represents this package. The best .egg-info directory's path is returned as a string. None is returned if no matches can be found.
[ "Find", "this", "package", "s", ".", "egg", "-", "info", "directory", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip.py#L355-L389
24,831
pypa/pipenv
pipenv/vendor/vistir/compat.py
fs_str
def fs_str(string): """Encodes a string into the proper filesystem encoding Borrowed from pip-tools """ if isinstance(string, str): return string assert not isinstance(string, bytes) return string.encode(_fs_encoding)
python
def fs_str(string): """Encodes a string into the proper filesystem encoding Borrowed from pip-tools """ if isinstance(string, str): return string assert not isinstance(string, bytes) return string.encode(_fs_encoding)
[ "def", "fs_str", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "return", "string", "assert", "not", "isinstance", "(", "string", ",", "bytes", ")", "return", "string", ".", "encode", "(", "_fs_encoding", ")" ]
Encodes a string into the proper filesystem encoding Borrowed from pip-tools
[ "Encodes", "a", "string", "into", "the", "proper", "filesystem", "encoding" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L208-L217
24,832
pypa/pipenv
pipenv/vendor/vistir/compat.py
_get_path
def _get_path(path): """ Fetch the string value from a path-like object Returns **None** if there is no string value. """ if isinstance(path, (six.string_types, bytes)): return path path_type = type(path) try: path_repr = path_type.__fspath__(path) except AttributeError: return if isinstance(path_repr, (six.string_types, bytes)): return path_repr return
python
def _get_path(path): """ Fetch the string value from a path-like object Returns **None** if there is no string value. """ if isinstance(path, (six.string_types, bytes)): return path path_type = type(path) try: path_repr = path_type.__fspath__(path) except AttributeError: return if isinstance(path_repr, (six.string_types, bytes)): return path_repr return
[ "def", "_get_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "(", "six", ".", "string_types", ",", "bytes", ")", ")", ":", "return", "path", "path_type", "=", "type", "(", "path", ")", "try", ":", "path_repr", "=", "path_type", ".", "__fspath__", "(", "path", ")", "except", "AttributeError", ":", "return", "if", "isinstance", "(", "path_repr", ",", "(", "six", ".", "string_types", ",", "bytes", ")", ")", ":", "return", "path_repr", "return" ]
Fetch the string value from a path-like object Returns **None** if there is no string value.
[ "Fetch", "the", "string", "value", "from", "a", "path", "-", "like", "object" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/compat.py#L220-L236
24,833
pypa/pipenv
pipenv/vendor/passa/internals/traces.py
trace_graph
def trace_graph(graph): """Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { None: [], "A": [None], "B": [None], "C": [[None, "A"], [None, "B"]], "D": [[None, "B", "C"], [None, "A"]], } """ result = {None: []} for vertex in graph: result[vertex] = [] for root in graph.iter_children(None): paths = [] _trace_visit_vertex(graph, root, vertex, {None}, [None], paths) result[vertex].extend(paths) return result
python
def trace_graph(graph): """Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { None: [], "A": [None], "B": [None], "C": [[None, "A"], [None, "B"]], "D": [[None, "B", "C"], [None, "A"]], } """ result = {None: []} for vertex in graph: result[vertex] = [] for root in graph.iter_children(None): paths = [] _trace_visit_vertex(graph, root, vertex, {None}, [None], paths) result[vertex].extend(paths) return result
[ "def", "trace_graph", "(", "graph", ")", ":", "result", "=", "{", "None", ":", "[", "]", "}", "for", "vertex", "in", "graph", ":", "result", "[", "vertex", "]", "=", "[", "]", "for", "root", "in", "graph", ".", "iter_children", "(", "None", ")", ":", "paths", "=", "[", "]", "_trace_visit_vertex", "(", "graph", ",", "root", ",", "vertex", ",", "{", "None", "}", ",", "[", "None", "]", ",", "paths", ")", "result", "[", "vertex", "]", ".", "extend", "(", "paths", ")", "return", "result" ]
Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { None: [], "A": [None], "B": [None], "C": [[None, "A"], [None, "B"]], "D": [[None, "B", "C"], [None, "A"]], }
[ "Build", "a", "collection", "of", "traces", "for", "each", "package", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/traces.py#L18-L40
24,834
pypa/pipenv
pipenv/vendor/urllib3/util/timeout.py
Timeout._validate_timeout
def _validate_timeout(cls, value, name): """ Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to zero, or the type is not an integer, float, or None. """ if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value if isinstance(value, bool): raise ValueError("Timeout cannot be a boolean value. It must " "be an int, float or None.") try: float(value) except (TypeError, ValueError): raise ValueError("Timeout value %s was %s, but it must be an " "int, float or None." % (name, value)) try: if value <= 0: raise ValueError("Attempted to set %s timeout to %s, but the " "timeout cannot be set to a value less " "than or equal to 0." % (name, value)) except TypeError: # Python 3 raise ValueError("Timeout value %s was %s, but it must be an " "int, float or None." % (name, value)) return value
python
def _validate_timeout(cls, value, name): """ Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to zero, or the type is not an integer, float, or None. """ if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value if isinstance(value, bool): raise ValueError("Timeout cannot be a boolean value. It must " "be an int, float or None.") try: float(value) except (TypeError, ValueError): raise ValueError("Timeout value %s was %s, but it must be an " "int, float or None." % (name, value)) try: if value <= 0: raise ValueError("Attempted to set %s timeout to %s, but the " "timeout cannot be set to a value less " "than or equal to 0." % (name, value)) except TypeError: # Python 3 raise ValueError("Timeout value %s was %s, but it must be an " "int, float or None." % (name, value)) return value
[ "def", "_validate_timeout", "(", "cls", ",", "value", ",", "name", ")", ":", "if", "value", "is", "_Default", ":", "return", "cls", ".", "DEFAULT_TIMEOUT", "if", "value", "is", "None", "or", "value", "is", "cls", ".", "DEFAULT_TIMEOUT", ":", "return", "value", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"Timeout cannot be a boolean value. It must \"", "\"be an int, float or None.\"", ")", "try", ":", "float", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Timeout value %s was %s, but it must be an \"", "\"int, float or None.\"", "%", "(", "name", ",", "value", ")", ")", "try", ":", "if", "value", "<=", "0", ":", "raise", "ValueError", "(", "\"Attempted to set %s timeout to %s, but the \"", "\"timeout cannot be set to a value less \"", "\"than or equal to 0.\"", "%", "(", "name", ",", "value", ")", ")", "except", "TypeError", ":", "# Python 3", "raise", "ValueError", "(", "\"Timeout value %s was %s, but it must be an \"", "\"int, float or None.\"", "%", "(", "name", ",", "value", ")", ")", "return", "value" ]
Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to zero, or the type is not an integer, float, or None.
[ "Check", "that", "a", "timeout", "attribute", "is", "valid", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L104-L138
24,835
pypa/pipenv
pipenv/vendor/urllib3/util/timeout.py
Timeout.clone
def clone(self): """ Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total)
python
def clone(self): """ Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total)
[ "def", "clone", "(", "self", ")", ":", "# We can't use copy.deepcopy because that will also create a new object", "# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to", "# detect the user default.", "return", "Timeout", "(", "connect", "=", "self", ".", "_connect", ",", "read", "=", "self", ".", "_read", ",", "total", "=", "self", ".", "total", ")" ]
Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout`
[ "Create", "a", "copy", "of", "the", "timeout", "object" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L156-L169
24,836
pypa/pipenv
pipenv/vendor/urllib3/util/timeout.py
Timeout.connect_timeout
def connect_timeout(self): """ Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total)
python
def connect_timeout(self): """ Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total)
[ "def", "connect_timeout", "(", "self", ")", ":", "if", "self", ".", "total", "is", "None", ":", "return", "self", ".", "_connect", "if", "self", ".", "_connect", "is", "None", "or", "self", ".", "_connect", "is", "self", ".", "DEFAULT_TIMEOUT", ":", "return", "self", ".", "total", "return", "min", "(", "self", ".", "_connect", ",", "self", ".", "total", ")" ]
Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
[ "Get", "the", "value", "to", "use", "when", "setting", "a", "connection", "timeout", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L196-L211
24,837
pypa/pipenv
pipenv/vendor/urllib3/util/timeout.py
Timeout.read_timeout
def read_timeout(self): """ Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if (self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read
python
def read_timeout(self): """ Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if (self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read
[ "def", "read_timeout", "(", "self", ")", ":", "if", "(", "self", ".", "total", "is", "not", "None", "and", "self", ".", "total", "is", "not", "self", ".", "DEFAULT_TIMEOUT", "and", "self", ".", "_read", "is", "not", "None", "and", "self", ".", "_read", "is", "not", "self", ".", "DEFAULT_TIMEOUT", ")", ":", "# In case the connect timeout has not yet been established.", "if", "self", ".", "_start_connect", "is", "None", ":", "return", "self", ".", "_read", "return", "max", "(", "0", ",", "min", "(", "self", ".", "total", "-", "self", ".", "get_connect_duration", "(", ")", ",", "self", ".", "_read", ")", ")", "elif", "self", ".", "total", "is", "not", "None", "and", "self", ".", "total", "is", "not", "self", ".", "DEFAULT_TIMEOUT", ":", "return", "max", "(", "0", ",", "self", ".", "total", "-", "self", ".", "get_connect_duration", "(", ")", ")", "else", ":", "return", "self", ".", "_read" ]
Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object.
[ "Get", "the", "value", "for", "the", "read", "timeout", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/timeout.py#L214-L242
24,838
pypa/pipenv
pipenv/vendor/urllib3/contrib/socks.py
SOCKSConnection._new_conn
def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=self.timeout, **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout) ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
python
def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=self.timeout, **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout) ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
[ "def", "_new_conn", "(", "self", ")", ":", "extra_kw", "=", "{", "}", "if", "self", ".", "source_address", ":", "extra_kw", "[", "'source_address'", "]", "=", "self", ".", "source_address", "if", "self", ".", "socket_options", ":", "extra_kw", "[", "'socket_options'", "]", "=", "self", ".", "socket_options", "try", ":", "conn", "=", "socks", ".", "create_connection", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "proxy_type", "=", "self", ".", "_socks_options", "[", "'socks_version'", "]", ",", "proxy_addr", "=", "self", ".", "_socks_options", "[", "'proxy_host'", "]", ",", "proxy_port", "=", "self", ".", "_socks_options", "[", "'proxy_port'", "]", ",", "proxy_username", "=", "self", ".", "_socks_options", "[", "'username'", "]", ",", "proxy_password", "=", "self", ".", "_socks_options", "[", "'password'", "]", ",", "proxy_rdns", "=", "self", ".", "_socks_options", "[", "'rdns'", "]", ",", "timeout", "=", "self", ".", "timeout", ",", "*", "*", "extra_kw", ")", "except", "SocketTimeout", "as", "e", ":", "raise", "ConnectTimeoutError", "(", "self", ",", "\"Connection to %s timed out. (connect timeout=%s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "timeout", ")", ")", "except", "socks", ".", "ProxyError", "as", "e", ":", "# This is fragile as hell, but it seems to be the only way to raise", "# useful errors here.", "if", "e", ".", "socket_err", ":", "error", "=", "e", ".", "socket_err", "if", "isinstance", "(", "error", ",", "SocketTimeout", ")", ":", "raise", "ConnectTimeoutError", "(", "self", ",", "\"Connection to %s timed out. (connect timeout=%s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "timeout", ")", ")", "else", ":", "raise", "NewConnectionError", "(", "self", ",", "\"Failed to establish a new connection: %s\"", "%", "error", ")", "else", ":", "raise", "NewConnectionError", "(", "self", ",", "\"Failed to establish a new connection: %s\"", "%", "e", ")", "except", "SocketError", "as", "e", ":", "# Defensive: PySocks should catch all these.", "raise", "NewConnectionError", "(", "self", ",", "\"Failed to establish a new connection: %s\"", "%", "e", ")", "return", "conn" ]
Establish a new connection via the SOCKS proxy.
[ "Establish", "a", "new", "connection", "via", "the", "SOCKS", "proxy", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/socks.py#L67-L122
24,839
pypa/pipenv
pipenv/vendor/click/core.py
fast_exit
def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code)
python
def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code)
[ "def", "fast_exit", "(", "code", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "os", ".", "_exit", "(", "code", ")" ]
Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion.
[ "Exit", "without", "garbage", "collection", "this", "speeds", "up", "exit", "by", "about", "10ms", "for", "things", "like", "bash", "completion", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L39-L45
24,840
pypa/pipenv
pipenv/vendor/click/core.py
augment_usage_errors
def augment_usage_errors(ctx, param=None): """Context manager that attaches extra information to exceptions that fly. """ try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx if param is not None and e.param is None: e.param = param raise except UsageError as e: if e.ctx is None: e.ctx = ctx raise
python
def augment_usage_errors(ctx, param=None): """Context manager that attaches extra information to exceptions that fly. """ try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx if param is not None and e.param is None: e.param = param raise except UsageError as e: if e.ctx is None: e.ctx = ctx raise
[ "def", "augment_usage_errors", "(", "ctx", ",", "param", "=", "None", ")", ":", "try", ":", "yield", "except", "BadParameter", "as", "e", ":", "if", "e", ".", "ctx", "is", "None", ":", "e", ".", "ctx", "=", "ctx", "if", "param", "is", "not", "None", "and", "e", ".", "param", "is", "None", ":", "e", ".", "param", "=", "param", "raise", "except", "UsageError", "as", "e", ":", "if", "e", ".", "ctx", "is", "None", ":", "e", ".", "ctx", "=", "ctx", "raise" ]
Context manager that attaches extra information to exceptions that fly.
[ "Context", "manager", "that", "attaches", "extra", "information", "to", "exceptions", "that", "fly", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L100-L115
24,841
pypa/pipenv
pipenv/vendor/click/core.py
iter_params_for_processing
def iter_params_for_processing(invocation_order, declaration_order): """Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. """ def sort_key(item): try: idx = invocation_order.index(item) except ValueError: idx = float('inf') return (not item.is_eager, idx) return sorted(declaration_order, key=sort_key)
python
def iter_params_for_processing(invocation_order, declaration_order): """Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed. """ def sort_key(item): try: idx = invocation_order.index(item) except ValueError: idx = float('inf') return (not item.is_eager, idx) return sorted(declaration_order, key=sort_key)
[ "def", "iter_params_for_processing", "(", "invocation_order", ",", "declaration_order", ")", ":", "def", "sort_key", "(", "item", ")", ":", "try", ":", "idx", "=", "invocation_order", ".", "index", "(", "item", ")", "except", "ValueError", ":", "idx", "=", "float", "(", "'inf'", ")", "return", "(", "not", "item", ".", "is_eager", ",", "idx", ")", "return", "sorted", "(", "declaration_order", ",", "key", "=", "sort_key", ")" ]
Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed.
[ "Given", "a", "sequence", "of", "parameters", "in", "the", "order", "as", "should", "be", "considered", "for", "processing", "and", "an", "iterable", "of", "parameters", "that", "exist", "this", "returns", "a", "list", "in", "the", "correct", "order", "as", "they", "should", "be", "processed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L118-L130
24,842
pypa/pipenv
pipenv/vendor/click/core.py
Context.command_path
def command_path(self): """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = '' if self.info_name is not None: rv = self.info_name if self.parent is not None: rv = self.parent.command_path + ' ' + rv return rv.lstrip()
python
def command_path(self): """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = '' if self.info_name is not None: rv = self.info_name if self.parent is not None: rv = self.parent.command_path + ' ' + rv return rv.lstrip()
[ "def", "command_path", "(", "self", ")", ":", "rv", "=", "''", "if", "self", ".", "info_name", "is", "not", "None", ":", "rv", "=", "self", ".", "info_name", "if", "self", ".", "parent", "is", "not", "None", ":", "rv", "=", "self", ".", "parent", ".", "command_path", "+", "' '", "+", "rv", "return", "rv", ".", "lstrip", "(", ")" ]
The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root.
[ "The", "computed", "command", "path", ".", "This", "is", "used", "for", "the", "usage", "information", "on", "the", "help", "page", ".", "It", "s", "automatically", "created", "by", "combining", "the", "info", "names", "of", "the", "chain", "of", "contexts", "to", "the", "root", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L444-L454
24,843
pypa/pipenv
pipenv/vendor/click/core.py
Context.find_root
def find_root(self): """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node
python
def find_root(self): """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node
[ "def", "find_root", "(", "self", ")", ":", "node", "=", "self", "while", "node", ".", "parent", "is", "not", "None", ":", "node", "=", "node", ".", "parent", "return", "node" ]
Finds the outermost context.
[ "Finds", "the", "outermost", "context", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L456-L461
24,844
pypa/pipenv
pipenv/vendor/click/core.py
Context.find_object
def find_object(self, object_type): """Finds the closest object of a given type.""" node = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent
python
def find_object(self, object_type): """Finds the closest object of a given type.""" node = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent
[ "def", "find_object", "(", "self", ",", "object_type", ")", ":", "node", "=", "self", "while", "node", "is", "not", "None", ":", "if", "isinstance", "(", "node", ".", "obj", ",", "object_type", ")", ":", "return", "node", ".", "obj", "node", "=", "node", ".", "parent" ]
Finds the closest object of a given type.
[ "Finds", "the", "closest", "object", "of", "a", "given", "type", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L463-L469
24,845
pypa/pipenv
pipenv/vendor/click/core.py
Command.format_usage
def format_usage(self, ctx, formatter): """Writes the usage line into the formatter.""" pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces))
python
def format_usage(self, ctx, formatter): """Writes the usage line into the formatter.""" pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces))
[ "def", "format_usage", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "pieces", "=", "self", ".", "collect_usage_pieces", "(", "ctx", ")", "formatter", ".", "write_usage", "(", "ctx", ".", "command_path", ",", "' '", ".", "join", "(", "pieces", ")", ")" ]
Writes the usage line into the formatter.
[ "Writes", "the", "usage", "line", "into", "the", "formatter", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L830-L833
24,846
pypa/pipenv
pipenv/vendor/click/core.py
Command.collect_usage_pieces
def collect_usage_pieces(self, ctx): """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv
python
def collect_usage_pieces(self, ctx): """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv
[ "def", "collect_usage_pieces", "(", "self", ",", "ctx", ")", ":", "rv", "=", "[", "self", ".", "options_metavar", "]", "for", "param", "in", "self", ".", "get_params", "(", "ctx", ")", ":", "rv", ".", "extend", "(", "param", ".", "get_usage_pieces", "(", "ctx", ")", ")", "return", "rv" ]
Returns all the pieces that go into the usage line and returns it as a list of strings.
[ "Returns", "all", "the", "pieces", "that", "go", "into", "the", "usage", "line", "and", "returns", "it", "as", "a", "list", "of", "strings", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L835-L842
24,847
pypa/pipenv
pipenv/vendor/click/core.py
Command.get_help_option_names
def get_help_option_names(self, ctx): """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return all_names
python
def get_help_option_names(self, ctx): """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return all_names
[ "def", "get_help_option_names", "(", "self", ",", "ctx", ")", ":", "all_names", "=", "set", "(", "ctx", ".", "help_option_names", ")", "for", "param", "in", "self", ".", "params", ":", "all_names", ".", "difference_update", "(", "param", ".", "opts", ")", "all_names", ".", "difference_update", "(", "param", ".", "secondary_opts", ")", "return", "all_names" ]
Returns the names for the help option.
[ "Returns", "the", "names", "for", "the", "help", "option", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L844-L850
24,848
pypa/pipenv
pipenv/vendor/click/core.py
Command.get_short_help_str
def get_short_help_str(self, limit=45): """Gets short help for the command or makes it by shortening the long help string.""" return self.short_help or self.help and make_default_short_help(self.help, limit) or ''
python
def get_short_help_str(self, limit=45): """Gets short help for the command or makes it by shortening the long help string.""" return self.short_help or self.help and make_default_short_help(self.help, limit) or ''
[ "def", "get_short_help_str", "(", "self", ",", "limit", "=", "45", ")", ":", "return", "self", ".", "short_help", "or", "self", ".", "help", "and", "make_default_short_help", "(", "self", ".", "help", ",", "limit", ")", "or", "''" ]
Gets short help for the command or makes it by shortening the long help string.
[ "Gets", "short", "help", "for", "the", "command", "or", "makes", "it", "by", "shortening", "the", "long", "help", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L882-L884
24,849
pypa/pipenv
pipenv/vendor/click/core.py
Command.format_help
def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter)
python
def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter)
[ "def", "format_help", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "self", ".", "format_usage", "(", "ctx", ",", "formatter", ")", "self", ".", "format_help_text", "(", "ctx", ",", "formatter", ")", "self", ".", "format_options", "(", "ctx", ",", "formatter", ")", "self", ".", "format_epilog", "(", "ctx", ",", "formatter", ")" ]
Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog`
[ "Writes", "the", "help", "into", "the", "formatter", "if", "it", "exists", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L886-L899
24,850
pypa/pipenv
pipenv/vendor/click/core.py
Command.format_options
def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section('Options'): formatter.write_dl(opts)
python
def format_options(self, ctx, formatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section('Options'): formatter.write_dl(opts)
[ "def", "format_options", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "opts", "=", "[", "]", "for", "param", "in", "self", ".", "get_params", "(", "ctx", ")", ":", "rv", "=", "param", ".", "get_help_record", "(", "ctx", ")", "if", "rv", "is", "not", "None", ":", "opts", ".", "append", "(", "rv", ")", "if", "opts", ":", "with", "formatter", ".", "section", "(", "'Options'", ")", ":", "formatter", ".", "write_dl", "(", "opts", ")" ]
Writes all the options into the formatter if they exist.
[ "Writes", "all", "the", "options", "into", "the", "formatter", "if", "they", "exist", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L915-L925
24,851
pypa/pipenv
pipenv/vendor/click/core.py
Command.format_epilog
def format_epilog(self, ctx, formatter): """Writes the epilog into the formatter if it exists.""" if self.epilog: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.epilog)
python
def format_epilog(self, ctx, formatter): """Writes the epilog into the formatter if it exists.""" if self.epilog: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.epilog)
[ "def", "format_epilog", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "if", "self", ".", "epilog", ":", "formatter", ".", "write_paragraph", "(", ")", "with", "formatter", ".", "indentation", "(", ")", ":", "formatter", ".", "write_text", "(", "self", ".", "epilog", ")" ]
Writes the epilog into the formatter if it exists.
[ "Writes", "the", "epilog", "into", "the", "formatter", "if", "it", "exists", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L927-L932
24,852
pypa/pipenv
pipenv/vendor/click/core.py
Parameter.get_default
def get_default(self, ctx): """Given a context variable this calculates the default value.""" # Otherwise go with the regular default. if callable(self.default): rv = self.default() else: rv = self.default return self.type_cast_value(ctx, rv)
python
def get_default(self, ctx): """Given a context variable this calculates the default value.""" # Otherwise go with the regular default. if callable(self.default): rv = self.default() else: rv = self.default return self.type_cast_value(ctx, rv)
[ "def", "get_default", "(", "self", ",", "ctx", ")", ":", "# Otherwise go with the regular default.", "if", "callable", "(", "self", ".", "default", ")", ":", "rv", "=", "self", ".", "default", "(", ")", "else", ":", "rv", "=", "self", ".", "default", "return", "self", ".", "type_cast_value", "(", "ctx", ",", "rv", ")" ]
Given a context variable this calculates the default value.
[ "Given", "a", "context", "variable", "this", "calculates", "the", "default", "value", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L1378-L1385
24,853
pypa/pipenv
pipenv/vendor/click/core.py
Parameter.type_cast_value
def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ if self.type.is_composite: if self.nargs <= 1: raise TypeError('Attempted to invoke composite type ' 'but nargs has been set to %s. This is ' 'not supported; nargs needs to be set to ' 'a fixed value > 1.' % self.nargs) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) return self.type(value or (), self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) return tuple(_convert(x, level - 1) for x in value or ()) return _convert(value, (self.nargs != 1) + bool(self.multiple))
python
def type_cast_value(self, ctx, value): """Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types. """ if self.type.is_composite: if self.nargs <= 1: raise TypeError('Attempted to invoke composite type ' 'but nargs has been set to %s. This is ' 'not supported; nargs needs to be set to ' 'a fixed value > 1.' % self.nargs) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) return self.type(value or (), self, ctx) def _convert(value, level): if level == 0: return self.type(value, self, ctx) return tuple(_convert(x, level - 1) for x in value or ()) return _convert(value, (self.nargs != 1) + bool(self.multiple))
[ "def", "type_cast_value", "(", "self", ",", "ctx", ",", "value", ")", ":", "if", "self", ".", "type", ".", "is_composite", ":", "if", "self", ".", "nargs", "<=", "1", ":", "raise", "TypeError", "(", "'Attempted to invoke composite type '", "'but nargs has been set to %s. This is '", "'not supported; nargs needs to be set to '", "'a fixed value > 1.'", "%", "self", ".", "nargs", ")", "if", "self", ".", "multiple", ":", "return", "tuple", "(", "self", ".", "type", "(", "x", "or", "(", ")", ",", "self", ",", "ctx", ")", "for", "x", "in", "value", "or", "(", ")", ")", "return", "self", ".", "type", "(", "value", "or", "(", ")", ",", "self", ",", "ctx", ")", "def", "_convert", "(", "value", ",", "level", ")", ":", "if", "level", "==", "0", ":", "return", "self", ".", "type", "(", "value", ",", "self", ",", "ctx", ")", "return", "tuple", "(", "_convert", "(", "x", ",", "level", "-", "1", ")", "for", "x", "in", "value", "or", "(", ")", ")", "return", "_convert", "(", "value", ",", "(", "self", ".", "nargs", "!=", "1", ")", "+", "bool", "(", "self", ".", "multiple", ")", ")" ]
Given a value this runs it properly through the type system. This automatically handles things like `nargs` and `multiple` as well as composite types.
[ "Given", "a", "value", "this", "runs", "it", "properly", "through", "the", "type", "system", ".", "This", "automatically", "handles", "things", "like", "nargs", "and", "multiple", "as", "well", "as", "composite", "types", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L1398-L1417
24,854
pypa/pipenv
pipenv/vendor/click/core.py
Parameter.get_error_hint
def get_error_hint(self, ctx): """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return ' / '.join('"%s"' % x for x in hint_list)
python
def get_error_hint(self, ctx): """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return ' / '.join('"%s"' % x for x in hint_list)
[ "def", "get_error_hint", "(", "self", ",", "ctx", ")", ":", "hint_list", "=", "self", ".", "opts", "or", "[", "self", ".", "human_readable_name", "]", "return", "' / '", ".", "join", "(", "'\"%s\"'", "%", "x", "for", "x", "in", "hint_list", ")" ]
Get a stringified version of the param for use in error messages to indicate which param caused the error.
[ "Get", "a", "stringified", "version", "of", "the", "param", "for", "use", "in", "error", "messages", "to", "indicate", "which", "param", "caused", "the", "error", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L1492-L1497
24,855
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
find_all_matches
def find_all_matches(finder, ireq, pre=False): # type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate] """Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A list of matching candidates. :rtype: list[:class:`~pip._internal.index.InstallationCandidate`] """ candidates = clean_requires_python(finder.find_all_candidates(ireq.name)) versions = {candidate.version for candidate in candidates} allowed_versions = _get_filtered_versions(ireq, versions, pre) if not pre and not allowed_versions: allowed_versions = _get_filtered_versions(ireq, versions, True) candidates = {c for c in candidates if c.version in allowed_versions} return candidates
python
def find_all_matches(finder, ireq, pre=False): # type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate] """Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A list of matching candidates. :rtype: list[:class:`~pip._internal.index.InstallationCandidate`] """ candidates = clean_requires_python(finder.find_all_candidates(ireq.name)) versions = {candidate.version for candidate in candidates} allowed_versions = _get_filtered_versions(ireq, versions, pre) if not pre and not allowed_versions: allowed_versions = _get_filtered_versions(ireq, versions, True) candidates = {c for c in candidates if c.version in allowed_versions} return candidates
[ "def", "find_all_matches", "(", "finder", ",", "ireq", ",", "pre", "=", "False", ")", ":", "# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]", "candidates", "=", "clean_requires_python", "(", "finder", ".", "find_all_candidates", "(", "ireq", ".", "name", ")", ")", "versions", "=", "{", "candidate", ".", "version", "for", "candidate", "in", "candidates", "}", "allowed_versions", "=", "_get_filtered_versions", "(", "ireq", ",", "versions", ",", "pre", ")", "if", "not", "pre", "and", "not", "allowed_versions", ":", "allowed_versions", "=", "_get_filtered_versions", "(", "ireq", ",", "versions", ",", "True", ")", "candidates", "=", "{", "c", "for", "c", "in", "candidates", "if", "c", ".", "version", "in", "allowed_versions", "}", "return", "candidates" ]
Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A list of matching candidates. :rtype: list[:class:`~pip._internal.index.InstallationCandidate`]
[ "Find", "all", "matching", "dependencies", "using", "the", "supplied", "finder", "and", "the", "given", "ireq", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L57-L77
24,856
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_abstract_dependencies
def get_abstract_dependencies(reqs, sources=None, parent=None): """Get all abstract dependencies for a given list of requirements. Given a set of requirements, convert each requirement to an Abstract Dependency. :param reqs: A list of Requirements :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`] :param sources: Pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional :return: A list of Abstract Dependencies :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`] """ deps = [] from .requirements import Requirement for req in reqs: if isinstance(req, pip_shims.shims.InstallRequirement): requirement = Requirement.from_line( "{0}{1}".format(req.name, req.specifier) ) if req.link: requirement.req.link = req.link requirement.markers = req.markers requirement.req.markers = req.markers requirement.extras = req.extras requirement.req.extras = req.extras elif isinstance(req, Requirement): requirement = copy.deepcopy(req) else: requirement = Requirement.from_line(req) dep = AbstractDependency.from_requirement(requirement, parent=parent) deps.append(dep) return deps
python
def get_abstract_dependencies(reqs, sources=None, parent=None): """Get all abstract dependencies for a given list of requirements. Given a set of requirements, convert each requirement to an Abstract Dependency. :param reqs: A list of Requirements :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`] :param sources: Pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional :return: A list of Abstract Dependencies :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`] """ deps = [] from .requirements import Requirement for req in reqs: if isinstance(req, pip_shims.shims.InstallRequirement): requirement = Requirement.from_line( "{0}{1}".format(req.name, req.specifier) ) if req.link: requirement.req.link = req.link requirement.markers = req.markers requirement.req.markers = req.markers requirement.extras = req.extras requirement.req.extras = req.extras elif isinstance(req, Requirement): requirement = copy.deepcopy(req) else: requirement = Requirement.from_line(req) dep = AbstractDependency.from_requirement(requirement, parent=parent) deps.append(dep) return deps
[ "def", "get_abstract_dependencies", "(", "reqs", ",", "sources", "=", "None", ",", "parent", "=", "None", ")", ":", "deps", "=", "[", "]", "from", ".", "requirements", "import", "Requirement", "for", "req", "in", "reqs", ":", "if", "isinstance", "(", "req", ",", "pip_shims", ".", "shims", ".", "InstallRequirement", ")", ":", "requirement", "=", "Requirement", ".", "from_line", "(", "\"{0}{1}\"", ".", "format", "(", "req", ".", "name", ",", "req", ".", "specifier", ")", ")", "if", "req", ".", "link", ":", "requirement", ".", "req", ".", "link", "=", "req", ".", "link", "requirement", ".", "markers", "=", "req", ".", "markers", "requirement", ".", "req", ".", "markers", "=", "req", ".", "markers", "requirement", ".", "extras", "=", "req", ".", "extras", "requirement", ".", "req", ".", "extras", "=", "req", ".", "extras", "elif", "isinstance", "(", "req", ",", "Requirement", ")", ":", "requirement", "=", "copy", ".", "deepcopy", "(", "req", ")", "else", ":", "requirement", "=", "Requirement", ".", "from_line", "(", "req", ")", "dep", "=", "AbstractDependency", ".", "from_requirement", "(", "requirement", ",", "parent", "=", "parent", ")", "deps", ".", "append", "(", "dep", ")", "return", "deps" ]
Get all abstract dependencies for a given list of requirements. Given a set of requirements, convert each requirement to an Abstract Dependency. :param reqs: A list of Requirements :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`] :param sources: Pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param parent: The parent of this list of dependencies, defaults to None :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional :return: A list of Abstract Dependencies :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]
[ "Get", "all", "abstract", "dependencies", "for", "a", "given", "list", "of", "requirements", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L262-L297
24,857
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_dependencies_from_wheel_cache
def get_dependencies_from_wheel_cache(ireq): """Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return matches = WHEEL_CACHE.get(ireq.link, name_from_req(ireq.req)) if matches: matches = set(matches) if not DEPENDENCY_CACHE.get(ireq): DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches] return matches return
python
def get_dependencies_from_wheel_cache(ireq): """Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return matches = WHEEL_CACHE.get(ireq.link, name_from_req(ireq.req)) if matches: matches = set(matches) if not DEPENDENCY_CACHE.get(ireq): DEPENDENCY_CACHE[ireq] = [format_requirement(m) for m in matches] return matches return
[ "def", "get_dependencies_from_wheel_cache", "(", "ireq", ")", ":", "if", "ireq", ".", "editable", "or", "not", "is_pinned_requirement", "(", "ireq", ")", ":", "return", "matches", "=", "WHEEL_CACHE", ".", "get", "(", "ireq", ".", "link", ",", "name_from_req", "(", "ireq", ".", "req", ")", ")", "if", "matches", ":", "matches", "=", "set", "(", "matches", ")", "if", "not", "DEPENDENCY_CACHE", ".", "get", "(", "ireq", ")", ":", "DEPENDENCY_CACHE", "[", "ireq", "]", "=", "[", "format_requirement", "(", "m", ")", "for", "m", "in", "matches", "]", "return", "matches", "return" ]
Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None
[ "Retrieves", "dependencies", "for", "the", "given", "install", "requirement", "from", "the", "wheel", "cache", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L337-L354
24,858
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_dependencies_from_json
def get_dependencies_from_json(ireq): """Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return session = requests.session() atexit.register(session.close) version = str(ireq.req.specifier).lstrip("=") def gen(ireq): info = None try: info = session.get( "https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version) ).json()["info"] finally: session.close() requires_dist = info.get("requires_dist", info.get("requires")) if not requires_dist: # The API can return None for this. return for requires in requires_dist: i = pip_shims.shims.InstallRequirement.from_line(requires) # See above, we don't handle requirements with extras. if not _marker_contains_extra(i): yield format_requirement(i) if ireq not in DEPENDENCY_CACHE: try: reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq)) except JSONDecodeError: return req_iter = iter(reqs) else: req_iter = gen(ireq) return set(req_iter)
python
def get_dependencies_from_json(ireq): """Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return session = requests.session() atexit.register(session.close) version = str(ireq.req.specifier).lstrip("=") def gen(ireq): info = None try: info = session.get( "https://pypi.org/pypi/{0}/{1}/json".format(ireq.req.name, version) ).json()["info"] finally: session.close() requires_dist = info.get("requires_dist", info.get("requires")) if not requires_dist: # The API can return None for this. return for requires in requires_dist: i = pip_shims.shims.InstallRequirement.from_line(requires) # See above, we don't handle requirements with extras. if not _marker_contains_extra(i): yield format_requirement(i) if ireq not in DEPENDENCY_CACHE: try: reqs = DEPENDENCY_CACHE[ireq] = list(gen(ireq)) except JSONDecodeError: return req_iter = iter(reqs) else: req_iter = gen(ireq) return set(req_iter)
[ "def", "get_dependencies_from_json", "(", "ireq", ")", ":", "if", "ireq", ".", "editable", "or", "not", "is_pinned_requirement", "(", "ireq", ")", ":", "return", "# It is technically possible to parse extras out of the JSON API's", "# requirement format, but it is such a chore let's just use the simple API.", "if", "ireq", ".", "extras", ":", "return", "session", "=", "requests", ".", "session", "(", ")", "atexit", ".", "register", "(", "session", ".", "close", ")", "version", "=", "str", "(", "ireq", ".", "req", ".", "specifier", ")", ".", "lstrip", "(", "\"=\"", ")", "def", "gen", "(", "ireq", ")", ":", "info", "=", "None", "try", ":", "info", "=", "session", ".", "get", "(", "\"https://pypi.org/pypi/{0}/{1}/json\"", ".", "format", "(", "ireq", ".", "req", ".", "name", ",", "version", ")", ")", ".", "json", "(", ")", "[", "\"info\"", "]", "finally", ":", "session", ".", "close", "(", ")", "requires_dist", "=", "info", ".", "get", "(", "\"requires_dist\"", ",", "info", ".", "get", "(", "\"requires\"", ")", ")", "if", "not", "requires_dist", ":", "# The API can return None for this.", "return", "for", "requires", "in", "requires_dist", ":", "i", "=", "pip_shims", ".", "shims", ".", "InstallRequirement", ".", "from_line", "(", "requires", ")", "# See above, we don't handle requirements with extras.", "if", "not", "_marker_contains_extra", "(", "i", ")", ":", "yield", "format_requirement", "(", "i", ")", "if", "ireq", "not", "in", "DEPENDENCY_CACHE", ":", "try", ":", "reqs", "=", "DEPENDENCY_CACHE", "[", "ireq", "]", "=", "list", "(", "gen", "(", "ireq", ")", ")", "except", "JSONDecodeError", ":", "return", "req_iter", "=", "iter", "(", "reqs", ")", "else", ":", "req_iter", "=", "gen", "(", "ireq", ")", "return", "set", "(", "req_iter", ")" ]
Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None
[ "Retrieves", "dependencies", "for", "the", "given", "install", "requirement", "from", "the", "json", "api", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L362-L408
24,859
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_dependencies_from_cache
def get_dependencies_from_cache(ireq): """Retrieves dependencies for the given install requirement from the dependency cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return if ireq not in DEPENDENCY_CACHE: return cached = set(DEPENDENCY_CACHE[ireq]) # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: broken = False for line in cached: dep_ireq = pip_shims.shims.InstallRequirement.from_line(line) name = canonicalize_name(dep_ireq.name) if _marker_contains_extra(dep_ireq): broken = True # The "extra =" marker breaks everything. elif name == canonicalize_name(ireq.name): broken = True # A package cannot depend on itself. if broken: break except Exception: broken = True if broken: del DEPENDENCY_CACHE[ireq] return return cached
python
def get_dependencies_from_cache(ireq): """Retrieves dependencies for the given install requirement from the dependency cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if ireq.editable or not is_pinned_requirement(ireq): return if ireq not in DEPENDENCY_CACHE: return cached = set(DEPENDENCY_CACHE[ireq]) # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: broken = False for line in cached: dep_ireq = pip_shims.shims.InstallRequirement.from_line(line) name = canonicalize_name(dep_ireq.name) if _marker_contains_extra(dep_ireq): broken = True # The "extra =" marker breaks everything. elif name == canonicalize_name(ireq.name): broken = True # A package cannot depend on itself. if broken: break except Exception: broken = True if broken: del DEPENDENCY_CACHE[ireq] return return cached
[ "def", "get_dependencies_from_cache", "(", "ireq", ")", ":", "if", "ireq", ".", "editable", "or", "not", "is_pinned_requirement", "(", "ireq", ")", ":", "return", "if", "ireq", "not", "in", "DEPENDENCY_CACHE", ":", "return", "cached", "=", "set", "(", "DEPENDENCY_CACHE", "[", "ireq", "]", ")", "# Preserving sanity: Run through the cache and make sure every entry if", "# valid. If this fails, something is wrong with the cache. Drop it.", "try", ":", "broken", "=", "False", "for", "line", "in", "cached", ":", "dep_ireq", "=", "pip_shims", ".", "shims", ".", "InstallRequirement", ".", "from_line", "(", "line", ")", "name", "=", "canonicalize_name", "(", "dep_ireq", ".", "name", ")", "if", "_marker_contains_extra", "(", "dep_ireq", ")", ":", "broken", "=", "True", "# The \"extra =\" marker breaks everything.", "elif", "name", "==", "canonicalize_name", "(", "ireq", ".", "name", ")", ":", "broken", "=", "True", "# A package cannot depend on itself.", "if", "broken", ":", "break", "except", "Exception", ":", "broken", "=", "True", "if", "broken", ":", "del", "DEPENDENCY_CACHE", "[", "ireq", "]", "return", "return", "cached" ]
Retrieves dependencies for the given install requirement from the dependency cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None
[ "Retrieves", "dependencies", "for", "the", "given", "install", "requirement", "from", "the", "dependency", "cache", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L411-L445
24,860
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_dependencies_from_index
def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None): """Retrieves dependencies for the given install requirement from the pip resolver. :param dep: A single InstallRequirement :type dep: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ finder = get_finder(sources=sources, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE dep.is_direct = True reqset = pip_shims.shims.RequirementSet() reqset.add_requirement(dep) requirements = None setup_requires = {} with temp_environ(), start_resolver(finder=finder, wheel_cache=wheel_cache) as resolver: os.environ['PIP_EXISTS_ACTION'] = 'i' dist = None if dep.editable and not dep.prepared and not dep.req: with cd(dep.setup_py_dir): from setuptools.dist import distutils try: dist = distutils.core.run_setup(dep.setup_py) except (ImportError, TypeError, AttributeError): dist = None else: setup_requires[dist.get_name()] = dist.setup_requires if not dist: try: dist = dep.get_dist() except (TypeError, ValueError, AttributeError): pass else: setup_requires[dist.get_name()] = dist.setup_requires resolver.require_hashes = False try: results = resolver._resolve_one(reqset, dep) except Exception: # FIXME: Needs to bubble the exception somehow to the user. results = [] finally: try: wheel_cache.cleanup() except AttributeError: pass resolver_requires_python = getattr(resolver, "requires_python", None) requires_python = getattr(reqset, "requires_python", resolver_requires_python) if requires_python: add_marker = fix_requires_python_marker(requires_python) reqset.remove(dep) if dep.req.marker: dep.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: dep.req.marker = add_marker reqset.add(dep) requirements = set() for r in results: if requires_python: if r.req.marker: r.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: r.req.marker = add_marker requirements.add(format_requirement(r)) for section in setup_requires: python_version = section not_python = not is_python(section) # This is for cleaning up :extras: formatted markers # by adding them to the results of the resolver # since any such extra would have been returned as a result anyway for value in setup_requires[section]: # This is a marker. if is_python(section): python_version = value[1:-1] else: not_python = True if ':' not in value and not_python: try: requirement_str = "{0}{1}".format(value, python_version).replace(":", ";") requirements.add(format_requirement(make_install_requirement(requirement_str).ireq)) # Anything could go wrong here -- can't be too careful. except Exception: pass if not dep.editable and is_pinned_requirement(dep) and requirements is not None: DEPENDENCY_CACHE[dep] = list(requirements) return requirements
python
def get_dependencies_from_index(dep, sources=None, pip_options=None, wheel_cache=None): """Retrieves dependencies for the given install requirement from the pip resolver. :param dep: A single InstallRequirement :type dep: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ finder = get_finder(sources=sources, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE dep.is_direct = True reqset = pip_shims.shims.RequirementSet() reqset.add_requirement(dep) requirements = None setup_requires = {} with temp_environ(), start_resolver(finder=finder, wheel_cache=wheel_cache) as resolver: os.environ['PIP_EXISTS_ACTION'] = 'i' dist = None if dep.editable and not dep.prepared and not dep.req: with cd(dep.setup_py_dir): from setuptools.dist import distutils try: dist = distutils.core.run_setup(dep.setup_py) except (ImportError, TypeError, AttributeError): dist = None else: setup_requires[dist.get_name()] = dist.setup_requires if not dist: try: dist = dep.get_dist() except (TypeError, ValueError, AttributeError): pass else: setup_requires[dist.get_name()] = dist.setup_requires resolver.require_hashes = False try: results = resolver._resolve_one(reqset, dep) except Exception: # FIXME: Needs to bubble the exception somehow to the user. results = [] finally: try: wheel_cache.cleanup() except AttributeError: pass resolver_requires_python = getattr(resolver, "requires_python", None) requires_python = getattr(reqset, "requires_python", resolver_requires_python) if requires_python: add_marker = fix_requires_python_marker(requires_python) reqset.remove(dep) if dep.req.marker: dep.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: dep.req.marker = add_marker reqset.add(dep) requirements = set() for r in results: if requires_python: if r.req.marker: r.req.marker._markers.extend(['and',].extend(add_marker._markers)) else: r.req.marker = add_marker requirements.add(format_requirement(r)) for section in setup_requires: python_version = section not_python = not is_python(section) # This is for cleaning up :extras: formatted markers # by adding them to the results of the resolver # since any such extra would have been returned as a result anyway for value in setup_requires[section]: # This is a marker. if is_python(section): python_version = value[1:-1] else: not_python = True if ':' not in value and not_python: try: requirement_str = "{0}{1}".format(value, python_version).replace(":", ";") requirements.add(format_requirement(make_install_requirement(requirement_str).ireq)) # Anything could go wrong here -- can't be too careful. except Exception: pass if not dep.editable and is_pinned_requirement(dep) and requirements is not None: DEPENDENCY_CACHE[dep] = list(requirements) return requirements
[ "def", "get_dependencies_from_index", "(", "dep", ",", "sources", "=", "None", ",", "pip_options", "=", "None", ",", "wheel_cache", "=", "None", ")", ":", "finder", "=", "get_finder", "(", "sources", "=", "sources", ",", "pip_options", "=", "pip_options", ")", "if", "not", "wheel_cache", ":", "wheel_cache", "=", "WHEEL_CACHE", "dep", ".", "is_direct", "=", "True", "reqset", "=", "pip_shims", ".", "shims", ".", "RequirementSet", "(", ")", "reqset", ".", "add_requirement", "(", "dep", ")", "requirements", "=", "None", "setup_requires", "=", "{", "}", "with", "temp_environ", "(", ")", ",", "start_resolver", "(", "finder", "=", "finder", ",", "wheel_cache", "=", "wheel_cache", ")", "as", "resolver", ":", "os", ".", "environ", "[", "'PIP_EXISTS_ACTION'", "]", "=", "'i'", "dist", "=", "None", "if", "dep", ".", "editable", "and", "not", "dep", ".", "prepared", "and", "not", "dep", ".", "req", ":", "with", "cd", "(", "dep", ".", "setup_py_dir", ")", ":", "from", "setuptools", ".", "dist", "import", "distutils", "try", ":", "dist", "=", "distutils", ".", "core", ".", "run_setup", "(", "dep", ".", "setup_py", ")", "except", "(", "ImportError", ",", "TypeError", ",", "AttributeError", ")", ":", "dist", "=", "None", "else", ":", "setup_requires", "[", "dist", ".", "get_name", "(", ")", "]", "=", "dist", ".", "setup_requires", "if", "not", "dist", ":", "try", ":", "dist", "=", "dep", ".", "get_dist", "(", ")", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "pass", "else", ":", "setup_requires", "[", "dist", ".", "get_name", "(", ")", "]", "=", "dist", ".", "setup_requires", "resolver", ".", "require_hashes", "=", "False", "try", ":", "results", "=", "resolver", ".", "_resolve_one", "(", "reqset", ",", "dep", ")", "except", "Exception", ":", "# FIXME: Needs to bubble the exception somehow to the user.", "results", "=", "[", "]", "finally", ":", "try", ":", "wheel_cache", ".", "cleanup", "(", ")", "except", "AttributeError", ":", "pass", "resolver_requires_python", "=", "getattr", "(", "resolver", ",", "\"requires_python\"", ",", "None", ")", "requires_python", "=", "getattr", "(", "reqset", ",", "\"requires_python\"", ",", "resolver_requires_python", ")", "if", "requires_python", ":", "add_marker", "=", "fix_requires_python_marker", "(", "requires_python", ")", "reqset", ".", "remove", "(", "dep", ")", "if", "dep", ".", "req", ".", "marker", ":", "dep", ".", "req", ".", "marker", ".", "_markers", ".", "extend", "(", "[", "'and'", ",", "]", ".", "extend", "(", "add_marker", ".", "_markers", ")", ")", "else", ":", "dep", ".", "req", ".", "marker", "=", "add_marker", "reqset", ".", "add", "(", "dep", ")", "requirements", "=", "set", "(", ")", "for", "r", "in", "results", ":", "if", "requires_python", ":", "if", "r", ".", "req", ".", "marker", ":", "r", ".", "req", ".", "marker", ".", "_markers", ".", "extend", "(", "[", "'and'", ",", "]", ".", "extend", "(", "add_marker", ".", "_markers", ")", ")", "else", ":", "r", ".", "req", ".", "marker", "=", "add_marker", "requirements", ".", "add", "(", "format_requirement", "(", "r", ")", ")", "for", "section", "in", "setup_requires", ":", "python_version", "=", "section", "not_python", "=", "not", "is_python", "(", "section", ")", "# This is for cleaning up :extras: formatted markers", "# by adding them to the results of the resolver", "# since any such extra would have been returned as a result anyway", "for", "value", "in", "setup_requires", "[", "section", "]", ":", "# This is a marker.", "if", "is_python", "(", "section", ")", ":", "python_version", "=", "value", "[", "1", ":", "-", "1", "]", "else", ":", "not_python", "=", "True", "if", "':'", "not", "in", "value", "and", "not_python", ":", "try", ":", "requirement_str", "=", "\"{0}{1}\"", ".", "format", "(", "value", ",", "python_version", ")", ".", "replace", "(", "\":\"", ",", "\";\"", ")", "requirements", ".", "add", "(", "format_requirement", "(", "make_install_requirement", "(", "requirement_str", ")", ".", "ireq", ")", ")", "# Anything could go wrong here -- can't be too careful.", "except", "Exception", ":", "pass", "if", "not", "dep", ".", "editable", "and", "is_pinned_requirement", "(", "dep", ")", "and", "requirements", "is", "not", "None", ":", "DEPENDENCY_CACHE", "[", "dep", "]", "=", "list", "(", "requirements", ")", "return", "requirements" ]
Retrieves dependencies for the given install requirement from the pip resolver. :param dep: A single InstallRequirement :type dep: :class:`~pip._internal.req.req_install.InstallRequirement` :param sources: Pipfile-formatted sources, defaults to None :type sources: list[dict], optional :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None
[ "Retrieves", "dependencies", "for", "the", "given", "install", "requirement", "from", "the", "pip", "resolver", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L452-L544
24,861
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_pip_options
def get_pip_options(args=[], sources=None, pip_command=None): """Build a pip command from a list of sources :param args: positional arguments passed through to the pip parser :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pre-built pip command instance :type pip_command: :class:`~pip._internal.cli.base_command.Command` :return: An instance of pip_options using the supplied arguments plus sane defaults :rtype: :class:`~pip._internal.cli.cmdoptions` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] _ensure_dir(CACHE_DIR) pip_args = args pip_args = prepare_pip_source_args(sources, pip_args) pip_options, _ = pip_command.parser.parse_args(pip_args) pip_options.cache_dir = CACHE_DIR return pip_options
python
def get_pip_options(args=[], sources=None, pip_command=None): """Build a pip command from a list of sources :param args: positional arguments passed through to the pip parser :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pre-built pip command instance :type pip_command: :class:`~pip._internal.cli.base_command.Command` :return: An instance of pip_options using the supplied arguments plus sane defaults :rtype: :class:`~pip._internal.cli.cmdoptions` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] _ensure_dir(CACHE_DIR) pip_args = args pip_args = prepare_pip_source_args(sources, pip_args) pip_options, _ = pip_command.parser.parse_args(pip_args) pip_options.cache_dir = CACHE_DIR return pip_options
[ "def", "get_pip_options", "(", "args", "=", "[", "]", ",", "sources", "=", "None", ",", "pip_command", "=", "None", ")", ":", "if", "not", "pip_command", ":", "pip_command", "=", "get_pip_command", "(", ")", "if", "not", "sources", ":", "sources", "=", "[", "{", "\"url\"", ":", "\"https://pypi.org/simple\"", ",", "\"name\"", ":", "\"pypi\"", ",", "\"verify_ssl\"", ":", "True", "}", "]", "_ensure_dir", "(", "CACHE_DIR", ")", "pip_args", "=", "args", "pip_args", "=", "prepare_pip_source_args", "(", "sources", ",", "pip_args", ")", "pip_options", ",", "_", "=", "pip_command", ".", "parser", ".", "parse_args", "(", "pip_args", ")", "pip_options", ".", "cache_dir", "=", "CACHE_DIR", "return", "pip_options" ]
Build a pip command from a list of sources :param args: positional arguments passed through to the pip parser :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pre-built pip command instance :type pip_command: :class:`~pip._internal.cli.base_command.Command` :return: An instance of pip_options using the supplied arguments plus sane defaults :rtype: :class:`~pip._internal.cli.cmdoptions`
[ "Build", "a", "pip", "command", "from", "a", "list", "of", "sources" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L547-L570
24,862
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
get_finder
def get_finder(sources=None, pip_command=None, pip_options=None): # type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder """Get a package finder for looking up candidates to install :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pip command instance, defaults to None :type pip_command: :class:`~pip._internal.cli.base_command.Command` :param pip_options: A pip options, defaults to None :type pip_options: :class:`~pip._internal.cli.cmdoptions` :return: A package finder :rtype: :class:`~pip._internal.index.PackageFinder` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] if not pip_options: pip_options = get_pip_options(sources=sources, pip_command=pip_command) session = pip_command._build_session(pip_options) atexit.register(session.close) finder = pip_shims.shims.PackageFinder( find_links=[], index_urls=[s.get("url") for s in sources], trusted_hosts=[], allow_all_prereleases=pip_options.pre, session=session, ) return finder
python
def get_finder(sources=None, pip_command=None, pip_options=None): # type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder """Get a package finder for looking up candidates to install :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pip command instance, defaults to None :type pip_command: :class:`~pip._internal.cli.base_command.Command` :param pip_options: A pip options, defaults to None :type pip_options: :class:`~pip._internal.cli.cmdoptions` :return: A package finder :rtype: :class:`~pip._internal.index.PackageFinder` """ if not pip_command: pip_command = get_pip_command() if not sources: sources = [ {"url": "https://pypi.org/simple", "name": "pypi", "verify_ssl": True} ] if not pip_options: pip_options = get_pip_options(sources=sources, pip_command=pip_command) session = pip_command._build_session(pip_options) atexit.register(session.close) finder = pip_shims.shims.PackageFinder( find_links=[], index_urls=[s.get("url") for s in sources], trusted_hosts=[], allow_all_prereleases=pip_options.pre, session=session, ) return finder
[ "def", "get_finder", "(", "sources", "=", "None", ",", "pip_command", "=", "None", ",", "pip_options", "=", "None", ")", ":", "# type: (List[Dict[S, Union[S, bool]]], Optional[Command], Any) -> PackageFinder", "if", "not", "pip_command", ":", "pip_command", "=", "get_pip_command", "(", ")", "if", "not", "sources", ":", "sources", "=", "[", "{", "\"url\"", ":", "\"https://pypi.org/simple\"", ",", "\"name\"", ":", "\"pypi\"", ",", "\"verify_ssl\"", ":", "True", "}", "]", "if", "not", "pip_options", ":", "pip_options", "=", "get_pip_options", "(", "sources", "=", "sources", ",", "pip_command", "=", "pip_command", ")", "session", "=", "pip_command", ".", "_build_session", "(", "pip_options", ")", "atexit", ".", "register", "(", "session", ".", "close", ")", "finder", "=", "pip_shims", ".", "shims", ".", "PackageFinder", "(", "find_links", "=", "[", "]", ",", "index_urls", "=", "[", "s", ".", "get", "(", "\"url\"", ")", "for", "s", "in", "sources", "]", ",", "trusted_hosts", "=", "[", "]", ",", "allow_all_prereleases", "=", "pip_options", ".", "pre", ",", "session", "=", "session", ",", ")", "return", "finder" ]
Get a package finder for looking up candidates to install :param sources: A list of pipfile-formatted sources, defaults to None :param sources: list[dict], optional :param pip_command: A pip command instance, defaults to None :type pip_command: :class:`~pip._internal.cli.base_command.Command` :param pip_options: A pip options, defaults to None :type pip_options: :class:`~pip._internal.cli.cmdoptions` :return: A package finder :rtype: :class:`~pip._internal.index.PackageFinder`
[ "Get", "a", "package", "finder", "for", "looking", "up", "candidates", "to", "install" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L573-L604
24,863
pypa/pipenv
pipenv/vendor/requirementslib/models/dependencies.py
start_resolver
def start_resolver(finder=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`) """ pip_command = get_pip_command() pip_options = get_pip_options(pip_command=pip_command) if not finder: finder = get_finder(pip_command=pip_command, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE _ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels"))) download_dir = PKGS_DOWNLOAD_DIR _ensure_dir(download_dir) _build_dir = create_tracked_tempdir(fs_str("build")) _source_dir = create_tracked_tempdir(fs_str("source")) preparer = partialclass( pip_shims.shims.RequirementPreparer, build_dir=_build_dir, src_dir=_source_dir, download_dir=download_dir, wheel_download_dir=WHEEL_DOWNLOAD_DIR, progress_bar="off", build_isolation=False, ) resolver = partialclass( pip_shims.shims.Resolver, finder=finder, session=finder.session, upgrade_strategy="to-satisfy-only", force_reinstall=True, ignore_dependencies=False, ignore_requires_python=True, ignore_installed=True, isolated=False, wheel_cache=wheel_cache, use_user_site=False, ) try: if packaging.version.parse(pip_shims.shims.pip_version) >= packaging.version.parse('18'): with pip_shims.shims.RequirementTracker() as req_tracker: preparer = preparer(req_tracker=req_tracker) yield resolver(preparer=preparer) else: preparer = preparer() yield resolver(preparer=preparer) finally: finder.session.close()
python
def start_resolver(finder=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`) """ pip_command = get_pip_command() pip_options = get_pip_options(pip_command=pip_command) if not finder: finder = get_finder(pip_command=pip_command, pip_options=pip_options) if not wheel_cache: wheel_cache = WHEEL_CACHE _ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels"))) download_dir = PKGS_DOWNLOAD_DIR _ensure_dir(download_dir) _build_dir = create_tracked_tempdir(fs_str("build")) _source_dir = create_tracked_tempdir(fs_str("source")) preparer = partialclass( pip_shims.shims.RequirementPreparer, build_dir=_build_dir, src_dir=_source_dir, download_dir=download_dir, wheel_download_dir=WHEEL_DOWNLOAD_DIR, progress_bar="off", build_isolation=False, ) resolver = partialclass( pip_shims.shims.Resolver, finder=finder, session=finder.session, upgrade_strategy="to-satisfy-only", force_reinstall=True, ignore_dependencies=False, ignore_requires_python=True, ignore_installed=True, isolated=False, wheel_cache=wheel_cache, use_user_site=False, ) try: if packaging.version.parse(pip_shims.shims.pip_version) >= packaging.version.parse('18'): with pip_shims.shims.RequirementTracker() as req_tracker: preparer = preparer(req_tracker=req_tracker) yield resolver(preparer=preparer) else: preparer = preparer() yield resolver(preparer=preparer) finally: finder.session.close()
[ "def", "start_resolver", "(", "finder", "=", "None", ",", "wheel_cache", "=", "None", ")", ":", "pip_command", "=", "get_pip_command", "(", ")", "pip_options", "=", "get_pip_options", "(", "pip_command", "=", "pip_command", ")", "if", "not", "finder", ":", "finder", "=", "get_finder", "(", "pip_command", "=", "pip_command", ",", "pip_options", "=", "pip_options", ")", "if", "not", "wheel_cache", ":", "wheel_cache", "=", "WHEEL_CACHE", "_ensure_dir", "(", "fs_str", "(", "os", ".", "path", ".", "join", "(", "wheel_cache", ".", "cache_dir", ",", "\"wheels\"", ")", ")", ")", "download_dir", "=", "PKGS_DOWNLOAD_DIR", "_ensure_dir", "(", "download_dir", ")", "_build_dir", "=", "create_tracked_tempdir", "(", "fs_str", "(", "\"build\"", ")", ")", "_source_dir", "=", "create_tracked_tempdir", "(", "fs_str", "(", "\"source\"", ")", ")", "preparer", "=", "partialclass", "(", "pip_shims", ".", "shims", ".", "RequirementPreparer", ",", "build_dir", "=", "_build_dir", ",", "src_dir", "=", "_source_dir", ",", "download_dir", "=", "download_dir", ",", "wheel_download_dir", "=", "WHEEL_DOWNLOAD_DIR", ",", "progress_bar", "=", "\"off\"", ",", "build_isolation", "=", "False", ",", ")", "resolver", "=", "partialclass", "(", "pip_shims", ".", "shims", ".", "Resolver", ",", "finder", "=", "finder", ",", "session", "=", "finder", ".", "session", ",", "upgrade_strategy", "=", "\"to-satisfy-only\"", ",", "force_reinstall", "=", "True", ",", "ignore_dependencies", "=", "False", ",", "ignore_requires_python", "=", "True", ",", "ignore_installed", "=", "True", ",", "isolated", "=", "False", ",", "wheel_cache", "=", "wheel_cache", ",", "use_user_site", "=", "False", ",", ")", "try", ":", "if", "packaging", ".", "version", ".", "parse", "(", "pip_shims", ".", "shims", ".", "pip_version", ")", ">=", "packaging", ".", "version", ".", "parse", "(", "'18'", ")", ":", "with", "pip_shims", ".", "shims", ".", "RequirementTracker", "(", ")", "as", "req_tracker", ":", "preparer", "=", "preparer", "(", "req_tracker", "=", "req_tracker", ")", "yield", "resolver", "(", "preparer", "=", "preparer", ")", "else", ":", "preparer", "=", "preparer", "(", ")", "yield", "resolver", "(", "preparer", "=", "preparer", ")", "finally", ":", "finder", ".", "session", ".", "close", "(", ")" ]
Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._internal.resolve.Resolver`)
[ "Context", "manager", "to", "produce", "a", "resolver", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/dependencies.py#L608-L663
24,864
pypa/pipenv
pipenv/vendor/requirementslib/models/cache.py
DependencyCache.write_cache
def write_cache(self): """Writes the cache to disk as JSON.""" doc = { '__format__': 1, 'dependencies': self._cache, } with open(self._cache_file, 'w') as f: json.dump(doc, f, sort_keys=True)
python
def write_cache(self): """Writes the cache to disk as JSON.""" doc = { '__format__': 1, 'dependencies': self._cache, } with open(self._cache_file, 'w') as f: json.dump(doc, f, sort_keys=True)
[ "def", "write_cache", "(", "self", ")", ":", "doc", "=", "{", "'__format__'", ":", "1", ",", "'dependencies'", ":", "self", ".", "_cache", ",", "}", "with", "open", "(", "self", ".", "_cache_file", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "doc", ",", "f", ",", "sort_keys", "=", "True", ")" ]
Writes the cache to disk as JSON.
[ "Writes", "the", "cache", "to", "disk", "as", "JSON", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L112-L119
24,865
pypa/pipenv
pipenv/vendor/requirementslib/models/cache.py
DependencyCache.reverse_dependencies
def reverse_dependencies(self, ireqs): """ Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency tree is resolved. """ ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs] return self._reverse_dependencies(ireqs_as_cache_values)
python
def reverse_dependencies(self, ireqs): """ Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency tree is resolved. """ ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs] return self._reverse_dependencies(ireqs_as_cache_values)
[ "def", "reverse_dependencies", "(", "self", ",", "ireqs", ")", ":", "ireqs_as_cache_values", "=", "[", "self", ".", "as_cache_key", "(", "ireq", ")", "for", "ireq", "in", "ireqs", "]", "return", "self", ".", "_reverse_dependencies", "(", "ireqs_as_cache_values", ")" ]
Returns a lookup table of reverse dependencies for all the given ireqs. Since this is all static, it only works if the dependency cache contains the complete data, otherwise you end up with a partial view. This is typically no problem if you use this function after the entire dependency tree is resolved.
[ "Returns", "a", "lookup", "table", "of", "reverse", "dependencies", "for", "all", "the", "given", "ireqs", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L151-L161
24,866
pypa/pipenv
pipenv/vendor/requirementslib/models/cache.py
DependencyCache._reverse_dependencies
def _reverse_dependencies(self, cache_keys): """ Returns a lookup table of reverse dependencies for all the given cache keys. Example input: [('pep8', '1.5.7'), ('flake8', '2.4.0'), ('mccabe', '0.3'), ('pyflakes', '0.8.1')] Example output: {'pep8': ['flake8'], 'flake8': [], 'mccabe': ['flake8'], 'pyflakes': ['flake8']} """ # First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'), # ('flake8', 'mccabe'), ...] return lookup_table((key_from_req(Requirement(dep_name)), name) for name, version_and_extras in cache_keys for dep_name in self.cache[name][version_and_extras])
python
def _reverse_dependencies(self, cache_keys): """ Returns a lookup table of reverse dependencies for all the given cache keys. Example input: [('pep8', '1.5.7'), ('flake8', '2.4.0'), ('mccabe', '0.3'), ('pyflakes', '0.8.1')] Example output: {'pep8': ['flake8'], 'flake8': [], 'mccabe': ['flake8'], 'pyflakes': ['flake8']} """ # First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'), # ('flake8', 'mccabe'), ...] return lookup_table((key_from_req(Requirement(dep_name)), name) for name, version_and_extras in cache_keys for dep_name in self.cache[name][version_and_extras])
[ "def", "_reverse_dependencies", "(", "self", ",", "cache_keys", ")", ":", "# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),", "# ('flake8', 'mccabe'), ...]", "return", "lookup_table", "(", "(", "key_from_req", "(", "Requirement", "(", "dep_name", ")", ")", ",", "name", ")", "for", "name", ",", "version_and_extras", "in", "cache_keys", "for", "dep_name", "in", "self", ".", "cache", "[", "name", "]", "[", "version_and_extras", "]", ")" ]
Returns a lookup table of reverse dependencies for all the given cache keys. Example input: [('pep8', '1.5.7'), ('flake8', '2.4.0'), ('mccabe', '0.3'), ('pyflakes', '0.8.1')] Example output: {'pep8': ['flake8'], 'flake8': [], 'mccabe': ['flake8'], 'pyflakes': ['flake8']}
[ "Returns", "a", "lookup", "table", "of", "reverse", "dependencies", "for", "all", "the", "given", "cache", "keys", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L163-L186
24,867
pypa/pipenv
pipenv/vendor/requirementslib/models/cache.py
_JSONCache.as_cache_key
def as_cache_key(self, ireq): """Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example:: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so:: ("ipython", "2.1.0[nbconvert,notebook]") """ extras = tuple(sorted(ireq.extras)) if not extras: extras_string = "" else: extras_string = "[{}]".format(",".join(extras)) name = key_from_req(ireq.req) version = get_pinned_version(ireq) return name, "{}{}".format(version, extras_string)
python
def as_cache_key(self, ireq): """Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example:: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so:: ("ipython", "2.1.0[nbconvert,notebook]") """ extras = tuple(sorted(ireq.extras)) if not extras: extras_string = "" else: extras_string = "[{}]".format(",".join(extras)) name = key_from_req(ireq.req) version = get_pinned_version(ireq) return name, "{}{}".format(version, extras_string)
[ "def", "as_cache_key", "(", "self", ",", "ireq", ")", ":", "extras", "=", "tuple", "(", "sorted", "(", "ireq", ".", "extras", ")", ")", "if", "not", "extras", ":", "extras_string", "=", "\"\"", "else", ":", "extras_string", "=", "\"[{}]\"", ".", "format", "(", "\",\"", ".", "join", "(", "extras", ")", ")", "name", "=", "key_from_req", "(", "ireq", ".", "req", ")", "version", "=", "get_pinned_version", "(", "ireq", ")", "return", "name", ",", "\"{}{}\"", ".", "format", "(", "version", ",", "extras_string", ")" ]
Given a requirement, return its cache key. This behavior is a little weird in order to allow backwards compatibility with cache files. For a requirement without extras, this will return, for example:: ("ipython", "2.1.0") For a requirement with extras, the extras will be comma-separated and appended to the version, inside brackets, like so:: ("ipython", "2.1.0[nbconvert,notebook]")
[ "Given", "a", "requirement", "return", "its", "cache", "key", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/cache.py#L266-L287
24,868
pypa/pipenv
pipenv/patched/notpip/_vendor/lockfile/__init__.py
locked
def locked(path, timeout=None): """Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... """ def decor(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock = FileLock(path, timeout=timeout) lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper return decor
python
def locked(path, timeout=None): """Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... """ def decor(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock = FileLock(path, timeout=timeout) lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper return decor
[ "def", "locked", "(", "path", ",", "timeout", "=", "None", ")", ":", "def", "decor", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lock", "=", "FileLock", "(", "path", ",", "timeout", "=", "timeout", ")", "lock", ".", "acquire", "(", ")", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "lock", ".", "release", "(", ")", "return", "wrapper", "return", "decor" ]
Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ...
[ "Decorator", "which", "enables", "locks", "for", "decorated", "function", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/__init__.py#L315-L337
24,869
pypa/pipenv
pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py
getTreeWalker
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). * "lxml": Optimized walker for lxml.etree * "genshi": a Genshi stream :arg implementation: A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree (Currently applies to the "etree" tree type only). :arg kwargs: keyword arguments passed to the etree walker--for other walkers, this has no effect :returns: a TreeWalker class """ treeType = treeType.lower() if treeType not in treeWalkerCache: if treeType == "dom": from . import dom treeWalkerCache[treeType] = dom.TreeWalker elif treeType == "genshi": from . import genshi treeWalkerCache[treeType] = genshi.TreeWalker elif treeType == "lxml": from . import etree_lxml treeWalkerCache[treeType] = etree_lxml.TreeWalker elif treeType == "etree": from . import etree if implementation is None: implementation = default_etree # XXX: NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeWalker return treeWalkerCache.get(treeType)
python
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). * "lxml": Optimized walker for lxml.etree * "genshi": a Genshi stream :arg implementation: A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree (Currently applies to the "etree" tree type only). :arg kwargs: keyword arguments passed to the etree walker--for other walkers, this has no effect :returns: a TreeWalker class """ treeType = treeType.lower() if treeType not in treeWalkerCache: if treeType == "dom": from . import dom treeWalkerCache[treeType] = dom.TreeWalker elif treeType == "genshi": from . import genshi treeWalkerCache[treeType] = genshi.TreeWalker elif treeType == "lxml": from . import etree_lxml treeWalkerCache[treeType] = etree_lxml.TreeWalker elif treeType == "etree": from . import etree if implementation is None: implementation = default_etree # XXX: NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeWalker return treeWalkerCache.get(treeType)
[ "def", "getTreeWalker", "(", "treeType", ",", "implementation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "treeType", "=", "treeType", ".", "lower", "(", ")", "if", "treeType", "not", "in", "treeWalkerCache", ":", "if", "treeType", "==", "\"dom\"", ":", "from", ".", "import", "dom", "treeWalkerCache", "[", "treeType", "]", "=", "dom", ".", "TreeWalker", "elif", "treeType", "==", "\"genshi\"", ":", "from", ".", "import", "genshi", "treeWalkerCache", "[", "treeType", "]", "=", "genshi", ".", "TreeWalker", "elif", "treeType", "==", "\"lxml\"", ":", "from", ".", "import", "etree_lxml", "treeWalkerCache", "[", "treeType", "]", "=", "etree_lxml", ".", "TreeWalker", "elif", "treeType", "==", "\"etree\"", ":", "from", ".", "import", "etree", "if", "implementation", "is", "None", ":", "implementation", "=", "default_etree", "# XXX: NEVER cache here, caching is done in the etree submodule", "return", "etree", ".", "getETreeModule", "(", "implementation", ",", "*", "*", "kwargs", ")", ".", "TreeWalker", "return", "treeWalkerCache", ".", "get", "(", "treeType", ")" ]
Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). * "lxml": Optimized walker for lxml.etree * "genshi": a Genshi stream :arg implementation: A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree (Currently applies to the "etree" tree type only). :arg kwargs: keyword arguments passed to the etree walker--for other walkers, this has no effect :returns: a TreeWalker class
[ "Get", "a", "TreeWalker", "class", "for", "various", "types", "of", "tree", "with", "built", "-", "in", "support" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treewalkers/__init__.py#L21-L62
24,870
pypa/pipenv
pipenv/vendor/yaspin/core.py
Yaspin.hide
def hide(self): """Hide the spinner to allow for custom writing to the terminal.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and not self._hide_spin.is_set(): # set the hidden spinner flag self._hide_spin.set() # clear the current line sys.stdout.write("\r") self._clear_line() # flush the stdout buffer so the current line can be rewritten to sys.stdout.flush()
python
def hide(self): """Hide the spinner to allow for custom writing to the terminal.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and not self._hide_spin.is_set(): # set the hidden spinner flag self._hide_spin.set() # clear the current line sys.stdout.write("\r") self._clear_line() # flush the stdout buffer so the current line can be rewritten to sys.stdout.flush()
[ "def", "hide", "(", "self", ")", ":", "thr_is_alive", "=", "self", ".", "_spin_thread", "and", "self", ".", "_spin_thread", ".", "is_alive", "(", ")", "if", "thr_is_alive", "and", "not", "self", ".", "_hide_spin", ".", "is_set", "(", ")", ":", "# set the hidden spinner flag", "self", ".", "_hide_spin", ".", "set", "(", ")", "# clear the current line", "sys", ".", "stdout", ".", "write", "(", "\"\\r\"", ")", "self", ".", "_clear_line", "(", ")", "# flush the stdout buffer so the current line can be rewritten to", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Hide the spinner to allow for custom writing to the terminal.
[ "Hide", "the", "spinner", "to", "allow", "for", "custom", "writing", "to", "the", "terminal", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L251-L264
24,871
pypa/pipenv
pipenv/vendor/yaspin/core.py
Yaspin.show
def show(self): """Show the hidden spinner.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and self._hide_spin.is_set(): # clear the hidden spinner flag self._hide_spin.clear() # clear the current line so the spinner is not appended to it sys.stdout.write("\r") self._clear_line()
python
def show(self): """Show the hidden spinner.""" thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and self._hide_spin.is_set(): # clear the hidden spinner flag self._hide_spin.clear() # clear the current line so the spinner is not appended to it sys.stdout.write("\r") self._clear_line()
[ "def", "show", "(", "self", ")", ":", "thr_is_alive", "=", "self", ".", "_spin_thread", "and", "self", ".", "_spin_thread", ".", "is_alive", "(", ")", "if", "thr_is_alive", "and", "self", ".", "_hide_spin", ".", "is_set", "(", ")", ":", "# clear the hidden spinner flag", "self", ".", "_hide_spin", ".", "clear", "(", ")", "# clear the current line so the spinner is not appended to it", "sys", ".", "stdout", ".", "write", "(", "\"\\r\"", ")", "self", ".", "_clear_line", "(", ")" ]
Show the hidden spinner.
[ "Show", "the", "hidden", "spinner", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L266-L276
24,872
pypa/pipenv
pipenv/vendor/yaspin/core.py
Yaspin.write
def write(self, text): """Write text in the terminal without breaking the spinner.""" # similar to tqdm.write() # https://pypi.python.org/pypi/tqdm#writing-messages sys.stdout.write("\r") self._clear_line() _text = to_unicode(text) if PY2: _text = _text.encode(ENCODING) # Ensure output is bytes for Py2 and Unicode for Py3 assert isinstance(_text, builtin_str) sys.stdout.write("{0}\n".format(_text))
python
def write(self, text): """Write text in the terminal without breaking the spinner.""" # similar to tqdm.write() # https://pypi.python.org/pypi/tqdm#writing-messages sys.stdout.write("\r") self._clear_line() _text = to_unicode(text) if PY2: _text = _text.encode(ENCODING) # Ensure output is bytes for Py2 and Unicode for Py3 assert isinstance(_text, builtin_str) sys.stdout.write("{0}\n".format(_text))
[ "def", "write", "(", "self", ",", "text", ")", ":", "# similar to tqdm.write()", "# https://pypi.python.org/pypi/tqdm#writing-messages", "sys", ".", "stdout", ".", "write", "(", "\"\\r\"", ")", "self", ".", "_clear_line", "(", ")", "_text", "=", "to_unicode", "(", "text", ")", "if", "PY2", ":", "_text", "=", "_text", ".", "encode", "(", "ENCODING", ")", "# Ensure output is bytes for Py2 and Unicode for Py3", "assert", "isinstance", "(", "_text", ",", "builtin_str", ")", "sys", ".", "stdout", ".", "write", "(", "\"{0}\\n\"", ".", "format", "(", "_text", ")", ")" ]
Write text in the terminal without breaking the spinner.
[ "Write", "text", "in", "the", "terminal", "without", "breaking", "the", "spinner", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L278-L292
24,873
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
RevOptions.to_args
def to_args(self): # type: () -> List[str] """ Return the VCS-specific command arguments. """ args = [] # type: List[str] rev = self.arg_rev if rev is not None: args += self.vcs.get_base_rev_args(rev) args += self.extra_args return args
python
def to_args(self): # type: () -> List[str] """ Return the VCS-specific command arguments. """ args = [] # type: List[str] rev = self.arg_rev if rev is not None: args += self.vcs.get_base_rev_args(rev) args += self.extra_args return args
[ "def", "to_args", "(", "self", ")", ":", "# type: () -> List[str]", "args", "=", "[", "]", "# type: List[str]", "rev", "=", "self", ".", "arg_rev", "if", "rev", "is", "not", "None", ":", "args", "+=", "self", ".", "vcs", ".", "get_base_rev_args", "(", "rev", ")", "args", "+=", "self", ".", "extra_args", "return", "args" ]
Return the VCS-specific command arguments.
[ "Return", "the", "VCS", "-", "specific", "command", "arguments", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L71-L82
24,874
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
RevOptions.make_new
def make_new(self, rev): # type: (str) -> RevOptions """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
python
def make_new(self, rev): # type: (str) -> RevOptions """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
[ "def", "make_new", "(", "self", ",", "rev", ")", ":", "# type: (str) -> RevOptions", "return", "self", ".", "vcs", ".", "make_rev_options", "(", "rev", ",", "extra_args", "=", "self", ".", "extra_args", ")" ]
Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object.
[ "Make", "a", "copy", "of", "the", "current", "instance", "but", "with", "a", "new", "rev", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L91-L99
24,875
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
VersionControl.get_url_rev_and_auth
def get_url_rev_and_auth(self, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] """ Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). """ scheme, netloc, path, query, frag = urllib_parse.urlsplit(url) if '+' not in scheme: raise ValueError( "Sorry, {!r} is a malformed VCS url. " "The format is <vcs>+<protocol>://<url>, " "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url) ) # Remove the vcs prefix. scheme = scheme.split('+', 1)[1] netloc, user_pass = self.get_netloc_and_auth(netloc, scheme) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urllib_parse.urlunsplit((scheme, netloc, path, query, '')) return url, rev, user_pass
python
def get_url_rev_and_auth(self, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] """ Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). """ scheme, netloc, path, query, frag = urllib_parse.urlsplit(url) if '+' not in scheme: raise ValueError( "Sorry, {!r} is a malformed VCS url. " "The format is <vcs>+<protocol>://<url>, " "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url) ) # Remove the vcs prefix. scheme = scheme.split('+', 1)[1] netloc, user_pass = self.get_netloc_and_auth(netloc, scheme) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urllib_parse.urlunsplit((scheme, netloc, path, query, '')) return url, rev, user_pass
[ "def", "get_url_rev_and_auth", "(", "self", ",", "url", ")", ":", "# type: (str) -> Tuple[str, Optional[str], AuthInfo]", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "frag", "=", "urllib_parse", ".", "urlsplit", "(", "url", ")", "if", "'+'", "not", "in", "scheme", ":", "raise", "ValueError", "(", "\"Sorry, {!r} is a malformed VCS url. \"", "\"The format is <vcs>+<protocol>://<url>, \"", "\"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp\"", ".", "format", "(", "url", ")", ")", "# Remove the vcs prefix.", "scheme", "=", "scheme", ".", "split", "(", "'+'", ",", "1", ")", "[", "1", "]", "netloc", ",", "user_pass", "=", "self", ".", "get_netloc_and_auth", "(", "netloc", ",", "scheme", ")", "rev", "=", "None", "if", "'@'", "in", "path", ":", "path", ",", "rev", "=", "path", ".", "rsplit", "(", "'@'", ",", "1", ")", "url", "=", "urllib_parse", ".", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "''", ")", ")", "return", "url", ",", "rev", ",", "user_pass" ]
Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)).
[ "Parse", "the", "repository", "URL", "to", "use", "and", "return", "the", "URL", "revision", "and", "auth", "info", "to", "use", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L248-L270
24,876
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
VersionControl.compare_urls
def compare_urls(self, url1, url2): # type: (str, str) -> bool """ Compare two repo URLs for identity, ignoring incidental differences. """ return (self.normalize_url(url1) == self.normalize_url(url2))
python
def compare_urls(self, url1, url2): # type: (str, str) -> bool """ Compare two repo URLs for identity, ignoring incidental differences. """ return (self.normalize_url(url1) == self.normalize_url(url2))
[ "def", "compare_urls", "(", "self", ",", "url1", ",", "url2", ")", ":", "# type: (str, str) -> bool", "return", "(", "self", ".", "normalize_url", "(", "url1", ")", "==", "self", ".", "normalize_url", "(", "url2", ")", ")" ]
Compare two repo URLs for identity, ignoring incidental differences.
[ "Compare", "two", "repo", "URLs", "for", "identity", "ignoring", "incidental", "differences", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L299-L304
24,877
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
VersionControl.obtain
def obtain(self, dest): # type: (str) -> None """ Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update. """ url, rev_options = self.get_url_rev_options(self.url) if not os.path.exists(dest): self.fetch_new(dest, url, rev_options) return rev_display = rev_options.to_display() if self.is_repository_directory(dest): existing_url = self.get_remote_url(dest) if self.compare_urls(existing_url, url): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.is_commit_id_equal(dest, rev_options.rev): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, url, rev_options) else: logger.info('Skipping because already up-to-date.') return logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) # https://github.com/python/mypy/issues/1174 prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore ('i', 'w', 'b')) logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 'a': sys.exit(-1) if response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) self.fetch_new(dest, url, rev_options) return if response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) self.fetch_new(dest, url, rev_options) return # Do nothing if the response is "i". if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options)
python
def obtain(self, dest): # type: (str) -> None """ Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update. """ url, rev_options = self.get_url_rev_options(self.url) if not os.path.exists(dest): self.fetch_new(dest, url, rev_options) return rev_display = rev_options.to_display() if self.is_repository_directory(dest): existing_url = self.get_remote_url(dest) if self.compare_urls(existing_url, url): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.is_commit_id_equal(dest, rev_options.rev): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, url, rev_options) else: logger.info('Skipping because already up-to-date.') return logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) # https://github.com/python/mypy/issues/1174 prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore ('i', 'w', 'b')) logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 'a': sys.exit(-1) if response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) self.fetch_new(dest, url, rev_options) return if response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) self.fetch_new(dest, url, rev_options) return # Do nothing if the response is "i". if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options)
[ "def", "obtain", "(", "self", ",", "dest", ")", ":", "# type: (str) -> None", "url", ",", "rev_options", "=", "self", ".", "get_url_rev_options", "(", "self", ".", "url", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "self", ".", "fetch_new", "(", "dest", ",", "url", ",", "rev_options", ")", "return", "rev_display", "=", "rev_options", ".", "to_display", "(", ")", "if", "self", ".", "is_repository_directory", "(", "dest", ")", ":", "existing_url", "=", "self", ".", "get_remote_url", "(", "dest", ")", "if", "self", ".", "compare_urls", "(", "existing_url", ",", "url", ")", ":", "logger", ".", "debug", "(", "'%s in %s exists, and has correct URL (%s)'", ",", "self", ".", "repo_name", ".", "title", "(", ")", ",", "display_path", "(", "dest", ")", ",", "url", ",", ")", "if", "not", "self", ".", "is_commit_id_equal", "(", "dest", ",", "rev_options", ".", "rev", ")", ":", "logger", ".", "info", "(", "'Updating %s %s%s'", ",", "display_path", "(", "dest", ")", ",", "self", ".", "repo_name", ",", "rev_display", ",", ")", "self", ".", "update", "(", "dest", ",", "url", ",", "rev_options", ")", "else", ":", "logger", ".", "info", "(", "'Skipping because already up-to-date.'", ")", "return", "logger", ".", "warning", "(", "'%s %s in %s exists with URL %s'", ",", "self", ".", "name", ",", "self", ".", "repo_name", ",", "display_path", "(", "dest", ")", ",", "existing_url", ",", ")", "prompt", "=", "(", "'(s)witch, (i)gnore, (w)ipe, (b)ackup '", ",", "(", "'s'", ",", "'i'", ",", "'w'", ",", "'b'", ")", ")", "else", ":", "logger", ".", "warning", "(", "'Directory %s already exists, and is not a %s %s.'", ",", "dest", ",", "self", ".", "name", ",", "self", ".", "repo_name", ",", ")", "# https://github.com/python/mypy/issues/1174", "prompt", "=", "(", "'(i)gnore, (w)ipe, (b)ackup '", ",", "# type: ignore", "(", "'i'", ",", "'w'", ",", "'b'", ")", ")", "logger", ".", "warning", "(", "'The plan is to install the %s repository %s'", ",", "self", ".", "name", ",", "url", ",", ")", "response", "=", "ask_path_exists", "(", "'What to do? %s'", "%", "prompt", "[", "0", "]", ",", "prompt", "[", "1", "]", ")", "if", "response", "==", "'a'", ":", "sys", ".", "exit", "(", "-", "1", ")", "if", "response", "==", "'w'", ":", "logger", ".", "warning", "(", "'Deleting %s'", ",", "display_path", "(", "dest", ")", ")", "rmtree", "(", "dest", ")", "self", ".", "fetch_new", "(", "dest", ",", "url", ",", "rev_options", ")", "return", "if", "response", "==", "'b'", ":", "dest_dir", "=", "backup_dir", "(", "dest", ")", "logger", ".", "warning", "(", "'Backing up %s to %s'", ",", "display_path", "(", "dest", ")", ",", "dest_dir", ",", ")", "shutil", ".", "move", "(", "dest", ",", "dest_dir", ")", "self", ".", "fetch_new", "(", "dest", ",", "url", ",", "rev_options", ")", "return", "# Do nothing if the response is \"i\".", "if", "response", "==", "'s'", ":", "logger", ".", "info", "(", "'Switching %s %s to %s%s'", ",", "self", ".", "repo_name", ",", "display_path", "(", "dest", ")", ",", "url", ",", "rev_display", ",", ")", "self", ".", "switch", "(", "dest", ",", "url", ",", "rev_options", ")" ]
Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update.
[ "Install", "or", "update", "in", "editable", "mode", "the", "package", "represented", "by", "this", "VersionControl", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L345-L436
24,878
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
VersionControl.run_command
def run_command( cls, cmd, # type: List[str] show_stdout=True, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] spinner=None # type: Optional[SpinnerInterface] ): # type: (...) -> Optional[Text] """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available """ cmd = [cls.name] + cmd try: return call_subprocess(cmd, show_stdout, cwd, on_returncode=on_returncode, extra_ok_returncodes=extra_ok_returncodes, command_desc=command_desc, extra_environ=extra_environ, unset_environ=cls.unset_environ, spinner=spinner) except OSError as e: # errno.ENOENT = no such file or directory # In other words, the VCS executable isn't available if e.errno == errno.ENOENT: raise BadCommand( 'Cannot find command %r - do you have ' '%r installed and in your ' 'PATH?' % (cls.name, cls.name)) else: raise
python
def run_command( cls, cmd, # type: List[str] show_stdout=True, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] spinner=None # type: Optional[SpinnerInterface] ): # type: (...) -> Optional[Text] """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available """ cmd = [cls.name] + cmd try: return call_subprocess(cmd, show_stdout, cwd, on_returncode=on_returncode, extra_ok_returncodes=extra_ok_returncodes, command_desc=command_desc, extra_environ=extra_environ, unset_environ=cls.unset_environ, spinner=spinner) except OSError as e: # errno.ENOENT = no such file or directory # In other words, the VCS executable isn't available if e.errno == errno.ENOENT: raise BadCommand( 'Cannot find command %r - do you have ' '%r installed and in your ' 'PATH?' % (cls.name, cls.name)) else: raise
[ "def", "run_command", "(", "cls", ",", "cmd", ",", "# type: List[str]", "show_stdout", "=", "True", ",", "# type: bool", "cwd", "=", "None", ",", "# type: Optional[str]", "on_returncode", "=", "'raise'", ",", "# type: str", "extra_ok_returncodes", "=", "None", ",", "# type: Optional[Iterable[int]]", "command_desc", "=", "None", ",", "# type: Optional[str]", "extra_environ", "=", "None", ",", "# type: Optional[Mapping[str, Any]]", "spinner", "=", "None", "# type: Optional[SpinnerInterface]", ")", ":", "# type: (...) -> Optional[Text]", "cmd", "=", "[", "cls", ".", "name", "]", "+", "cmd", "try", ":", "return", "call_subprocess", "(", "cmd", ",", "show_stdout", ",", "cwd", ",", "on_returncode", "=", "on_returncode", ",", "extra_ok_returncodes", "=", "extra_ok_returncodes", ",", "command_desc", "=", "command_desc", ",", "extra_environ", "=", "extra_environ", ",", "unset_environ", "=", "cls", ".", "unset_environ", ",", "spinner", "=", "spinner", ")", "except", "OSError", "as", "e", ":", "# errno.ENOENT = no such file or directory", "# In other words, the VCS executable isn't available", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "raise", "BadCommand", "(", "'Cannot find command %r - do you have '", "'%r installed and in your '", "'PATH?'", "%", "(", "cls", ".", "name", ",", "cls", ".", "name", ")", ")", "else", ":", "raise" ]
Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available
[ "Run", "a", "VCS", "subcommand", "This", "is", "simply", "a", "wrapper", "around", "call_subprocess", "that", "adds", "the", "VCS", "command", "name", "and", "checks", "that", "the", "VCS", "is", "available" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L476-L511
24,879
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/__init__.py
VersionControl.is_repository_directory
def is_repository_directory(cls, path): # type: (str) -> bool """ Return whether a directory path is a repository directory. """ logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.dirname))
python
def is_repository_directory(cls, path): # type: (str) -> bool """ Return whether a directory path is a repository directory. """ logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.dirname))
[ "def", "is_repository_directory", "(", "cls", ",", "path", ")", ":", "# type: (str) -> bool", "logger", ".", "debug", "(", "'Checking in %s for %s (%s)...'", ",", "path", ",", "cls", ".", "dirname", ",", "cls", ".", "name", ")", "return", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cls", ".", "dirname", ")", ")" ]
Return whether a directory path is a repository directory.
[ "Return", "whether", "a", "directory", "path", "is", "a", "repository", "directory", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/__init__.py#L514-L521
24,880
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
compress_for_rename
def compress_for_rename(paths): """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() def norm_join(*a): return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() all_subdirs = set() for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards
python
def compress_for_rename(paths): """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() def norm_join(*a): return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() all_subdirs = set() for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards
[ "def", "compress_for_rename", "(", "paths", ")", ":", "case_map", "=", "dict", "(", "(", "os", ".", "path", ".", "normcase", "(", "p", ")", ",", "p", ")", "for", "p", "in", "paths", ")", "remaining", "=", "set", "(", "case_map", ")", "unchecked", "=", "sorted", "(", "set", "(", "os", ".", "path", ".", "split", "(", "p", ")", "[", "0", "]", "for", "p", "in", "case_map", ".", "values", "(", ")", ")", ",", "key", "=", "len", ")", "wildcards", "=", "set", "(", ")", "def", "norm_join", "(", "*", "a", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "join", "(", "*", "a", ")", ")", "for", "root", "in", "unchecked", ":", "if", "any", "(", "os", ".", "path", ".", "normcase", "(", "root", ")", ".", "startswith", "(", "w", ")", "for", "w", "in", "wildcards", ")", ":", "# This directory has already been handled.", "continue", "all_files", "=", "set", "(", ")", "all_subdirs", "=", "set", "(", ")", "for", "dirname", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "root", ")", ":", "all_subdirs", ".", "update", "(", "norm_join", "(", "root", ",", "dirname", ",", "d", ")", "for", "d", "in", "subdirs", ")", "all_files", ".", "update", "(", "norm_join", "(", "root", ",", "dirname", ",", "f", ")", "for", "f", "in", "files", ")", "# If all the files we found are in our remaining set of files to", "# remove, then remove them from the latter set and add a wildcard", "# for the directory.", "if", "not", "(", "all_files", "-", "remaining", ")", ":", "remaining", ".", "difference_update", "(", "all_files", ")", "wildcards", ".", "add", "(", "root", "+", "os", ".", "sep", ")", "return", "set", "(", "map", "(", "case_map", ".", "__getitem__", ",", "remaining", ")", ")", "|", "wildcards" ]
Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk.
[ "Returns", "a", "set", "containing", "the", "paths", "that", "need", "to", "be", "renamed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L99-L134
24,881
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
compress_for_output_listing
def compress_for_output_listing(paths): """Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. """ will_remove = list(paths) will_skip = set() # Determine folders and files folders = set() files = set() for path in will_remove: if path.endswith(".pyc"): continue if path.endswith("__init__.py") or ".dist-info" in path: folders.add(os.path.dirname(path)) files.add(path) _normcased_files = set(map(os.path.normcase, files)) folders = compact(folders) # This walks the tree using os.walk to not miss extra folders # that might get added. for folder in folders: for dirpath, _, dirfiles in os.walk(folder): for fname in dirfiles: if fname.endswith(".pyc"): continue file_ = os.path.join(dirpath, fname) if (os.path.isfile(file_) and os.path.normcase(file_) not in _normcased_files): # We are skipping this file. Add it to the set. will_skip.add(file_) will_remove = files | { os.path.join(folder, "*") for folder in folders } return will_remove, will_skip
python
def compress_for_output_listing(paths): """Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. """ will_remove = list(paths) will_skip = set() # Determine folders and files folders = set() files = set() for path in will_remove: if path.endswith(".pyc"): continue if path.endswith("__init__.py") or ".dist-info" in path: folders.add(os.path.dirname(path)) files.add(path) _normcased_files = set(map(os.path.normcase, files)) folders = compact(folders) # This walks the tree using os.walk to not miss extra folders # that might get added. for folder in folders: for dirpath, _, dirfiles in os.walk(folder): for fname in dirfiles: if fname.endswith(".pyc"): continue file_ = os.path.join(dirpath, fname) if (os.path.isfile(file_) and os.path.normcase(file_) not in _normcased_files): # We are skipping this file. Add it to the set. will_skip.add(file_) will_remove = files | { os.path.join(folder, "*") for folder in folders } return will_remove, will_skip
[ "def", "compress_for_output_listing", "(", "paths", ")", ":", "will_remove", "=", "list", "(", "paths", ")", "will_skip", "=", "set", "(", ")", "# Determine folders and files", "folders", "=", "set", "(", ")", "files", "=", "set", "(", ")", "for", "path", "in", "will_remove", ":", "if", "path", ".", "endswith", "(", "\".pyc\"", ")", ":", "continue", "if", "path", ".", "endswith", "(", "\"__init__.py\"", ")", "or", "\".dist-info\"", "in", "path", ":", "folders", ".", "add", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "files", ".", "add", "(", "path", ")", "_normcased_files", "=", "set", "(", "map", "(", "os", ".", "path", ".", "normcase", ",", "files", ")", ")", "folders", "=", "compact", "(", "folders", ")", "# This walks the tree using os.walk to not miss extra folders", "# that might get added.", "for", "folder", "in", "folders", ":", "for", "dirpath", ",", "_", ",", "dirfiles", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "fname", "in", "dirfiles", ":", "if", "fname", ".", "endswith", "(", "\".pyc\"", ")", ":", "continue", "file_", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "fname", ")", "if", "(", "os", ".", "path", ".", "isfile", "(", "file_", ")", "and", "os", ".", "path", ".", "normcase", "(", "file_", ")", "not", "in", "_normcased_files", ")", ":", "# We are skipping this file. Add it to the set.", "will_skip", ".", "add", "(", "file_", ")", "will_remove", "=", "files", "|", "{", "os", ".", "path", ".", "join", "(", "folder", ",", "\"*\"", ")", "for", "folder", "in", "folders", "}", "return", "will_remove", ",", "will_skip" ]
Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders.
[ "Returns", "a", "tuple", "of", "2", "sets", "of", "which", "paths", "to", "display", "to", "user" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L137-L183
24,882
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
StashedUninstallPathSet._get_directory_stash
def _get_directory_stash(self, path): """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) save_dir.create() except OSError: save_dir = TempDirectory(kind="uninstall") save_dir.create() self._save_dirs[os.path.normcase(path)] = save_dir return save_dir.path
python
def _get_directory_stash(self, path): """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) save_dir.create() except OSError: save_dir = TempDirectory(kind="uninstall") save_dir.create() self._save_dirs[os.path.normcase(path)] = save_dir return save_dir.path
[ "def", "_get_directory_stash", "(", "self", ",", "path", ")", ":", "try", ":", "save_dir", "=", "AdjacentTempDirectory", "(", "path", ")", "save_dir", ".", "create", "(", ")", "except", "OSError", ":", "save_dir", "=", "TempDirectory", "(", "kind", "=", "\"uninstall\"", ")", "save_dir", ".", "create", "(", ")", "self", ".", "_save_dirs", "[", "os", ".", "path", ".", "normcase", "(", "path", ")", "]", "=", "save_dir", "return", "save_dir", ".", "path" ]
Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.
[ "Stashes", "a", "directory", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L197-L211
24,883
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
StashedUninstallPathSet._get_file_stash
def _get_file_stash(self, path): """Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.""" path = os.path.normcase(path) head, old_head = os.path.dirname(path), None save_dir = None while head != old_head: try: save_dir = self._save_dirs[head] break except KeyError: pass head, old_head = os.path.dirname(head), head else: # Did not find any suitable root head = os.path.dirname(path) save_dir = TempDirectory(kind='uninstall') save_dir.create() self._save_dirs[head] = save_dir relpath = os.path.relpath(path, head) if relpath and relpath != os.path.curdir: return os.path.join(save_dir.path, relpath) return save_dir.path
python
def _get_file_stash(self, path): """Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.""" path = os.path.normcase(path) head, old_head = os.path.dirname(path), None save_dir = None while head != old_head: try: save_dir = self._save_dirs[head] break except KeyError: pass head, old_head = os.path.dirname(head), head else: # Did not find any suitable root head = os.path.dirname(path) save_dir = TempDirectory(kind='uninstall') save_dir.create() self._save_dirs[head] = save_dir relpath = os.path.relpath(path, head) if relpath and relpath != os.path.curdir: return os.path.join(save_dir.path, relpath) return save_dir.path
[ "def", "_get_file_stash", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normcase", "(", "path", ")", "head", ",", "old_head", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "None", "save_dir", "=", "None", "while", "head", "!=", "old_head", ":", "try", ":", "save_dir", "=", "self", ".", "_save_dirs", "[", "head", "]", "break", "except", "KeyError", ":", "pass", "head", ",", "old_head", "=", "os", ".", "path", ".", "dirname", "(", "head", ")", ",", "head", "else", ":", "# Did not find any suitable root", "head", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "save_dir", "=", "TempDirectory", "(", "kind", "=", "'uninstall'", ")", "save_dir", ".", "create", "(", ")", "self", ".", "_save_dirs", "[", "head", "]", "=", "save_dir", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "head", ")", "if", "relpath", "and", "relpath", "!=", "os", ".", "path", ".", "curdir", ":", "return", "os", ".", "path", ".", "join", "(", "save_dir", ".", "path", ",", "relpath", ")", "return", "save_dir", ".", "path" ]
Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.
[ "Stashes", "a", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L213-L239
24,884
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
StashedUninstallPathSet.stash
def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if os.path.isdir(path) and os.path.isdir(new_path): # If we're moving a directory, we need to # remove the destination first or else it will be # moved to inside the existing directory. # We just created new_path ourselves, so it will # be removable. os.rmdir(new_path) renames(path, new_path) return new_path
python
def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if os.path.isdir(path) and os.path.isdir(new_path): # If we're moving a directory, we need to # remove the destination first or else it will be # moved to inside the existing directory. # We just created new_path ourselves, so it will # be removable. os.rmdir(new_path) renames(path, new_path) return new_path
[ "def", "stash", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "new_path", "=", "self", ".", "_get_directory_stash", "(", "path", ")", "else", ":", "new_path", "=", "self", ".", "_get_file_stash", "(", "path", ")", "self", ".", "_moves", ".", "append", "(", "(", "path", ",", "new_path", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "os", ".", "path", ".", "isdir", "(", "new_path", ")", ":", "# If we're moving a directory, we need to", "# remove the destination first or else it will be", "# moved to inside the existing directory.", "# We just created new_path ourselves, so it will", "# be removable.", "os", ".", "rmdir", "(", "new_path", ")", "renames", "(", "path", ",", "new_path", ")", "return", "new_path" ]
Stashes the directory or file and returns its new location.
[ "Stashes", "the", "directory", "or", "file", "and", "returns", "its", "new", "location", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L241-L258
24,885
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
StashedUninstallPathSet.commit
def commit(self): """Commits the uninstall by removing stashed files.""" for _, save_dir in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {}
python
def commit(self): """Commits the uninstall by removing stashed files.""" for _, save_dir in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {}
[ "def", "commit", "(", "self", ")", ":", "for", "_", ",", "save_dir", "in", "self", ".", "_save_dirs", ".", "items", "(", ")", ":", "save_dir", ".", "cleanup", "(", ")", "self", ".", "_moves", "=", "[", "]", "self", ".", "_save_dirs", "=", "{", "}" ]
Commits the uninstall by removing stashed files.
[ "Commits", "the", "uninstall", "by", "removing", "stashed", "files", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L260-L265
24,886
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
StashedUninstallPathSet.rollback
def rollback(self): """Undoes the uninstall by moving stashed files back.""" for p in self._moves: logging.info("Moving to %s\n from %s", *p) for new_path, path in self._moves: try: logger.debug('Replacing %s from %s', new_path, path) if os.path.isfile(new_path): os.unlink(new_path) elif os.path.isdir(new_path): rmtree(new_path) renames(path, new_path) except OSError as ex: logger.error("Failed to restore %s", new_path) logger.debug("Exception: %s", ex) self.commit()
python
def rollback(self): """Undoes the uninstall by moving stashed files back.""" for p in self._moves: logging.info("Moving to %s\n from %s", *p) for new_path, path in self._moves: try: logger.debug('Replacing %s from %s', new_path, path) if os.path.isfile(new_path): os.unlink(new_path) elif os.path.isdir(new_path): rmtree(new_path) renames(path, new_path) except OSError as ex: logger.error("Failed to restore %s", new_path) logger.debug("Exception: %s", ex) self.commit()
[ "def", "rollback", "(", "self", ")", ":", "for", "p", "in", "self", ".", "_moves", ":", "logging", ".", "info", "(", "\"Moving to %s\\n from %s\"", ",", "*", "p", ")", "for", "new_path", ",", "path", "in", "self", ".", "_moves", ":", "try", ":", "logger", ".", "debug", "(", "'Replacing %s from %s'", ",", "new_path", ",", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "new_path", ")", ":", "os", ".", "unlink", "(", "new_path", ")", "elif", "os", ".", "path", ".", "isdir", "(", "new_path", ")", ":", "rmtree", "(", "new_path", ")", "renames", "(", "path", ",", "new_path", ")", "except", "OSError", "as", "ex", ":", "logger", ".", "error", "(", "\"Failed to restore %s\"", ",", "new_path", ")", "logger", ".", "debug", "(", "\"Exception: %s\"", ",", "ex", ")", "self", ".", "commit", "(", ")" ]
Undoes the uninstall by moving stashed files back.
[ "Undoes", "the", "uninstall", "by", "moving", "stashed", "files", "back", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L267-L284
24,887
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
UninstallPathSet._allowed_to_proceed
def _allowed_to_proceed(self, verbose): """Display which files would be deleted and prompt for confirmation """ def _display(msg, paths): if not paths: return logger.info(msg) with indent_log(): for path in sorted(compact(paths)): logger.info(path) if not verbose: will_remove, will_skip = compress_for_output_listing(self.paths) else: # In verbose mode, display all the files that are going to be # deleted. will_remove = list(self.paths) will_skip = set() _display('Would remove:', will_remove) _display('Would not remove (might be manually added):', will_skip) _display('Would not remove (outside of prefix):', self._refuse) if verbose: _display('Will actually move:', compress_for_rename(self.paths)) return ask('Proceed (y/n)? ', ('y', 'n')) == 'y'
python
def _allowed_to_proceed(self, verbose): """Display which files would be deleted and prompt for confirmation """ def _display(msg, paths): if not paths: return logger.info(msg) with indent_log(): for path in sorted(compact(paths)): logger.info(path) if not verbose: will_remove, will_skip = compress_for_output_listing(self.paths) else: # In verbose mode, display all the files that are going to be # deleted. will_remove = list(self.paths) will_skip = set() _display('Would remove:', will_remove) _display('Would not remove (might be manually added):', will_skip) _display('Would not remove (outside of prefix):', self._refuse) if verbose: _display('Will actually move:', compress_for_rename(self.paths)) return ask('Proceed (y/n)? ', ('y', 'n')) == 'y'
[ "def", "_allowed_to_proceed", "(", "self", ",", "verbose", ")", ":", "def", "_display", "(", "msg", ",", "paths", ")", ":", "if", "not", "paths", ":", "return", "logger", ".", "info", "(", "msg", ")", "with", "indent_log", "(", ")", ":", "for", "path", "in", "sorted", "(", "compact", "(", "paths", ")", ")", ":", "logger", ".", "info", "(", "path", ")", "if", "not", "verbose", ":", "will_remove", ",", "will_skip", "=", "compress_for_output_listing", "(", "self", ".", "paths", ")", "else", ":", "# In verbose mode, display all the files that are going to be", "# deleted.", "will_remove", "=", "list", "(", "self", ".", "paths", ")", "will_skip", "=", "set", "(", ")", "_display", "(", "'Would remove:'", ",", "will_remove", ")", "_display", "(", "'Would not remove (might be manually added):'", ",", "will_skip", ")", "_display", "(", "'Would not remove (outside of prefix):'", ",", "self", ".", "_refuse", ")", "if", "verbose", ":", "_display", "(", "'Will actually move:'", ",", "compress_for_rename", "(", "self", ".", "paths", ")", ")", "return", "ask", "(", "'Proceed (y/n)? '", ",", "(", "'y'", ",", "'n'", ")", ")", "==", "'y'" ]
Display which files would be deleted and prompt for confirmation
[ "Display", "which", "files", "would", "be", "deleted", "and", "prompt", "for", "confirmation" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L368-L395
24,888
pypa/pipenv
pipenv/vendor/pexpect/utils.py
is_executable_file
def is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. """ # follow symlinks, fpath = os.path.realpath(path) if not os.path.isfile(fpath): # non-files (directories, fifo, etc.) return False mode = os.stat(fpath).st_mode if (sys.platform.startswith('sunos') and os.getuid() == 0): # When root on Solaris, os.X_OK is True for *all* files, irregardless # of their executability -- instead, any permission bit of any user, # group, or other is fine enough. # # (This may be true for other "Unix98" OS's such as HP-UX and AIX) return bool(mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) return os.access(fpath, os.X_OK)
python
def is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. """ # follow symlinks, fpath = os.path.realpath(path) if not os.path.isfile(fpath): # non-files (directories, fifo, etc.) return False mode = os.stat(fpath).st_mode if (sys.platform.startswith('sunos') and os.getuid() == 0): # When root on Solaris, os.X_OK is True for *all* files, irregardless # of their executability -- instead, any permission bit of any user, # group, or other is fine enough. # # (This may be true for other "Unix98" OS's such as HP-UX and AIX) return bool(mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) return os.access(fpath, os.X_OK)
[ "def", "is_executable_file", "(", "path", ")", ":", "# follow symlinks,", "fpath", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "fpath", ")", ":", "# non-files (directories, fifo, etc.)", "return", "False", "mode", "=", "os", ".", "stat", "(", "fpath", ")", ".", "st_mode", "if", "(", "sys", ".", "platform", ".", "startswith", "(", "'sunos'", ")", "and", "os", ".", "getuid", "(", ")", "==", "0", ")", ":", "# When root on Solaris, os.X_OK is True for *all* files, irregardless", "# of their executability -- instead, any permission bit of any user,", "# group, or other is fine enough.", "#", "# (This may be true for other \"Unix98\" OS's such as HP-UX and AIX)", "return", "bool", "(", "mode", "&", "(", "stat", ".", "S_IXUSR", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IXOTH", ")", ")", "return", "os", ".", "access", "(", "fpath", ",", "os", ".", "X_OK", ")" ]
Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
[ "Checks", "that", "path", "is", "an", "executable", "regular", "file", "or", "a", "symlink", "towards", "one", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L20-L45
24,889
pypa/pipenv
pipenv/vendor/pexpect/utils.py
split_command_line
def split_command_line(command_line): '''This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. ''' arg_list = [] arg = '' # Constants to name the states we can be in. state_basic = 0 state_esc = 1 state_singlequote = 2 state_doublequote = 3 # The state when consuming whitespace between commands. state_whitespace = 4 state = state_basic for c in command_line: if state == state_basic or state == state_whitespace: if c == '\\': # Escape the next character state = state_esc elif c == r"'": # Handle single quote state = state_singlequote elif c == r'"': # Handle double quote state = state_doublequote elif c.isspace(): # Add arg to arg_list if we aren't in the middle of whitespace. if state == state_whitespace: # Do nothing. None else: arg_list.append(arg) arg = '' state = state_whitespace else: arg = arg + c state = state_basic elif state == state_esc: arg = arg + c state = state_basic elif state == state_singlequote: if c == r"'": state = state_basic else: arg = arg + c elif state == state_doublequote: if c == r'"': state = state_basic else: arg = arg + c if arg != '': arg_list.append(arg) return arg_list
python
def split_command_line(command_line): '''This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line. ''' arg_list = [] arg = '' # Constants to name the states we can be in. state_basic = 0 state_esc = 1 state_singlequote = 2 state_doublequote = 3 # The state when consuming whitespace between commands. state_whitespace = 4 state = state_basic for c in command_line: if state == state_basic or state == state_whitespace: if c == '\\': # Escape the next character state = state_esc elif c == r"'": # Handle single quote state = state_singlequote elif c == r'"': # Handle double quote state = state_doublequote elif c.isspace(): # Add arg to arg_list if we aren't in the middle of whitespace. if state == state_whitespace: # Do nothing. None else: arg_list.append(arg) arg = '' state = state_whitespace else: arg = arg + c state = state_basic elif state == state_esc: arg = arg + c state = state_basic elif state == state_singlequote: if c == r"'": state = state_basic else: arg = arg + c elif state == state_doublequote: if c == r'"': state = state_basic else: arg = arg + c if arg != '': arg_list.append(arg) return arg_list
[ "def", "split_command_line", "(", "command_line", ")", ":", "arg_list", "=", "[", "]", "arg", "=", "''", "# Constants to name the states we can be in.", "state_basic", "=", "0", "state_esc", "=", "1", "state_singlequote", "=", "2", "state_doublequote", "=", "3", "# The state when consuming whitespace between commands.", "state_whitespace", "=", "4", "state", "=", "state_basic", "for", "c", "in", "command_line", ":", "if", "state", "==", "state_basic", "or", "state", "==", "state_whitespace", ":", "if", "c", "==", "'\\\\'", ":", "# Escape the next character", "state", "=", "state_esc", "elif", "c", "==", "r\"'\"", ":", "# Handle single quote", "state", "=", "state_singlequote", "elif", "c", "==", "r'\"'", ":", "# Handle double quote", "state", "=", "state_doublequote", "elif", "c", ".", "isspace", "(", ")", ":", "# Add arg to arg_list if we aren't in the middle of whitespace.", "if", "state", "==", "state_whitespace", ":", "# Do nothing.", "None", "else", ":", "arg_list", ".", "append", "(", "arg", ")", "arg", "=", "''", "state", "=", "state_whitespace", "else", ":", "arg", "=", "arg", "+", "c", "state", "=", "state_basic", "elif", "state", "==", "state_esc", ":", "arg", "=", "arg", "+", "c", "state", "=", "state_basic", "elif", "state", "==", "state_singlequote", ":", "if", "c", "==", "r\"'\"", ":", "state", "=", "state_basic", "else", ":", "arg", "=", "arg", "+", "c", "elif", "state", "==", "state_doublequote", ":", "if", "c", "==", "r'\"'", ":", "state", "=", "state_basic", "else", ":", "arg", "=", "arg", "+", "c", "if", "arg", "!=", "''", ":", "arg_list", ".", "append", "(", "arg", ")", "return", "arg_list" ]
This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line.
[ "This", "splits", "a", "command", "line", "into", "a", "list", "of", "arguments", ".", "It", "splits", "arguments", "on", "spaces", "but", "handles", "embedded", "quotes", "doublequotes", "and", "escaped", "characters", ".", "It", "s", "impossible", "to", "do", "this", "with", "a", "regular", "expression", "so", "I", "wrote", "a", "little", "state", "machine", "to", "parse", "the", "command", "line", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L69-L127
24,890
pypa/pipenv
pipenv/vendor/pexpect/utils.py
poll_ignore_interrupts
def poll_ignore_interrupts(fds, timeout=None): '''Simple wrapper around poll to register file descriptors and ignore signals.''' if timeout is not None: end_time = time.time() + timeout poller = select.poll() for fd in fds: poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) while True: try: timeout_ms = None if timeout is None else timeout * 1000 results = poller.poll(timeout_ms) return [afd for afd, _ in results] except InterruptedError: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: # if we loop back we have to subtract the # amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return [] else: # something else caused the select.error, so # this actually is an exception. raise
python
def poll_ignore_interrupts(fds, timeout=None): '''Simple wrapper around poll to register file descriptors and ignore signals.''' if timeout is not None: end_time = time.time() + timeout poller = select.poll() for fd in fds: poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) while True: try: timeout_ms = None if timeout is None else timeout * 1000 results = poller.poll(timeout_ms) return [afd for afd, _ in results] except InterruptedError: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: # if we loop back we have to subtract the # amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return [] else: # something else caused the select.error, so # this actually is an exception. raise
[ "def", "poll_ignore_interrupts", "(", "fds", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "poller", "=", "select", ".", "poll", "(", ")", "for", "fd", "in", "fds", ":", "poller", ".", "register", "(", "fd", ",", "select", ".", "POLLIN", "|", "select", ".", "POLLPRI", "|", "select", ".", "POLLHUP", "|", "select", ".", "POLLERR", ")", "while", "True", ":", "try", ":", "timeout_ms", "=", "None", "if", "timeout", "is", "None", "else", "timeout", "*", "1000", "results", "=", "poller", ".", "poll", "(", "timeout_ms", ")", "return", "[", "afd", "for", "afd", ",", "_", "in", "results", "]", "except", "InterruptedError", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ":", "# if we loop back we have to subtract the", "# amount of time we already waited.", "if", "timeout", "is", "not", "None", ":", "timeout", "=", "end_time", "-", "time", ".", "time", "(", ")", "if", "timeout", "<", "0", ":", "return", "[", "]", "else", ":", "# something else caused the select.error, so", "# this actually is an exception.", "raise" ]
Simple wrapper around poll to register file descriptors and ignore signals.
[ "Simple", "wrapper", "around", "poll", "to", "register", "file", "descriptors", "and", "ignore", "signals", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L159-L187
24,891
pypa/pipenv
pipenv/vendor/distlib/version.py
_suggest_semantic_version
def _suggest_semantic_version(s): """ Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything. """ result = s.strip().lower() for pat, repl in _REPLACEMENTS: result = pat.sub(repl, result) if not result: result = '0.0.0' # Now look for numeric prefix, and separate it out from # the rest. #import pdb; pdb.set_trace() m = _NUMERIC_PREFIX.match(result) if not m: prefix = '0.0.0' suffix = result else: prefix = m.groups()[0].split('.') prefix = [int(i) for i in prefix] while len(prefix) < 3: prefix.append(0) if len(prefix) == 3: suffix = result[m.end():] else: suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():] prefix = prefix[:3] prefix = '.'.join([str(i) for i in prefix]) suffix = suffix.strip() if suffix: #import pdb; pdb.set_trace() # massage the suffix. for pat, repl in _SUFFIX_REPLACEMENTS: suffix = pat.sub(repl, suffix) if not suffix: result = prefix else: sep = '-' if 'dev' in suffix else '+' result = prefix + sep + suffix if not is_semver(result): result = None return result
python
def _suggest_semantic_version(s): """ Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything. """ result = s.strip().lower() for pat, repl in _REPLACEMENTS: result = pat.sub(repl, result) if not result: result = '0.0.0' # Now look for numeric prefix, and separate it out from # the rest. #import pdb; pdb.set_trace() m = _NUMERIC_PREFIX.match(result) if not m: prefix = '0.0.0' suffix = result else: prefix = m.groups()[0].split('.') prefix = [int(i) for i in prefix] while len(prefix) < 3: prefix.append(0) if len(prefix) == 3: suffix = result[m.end():] else: suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():] prefix = prefix[:3] prefix = '.'.join([str(i) for i in prefix]) suffix = suffix.strip() if suffix: #import pdb; pdb.set_trace() # massage the suffix. for pat, repl in _SUFFIX_REPLACEMENTS: suffix = pat.sub(repl, suffix) if not suffix: result = prefix else: sep = '-' if 'dev' in suffix else '+' result = prefix + sep + suffix if not is_semver(result): result = None return result
[ "def", "_suggest_semantic_version", "(", "s", ")", ":", "result", "=", "s", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "pat", ",", "repl", "in", "_REPLACEMENTS", ":", "result", "=", "pat", ".", "sub", "(", "repl", ",", "result", ")", "if", "not", "result", ":", "result", "=", "'0.0.0'", "# Now look for numeric prefix, and separate it out from", "# the rest.", "#import pdb; pdb.set_trace()", "m", "=", "_NUMERIC_PREFIX", ".", "match", "(", "result", ")", "if", "not", "m", ":", "prefix", "=", "'0.0.0'", "suffix", "=", "result", "else", ":", "prefix", "=", "m", ".", "groups", "(", ")", "[", "0", "]", ".", "split", "(", "'.'", ")", "prefix", "=", "[", "int", "(", "i", ")", "for", "i", "in", "prefix", "]", "while", "len", "(", "prefix", ")", "<", "3", ":", "prefix", ".", "append", "(", "0", ")", "if", "len", "(", "prefix", ")", "==", "3", ":", "suffix", "=", "result", "[", "m", ".", "end", "(", ")", ":", "]", "else", ":", "suffix", "=", "'.'", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "prefix", "[", "3", ":", "]", "]", ")", "+", "result", "[", "m", ".", "end", "(", ")", ":", "]", "prefix", "=", "prefix", "[", ":", "3", "]", "prefix", "=", "'.'", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "prefix", "]", ")", "suffix", "=", "suffix", ".", "strip", "(", ")", "if", "suffix", ":", "#import pdb; pdb.set_trace()", "# massage the suffix.", "for", "pat", ",", "repl", "in", "_SUFFIX_REPLACEMENTS", ":", "suffix", "=", "pat", ".", "sub", "(", "repl", ",", "suffix", ")", "if", "not", "suffix", ":", "result", "=", "prefix", "else", ":", "sep", "=", "'-'", "if", "'dev'", "in", "suffix", "else", "'+'", "result", "=", "prefix", "+", "sep", "+", "suffix", "if", "not", "is_semver", "(", "result", ")", ":", "result", "=", "None", "return", "result" ]
Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything.
[ "Try", "to", "suggest", "a", "semantic", "form", "for", "a", "version", "for", "which", "_suggest_normalized_version", "couldn", "t", "come", "up", "with", "anything", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L406-L449
24,892
pypa/pipenv
pipenv/vendor/distlib/version.py
_suggest_normalized_version
def _suggest_normalized_version(s): """Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. """ try: _normalized_key(s) return s # already rational except UnsupportedVersionError: pass rs = s.lower() # part of this could use maketrans for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), ('beta', 'b'), ('rc', 'c'), ('-final', ''), ('-pre', 'c'), ('-release', ''), ('.release', ''), ('-stable', ''), ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), ('final', '')): rs = rs.replace(orig, repl) # if something ends with dev or pre, we add a 0 rs = re.sub(r"pre$", r"pre0", rs) rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the # version, that is probably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) # 1.0-dev-r371 -> 1.0.dev371 # 0.1-dev-r79 -> 0.1.dev79 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) # Clean: v0.3, v1.0 if rs.startswith('v'): rs = rs[1:] # Clean leading '0's on numbers. #TODO: unintended side-effect on, e.g., "2003.05.09" # PyPI stats: 77 (~2%) better rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers # zero. # PyPI stats: 245 (7.56%) better rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) # the 'dev-rNNN' tag is a dev tag rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) # clean the - when used as a pre delimiter rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) # a terminal "dev" or "devel" can be changed into ".dev0" rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) # a terminal "dev" can be changed into ".dev0" rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) # a terminal "final" or "stable" can be removed rs = re.sub(r"(final|stable)$", "", rs) # The 'r' and the '-' tags are post release tags # 0.4a1.r10 -> 0.4a1.post10 # 0.9.33-17222 -> 0.9.33.post17222 # 0.9.33-r17222 -> 0.9.33.post17222 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) # Clean 'r' instead of 'dev' usage: # 0.9.33+r17222 -> 0.9.33.dev17222 # 1.0dev123 -> 1.0.dev123 # 1.0.git123 -> 1.0.dev123 # 1.0.bzr123 -> 1.0.dev123 # 0.1a0dev.123 -> 0.1a0.dev123 # PyPI stats: ~150 (~4%) better rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: # 0.2.pre1 -> 0.2c1 # 0.2-c1 -> 0.2c1 # 1.0preview123 -> 1.0c123 # PyPI stats: ~21 (0.62%) better rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) # Tcl/Tk uses "px" for their post release markers rs = re.sub(r"p(\d+)$", r".post\1", rs) try: _normalized_key(rs) except UnsupportedVersionError: rs = None return rs
python
def _suggest_normalized_version(s): """Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. """ try: _normalized_key(s) return s # already rational except UnsupportedVersionError: pass rs = s.lower() # part of this could use maketrans for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), ('beta', 'b'), ('rc', 'c'), ('-final', ''), ('-pre', 'c'), ('-release', ''), ('.release', ''), ('-stable', ''), ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), ('final', '')): rs = rs.replace(orig, repl) # if something ends with dev or pre, we add a 0 rs = re.sub(r"pre$", r"pre0", rs) rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the # version, that is probably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) # 1.0-dev-r371 -> 1.0.dev371 # 0.1-dev-r79 -> 0.1.dev79 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) # Clean: v0.3, v1.0 if rs.startswith('v'): rs = rs[1:] # Clean leading '0's on numbers. #TODO: unintended side-effect on, e.g., "2003.05.09" # PyPI stats: 77 (~2%) better rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers # zero. # PyPI stats: 245 (7.56%) better rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) # the 'dev-rNNN' tag is a dev tag rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) # clean the - when used as a pre delimiter rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) # a terminal "dev" or "devel" can be changed into ".dev0" rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) # a terminal "dev" can be changed into ".dev0" rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) # a terminal "final" or "stable" can be removed rs = re.sub(r"(final|stable)$", "", rs) # The 'r' and the '-' tags are post release tags # 0.4a1.r10 -> 0.4a1.post10 # 0.9.33-17222 -> 0.9.33.post17222 # 0.9.33-r17222 -> 0.9.33.post17222 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) # Clean 'r' instead of 'dev' usage: # 0.9.33+r17222 -> 0.9.33.dev17222 # 1.0dev123 -> 1.0.dev123 # 1.0.git123 -> 1.0.dev123 # 1.0.bzr123 -> 1.0.dev123 # 0.1a0dev.123 -> 0.1a0.dev123 # PyPI stats: ~150 (~4%) better rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: # 0.2.pre1 -> 0.2c1 # 0.2-c1 -> 0.2c1 # 1.0preview123 -> 1.0c123 # PyPI stats: ~21 (0.62%) better rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) # Tcl/Tk uses "px" for their post release markers rs = re.sub(r"p(\d+)$", r".post\1", rs) try: _normalized_key(rs) except UnsupportedVersionError: rs = None return rs
[ "def", "_suggest_normalized_version", "(", "s", ")", ":", "try", ":", "_normalized_key", "(", "s", ")", "return", "s", "# already rational", "except", "UnsupportedVersionError", ":", "pass", "rs", "=", "s", ".", "lower", "(", ")", "# part of this could use maketrans", "for", "orig", ",", "repl", "in", "(", "(", "'-alpha'", ",", "'a'", ")", ",", "(", "'-beta'", ",", "'b'", ")", ",", "(", "'alpha'", ",", "'a'", ")", ",", "(", "'beta'", ",", "'b'", ")", ",", "(", "'rc'", ",", "'c'", ")", ",", "(", "'-final'", ",", "''", ")", ",", "(", "'-pre'", ",", "'c'", ")", ",", "(", "'-release'", ",", "''", ")", ",", "(", "'.release'", ",", "''", ")", ",", "(", "'-stable'", ",", "''", ")", ",", "(", "'+'", ",", "'.'", ")", ",", "(", "'_'", ",", "'.'", ")", ",", "(", "' '", ",", "''", ")", ",", "(", "'.final'", ",", "''", ")", ",", "(", "'final'", ",", "''", ")", ")", ":", "rs", "=", "rs", ".", "replace", "(", "orig", ",", "repl", ")", "# if something ends with dev or pre, we add a 0", "rs", "=", "re", ".", "sub", "(", "r\"pre$\"", ",", "r\"pre0\"", ",", "rs", ")", "rs", "=", "re", ".", "sub", "(", "r\"dev$\"", ",", "r\"dev0\"", ",", "rs", ")", "# if we have something like \"b-2\" or \"a.2\" at the end of the", "# version, that is probably beta, alpha, etc", "# let's remove the dash or dot", "rs", "=", "re", ".", "sub", "(", "r\"([abc]|rc)[\\-\\.](\\d+)$\"", ",", "r\"\\1\\2\"", ",", "rs", ")", "# 1.0-dev-r371 -> 1.0.dev371", "# 0.1-dev-r79 -> 0.1.dev79", "rs", "=", "re", ".", "sub", "(", "r\"[\\-\\.](dev)[\\-\\.]?r?(\\d+)$\"", ",", "r\".\\1\\2\"", ",", "rs", ")", "# Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1", "rs", "=", "re", ".", "sub", "(", "r\"[.~]?([abc])\\.?\"", ",", "r\"\\1\"", ",", "rs", ")", "# Clean: v0.3, v1.0", "if", "rs", ".", "startswith", "(", "'v'", ")", ":", "rs", "=", "rs", "[", "1", ":", "]", "# Clean leading '0's on numbers.", "#TODO: unintended side-effect on, e.g., \"2003.05.09\"", "# PyPI stats: 77 (~2%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\b0+(\\d+)(?!\\d)\"", ",", "r\"\\1\"", ",", "rs", ")", "# Clean a/b/c with no version. E.g. \"1.0a\" -> \"1.0a0\". Setuptools infers", "# zero.", "# PyPI stats: 245 (7.56%) better", "rs", "=", "re", ".", "sub", "(", "r\"(\\d+[abc])$\"", ",", "r\"\\g<1>0\"", ",", "rs", ")", "# the 'dev-rNNN' tag is a dev tag", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(dev-r|dev\\.r)\\.?(\\d+)$\"", ",", "r\".dev\\2\"", ",", "rs", ")", "# clean the - when used as a pre delimiter", "rs", "=", "re", ".", "sub", "(", "r\"-(a|b|c)(\\d+)$\"", ",", "r\"\\1\\2\"", ",", "rs", ")", "# a terminal \"dev\" or \"devel\" can be changed into \".dev0\"", "rs", "=", "re", ".", "sub", "(", "r\"[\\.\\-](dev|devel)$\"", ",", "r\".dev0\"", ",", "rs", ")", "# a terminal \"dev\" can be changed into \".dev0\"", "rs", "=", "re", ".", "sub", "(", "r\"(?![\\.\\-])dev$\"", ",", "r\".dev0\"", ",", "rs", ")", "# a terminal \"final\" or \"stable\" can be removed", "rs", "=", "re", ".", "sub", "(", "r\"(final|stable)$\"", ",", "\"\"", ",", "rs", ")", "# The 'r' and the '-' tags are post release tags", "# 0.4a1.r10 -> 0.4a1.post10", "# 0.9.33-17222 -> 0.9.33.post17222", "# 0.9.33-r17222 -> 0.9.33.post17222", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(r|-|-r)\\.?(\\d+)$\"", ",", "r\".post\\2\"", ",", "rs", ")", "# Clean 'r' instead of 'dev' usage:", "# 0.9.33+r17222 -> 0.9.33.dev17222", "# 1.0dev123 -> 1.0.dev123", "# 1.0.git123 -> 1.0.dev123", "# 1.0.bzr123 -> 1.0.dev123", "# 0.1a0dev.123 -> 0.1a0.dev123", "# PyPI stats: ~150 (~4%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(dev|git|bzr)\\.?(\\d+)$\"", ",", "r\".dev\\2\"", ",", "rs", ")", "# Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:", "# 0.2.pre1 -> 0.2c1", "# 0.2-c1 -> 0.2c1", "# 1.0preview123 -> 1.0c123", "# PyPI stats: ~21 (0.62%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(pre|preview|-c)(\\d+)$\"", ",", "r\"c\\g<2>\"", ",", "rs", ")", "# Tcl/Tk uses \"px\" for their post release markers", "rs", "=", "re", ".", "sub", "(", "r\"p(\\d+)$\"", ",", "r\".post\\1\"", ",", "rs", ")", "try", ":", "_normalized_key", "(", "rs", ")", "except", "UnsupportedVersionError", ":", "rs", "=", "None", "return", "rs" ]
Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one.
[ "Suggest", "a", "normalized", "version", "close", "to", "the", "given", "version", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L452-L560
24,893
pypa/pipenv
pipenv/vendor/distlib/version.py
Matcher.match
def match(self, version): """ Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) for operator, constraint, prefix in self._parts: f = self._operators.get(operator) if isinstance(f, string_types): f = getattr(self, f) if not f: msg = ('%r not implemented ' 'for %s' % (operator, self.__class__.__name__)) raise NotImplementedError(msg) if not f(version, constraint, prefix): return False return True
python
def match(self, version): """ Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) for operator, constraint, prefix in self._parts: f = self._operators.get(operator) if isinstance(f, string_types): f = getattr(self, f) if not f: msg = ('%r not implemented ' 'for %s' % (operator, self.__class__.__name__)) raise NotImplementedError(msg) if not f(version, constraint, prefix): return False return True
[ "def", "match", "(", "self", ",", "version", ")", ":", "if", "isinstance", "(", "version", ",", "string_types", ")", ":", "version", "=", "self", ".", "version_class", "(", "version", ")", "for", "operator", ",", "constraint", ",", "prefix", "in", "self", ".", "_parts", ":", "f", "=", "self", ".", "_operators", ".", "get", "(", "operator", ")", "if", "isinstance", "(", "f", ",", "string_types", ")", ":", "f", "=", "getattr", "(", "self", ",", "f", ")", "if", "not", "f", ":", "msg", "=", "(", "'%r not implemented '", "'for %s'", "%", "(", "operator", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "raise", "NotImplementedError", "(", "msg", ")", "if", "not", "f", "(", "version", ",", "constraint", ",", "prefix", ")", ":", "return", "False", "return", "True" ]
Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance.
[ "Check", "if", "the", "provided", "version", "matches", "the", "constraints", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/version.py#L129-L148
24,894
pypa/pipenv
pipenv/vendor/dotenv/main.py
_walk_to_root
def _walk_to_root(path): """ Yield directories starting from the given directory up to the root """ if not os.path.exists(path): raise IOError('Starting path not found') if os.path.isfile(path): path = os.path.dirname(path) last_dir = None current_dir = os.path.abspath(path) while last_dir != current_dir: yield current_dir parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) last_dir, current_dir = current_dir, parent_dir
python
def _walk_to_root(path): """ Yield directories starting from the given directory up to the root """ if not os.path.exists(path): raise IOError('Starting path not found') if os.path.isfile(path): path = os.path.dirname(path) last_dir = None current_dir = os.path.abspath(path) while last_dir != current_dir: yield current_dir parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) last_dir, current_dir = current_dir, parent_dir
[ "def", "_walk_to_root", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "IOError", "(", "'Starting path not found'", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "last_dir", "=", "None", "current_dir", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "while", "last_dir", "!=", "current_dir", ":", "yield", "current_dir", "parent_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "os", ".", "path", ".", "pardir", ")", ")", "last_dir", ",", "current_dir", "=", "current_dir", ",", "parent_dir" ]
Yield directories starting from the given directory up to the root
[ "Yield", "directories", "starting", "from", "the", "given", "directory", "up", "to", "the", "root" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L260-L275
24,895
pypa/pipenv
pipenv/vendor/dotenv/main.py
run_command
def run_command(command, env): """Run command in sub process. Runs the command in a sub process with the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additional environment variables Returns ------- int The return code of the command """ # copy the current environment variables and add the vales from # `env` cmd_env = os.environ.copy() cmd_env.update(env) p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env) _, _ = p.communicate() return p.returncode
python
def run_command(command, env): """Run command in sub process. Runs the command in a sub process with the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additional environment variables Returns ------- int The return code of the command """ # copy the current environment variables and add the vales from # `env` cmd_env = os.environ.copy() cmd_env.update(env) p = Popen(command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env) _, _ = p.communicate() return p.returncode
[ "def", "run_command", "(", "command", ",", "env", ")", ":", "# copy the current environment variables and add the vales from", "# `env`", "cmd_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "cmd_env", ".", "update", "(", "env", ")", "p", "=", "Popen", "(", "command", ",", "universal_newlines", "=", "True", ",", "bufsize", "=", "0", ",", "shell", "=", "False", ",", "env", "=", "cmd_env", ")", "_", ",", "_", "=", "p", ".", "communicate", "(", ")", "return", "p", ".", "returncode" ]
Run command in sub process. Runs the command in a sub process with the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additional environment variables Returns ------- int The return code of the command
[ "Run", "command", "in", "sub", "process", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L317-L348
24,896
pypa/pipenv
pipenv/vendor/dotenv/main.py
DotEnv.dict
def dict(self): """Return dotenv as dict""" if self._dict: return self._dict values = OrderedDict(self.parse()) self._dict = resolve_nested_variables(values) return self._dict
python
def dict(self): """Return dotenv as dict""" if self._dict: return self._dict values = OrderedDict(self.parse()) self._dict = resolve_nested_variables(values) return self._dict
[ "def", "dict", "(", "self", ")", ":", "if", "self", ".", "_dict", ":", "return", "self", ".", "_dict", "values", "=", "OrderedDict", "(", "self", ".", "parse", "(", ")", ")", "self", ".", "_dict", "=", "resolve_nested_variables", "(", "values", ")", "return", "self", ".", "_dict" ]
Return dotenv as dict
[ "Return", "dotenv", "as", "dict" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L110-L117
24,897
pypa/pipenv
pipenv/vendor/dotenv/main.py
DotEnv.set_as_environment_variables
def set_as_environment_variables(self, override=False): """ Load the current dotenv as system environemt variable. """ for k, v in self.dict().items(): if k in os.environ and not override: continue # With Python2 on Windows, force environment variables to str to avoid # "TypeError: environment can only contain strings" in Python's subprocess.py. if PY2 and WIN: if isinstance(k, text_type) or isinstance(v, text_type): k = k.encode('ascii') v = v.encode('ascii') os.environ[k] = v return True
python
def set_as_environment_variables(self, override=False): """ Load the current dotenv as system environemt variable. """ for k, v in self.dict().items(): if k in os.environ and not override: continue # With Python2 on Windows, force environment variables to str to avoid # "TypeError: environment can only contain strings" in Python's subprocess.py. if PY2 and WIN: if isinstance(k, text_type) or isinstance(v, text_type): k = k.encode('ascii') v = v.encode('ascii') os.environ[k] = v return True
[ "def", "set_as_environment_variables", "(", "self", ",", "override", "=", "False", ")", ":", "for", "k", ",", "v", "in", "self", ".", "dict", "(", ")", ".", "items", "(", ")", ":", "if", "k", "in", "os", ".", "environ", "and", "not", "override", ":", "continue", "# With Python2 on Windows, force environment variables to str to avoid", "# \"TypeError: environment can only contain strings\" in Python's subprocess.py.", "if", "PY2", "and", "WIN", ":", "if", "isinstance", "(", "k", ",", "text_type", ")", "or", "isinstance", "(", "v", ",", "text_type", ")", ":", "k", "=", "k", ".", "encode", "(", "'ascii'", ")", "v", "=", "v", ".", "encode", "(", "'ascii'", ")", "os", ".", "environ", "[", "k", "]", "=", "v", "return", "True" ]
Load the current dotenv as system environemt variable.
[ "Load", "the", "current", "dotenv", "as", "system", "environemt", "variable", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L125-L140
24,898
pypa/pipenv
pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py
inject_into_urllib3
def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True
python
def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True
[ "def", "inject_into_urllib3", "(", ")", ":", "_validate_dependencies_met", "(", ")", "util", ".", "ssl_", ".", "SSLContext", "=", "PyOpenSSLContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "IS_PYOPENSSL", "=", "True", "util", ".", "ssl_", ".", "IS_PYOPENSSL", "=", "True" ]
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
[ "Monkey", "-", "patch", "urllib3", "with", "PyOpenSSL", "-", "backed", "SSL", "-", "support", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L115-L124
24,899
pypa/pipenv
pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py
_validate_dependencies_met
def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError("'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer.") # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError("'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer.")
python
def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError("'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer.") # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError("'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer.")
[ "def", "_validate_dependencies_met", "(", ")", ":", "# Method added in `cryptography==1.1`; not available in older versions", "from", "cryptography", ".", "x509", ".", "extensions", "import", "Extensions", "if", "getattr", "(", "Extensions", ",", "\"get_extension_for_class\"", ",", "None", ")", "is", "None", ":", "raise", "ImportError", "(", "\"'cryptography' module missing required functionality. \"", "\"Try upgrading to v1.3.4 or newer.\"", ")", "# pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509", "# attribute is only present on those versions.", "from", "OpenSSL", ".", "crypto", "import", "X509", "x509", "=", "X509", "(", ")", "if", "getattr", "(", "x509", ",", "\"_x509\"", ",", "None", ")", "is", "None", ":", "raise", "ImportError", "(", "\"'pyOpenSSL' module missing required functionality. \"", "\"Try upgrading to v0.14 or newer.\"", ")" ]
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met.
[ "Verifies", "that", "PyOpenSSL", "s", "package", "-", "level", "dependencies", "have", "been", "met", ".", "Throws", "ImportError", "if", "they", "are", "not", "met", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/urllib3/contrib/pyopenssl.py#L137-L154