partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Project.register_proper_name
Registers a proper name to the database.
pipenv/project.py
def register_proper_name(self, name): """Registers a proper name to the database.""" with self.proper_names_db_path.open("a") as f: f.write(u"{0}\n".format(name))
def register_proper_name(self, name): """Registers a proper name to the database.""" with self.proper_names_db_path.open("a") as f: f.write(u"{0}\n".format(name))
[ "Registers", "a", "proper", "name", "to", "the", "database", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L462-L465
[ "def", "register_proper_name", "(", "self", ",", "name", ")", ":", "with", "self", ".", "proper_names_db_path", ".", "open", "(", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "u\"{0}\\n\"", ".", "format", "(", "name", ")", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.parsed_pipfile
Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)
pipenv/project.py
def parsed_pipfile(self): """Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)""" contents = self.read_pipfile() # use full contents to get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key not in _pipfile_cache: parsed = self._parse_pipfile(contents) _pipfile_cache[cache_key] = parsed return _pipfile_cache[cache_key]
def parsed_pipfile(self): """Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)""" contents = self.read_pipfile() # use full contents to get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key not in _pipfile_cache: parsed = self._parse_pipfile(contents) _pipfile_cache[cache_key] = parsed return _pipfile_cache[cache_key]
[ "Parse", "Pipfile", "into", "a", "TOMLFile", "and", "cache", "it" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L491-L501
[ "def", "parsed_pipfile", "(", "self", ")", ":", "contents", "=", "self", ".", "read_pipfile", "(", ")", "# use full contents to get around str/bytes 2/3 issues", "cache_key", "=", "(", "self", ".", "pipfile_location", ",", "contents", ")", "if", "cache_key", "not", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project._lockfile
Pipfile.lock divided by PyPI and external dependencies.
pipenv/project.py
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
[ "Pipfile", ".", "lock", "divided", "by", "PyPI", "and", "external", "dependencies", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L581-L590
[ "def", "_lockfile", "(", "self", ")", ":", "pfile", "=", "pipfile", ".", "load", "(", "self", ".", "pipfile_location", ",", "inject_env", "=", "False", ")", "lockfile", "=", "json", ".", "loads", "(", "pfile", ".", "lock", "(", ")", ")", "for", "sect...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.all_packages
Returns a list of all packages.
pipenv/project.py
def all_packages(self): """Returns a list of all packages.""" p = dict(self.parsed_pipfile.get("dev-packages", {})) p.update(self.parsed_pipfile.get("packages", {})) return p
def all_packages(self): """Returns a list of all packages.""" p = dict(self.parsed_pipfile.get("dev-packages", {})) p.update(self.parsed_pipfile.get("packages", {})) return p
[ "Returns", "a", "list", "of", "all", "packages", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L648-L652
[ "def", "all_packages", "(", "self", ")", ":", "p", "=", "dict", "(", "self", ".", "parsed_pipfile", ".", "get", "(", "\"dev-packages\"", ",", "{", "}", ")", ")", "p", ".", "update", "(", "self", ".", "parsed_pipfile", ".", "get", "(", "\"packages\"", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.create_pipfile
Creates the Pipfile, filled with juicy defaults.
pipenv/project.py
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(make_option_group(index_group, config_parser)) install = config_parser.option_groups[0] indexes = ( " ".join(install.get_option("--extra-index-url").default) .lstrip("\n") .split("\n") ) sources = [DEFAULT_SOURCE,] for i, index in enumerate(indexes): if not index: continue source_name = "pip_index_{}".format(i) verify_ssl = index.startswith("https") sources.append( {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name} ) data = { u"source": sources, # Default packages. u"packages": {}, u"dev-packages": {}, } # Default requires. required_python = python if not python: if self.virtualenv_location: required_python = self.which("python", self.virtualenv_location) else: required_python = self.which("python") version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION if version and len(version) >= 3: data[u"requires"] = {"python_version": version[: len("2.7")]} self.write_toml(data)
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(make_option_group(index_group, config_parser)) install = config_parser.option_groups[0] indexes = ( " ".join(install.get_option("--extra-index-url").default) .lstrip("\n") .split("\n") ) sources = [DEFAULT_SOURCE,] for i, index in enumerate(indexes): if not index: continue source_name = "pip_index_{}".format(i) verify_ssl = index.startswith("https") sources.append( {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name} ) data = { u"source": sources, # Default packages. u"packages": {}, u"dev-packages": {}, } # Default requires. required_python = python if not python: if self.virtualenv_location: required_python = self.which("python", self.virtualenv_location) else: required_python = self.which("python") version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION if version and len(version) >= 3: data[u"requires"] = {"python_version": version[: len("2.7")]} self.write_toml(data)
[ "Creates", "the", "Pipfile", "filled", "with", "juicy", "defaults", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L674-L715
[ "def", "create_pipfile", "(", "self", ",", "python", "=", "None", ")", ":", "from", ".", "vendor", ".", "pip_shims", ".", "shims", "import", "(", "ConfigOptionParser", ",", "make_option_group", ",", "index_group", ")", "config_parser", "=", "ConfigOptionParser",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.write_toml
Writes the given data structure out as TOML.
pipenv/project.py
def write_toml(self, data, path=None): """Writes the given data structure out as TOML.""" if path is None: path = self.pipfile_location data = convert_toml_outline_tables(data) try: formatted_data = tomlkit.dumps(data).rstrip() except Exception: document = tomlkit.document() for section in ("packages", "dev-packages"): document[section] = tomlkit.container.Table() # Convert things to inline tables — fancy :) for package in data.get(section, {}): if hasattr(data[section][package], "keys"): table = tomlkit.inline_table() table.update(data[section][package]) document[section][package] = table else: document[section][package] = tomlkit.string(data[section][package]) formatted_data = tomlkit.dumps(document).rstrip() if ( vistir.compat.Path(path).absolute() == vistir.compat.Path(self.pipfile_location).absolute() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
def write_toml(self, data, path=None): """Writes the given data structure out as TOML.""" if path is None: path = self.pipfile_location data = convert_toml_outline_tables(data) try: formatted_data = tomlkit.dumps(data).rstrip() except Exception: document = tomlkit.document() for section in ("packages", "dev-packages"): document[section] = tomlkit.container.Table() # Convert things to inline tables — fancy :) for package in data.get(section, {}): if hasattr(data[section][package], "keys"): table = tomlkit.inline_table() table.update(data[section][package]) document[section][package] = table else: document[section][package] = tomlkit.string(data[section][package]) formatted_data = tomlkit.dumps(document).rstrip() if ( vistir.compat.Path(path).absolute() == vistir.compat.Path(self.pipfile_location).absolute() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
[ "Writes", "the", "given", "data", "structure", "out", "as", "TOML", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L783-L815
[ "def", "write_toml", "(", "self", ",", "data", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "self", ".", "pipfile_location", "data", "=", "convert_toml_outline_tables", "(", "data", ")", "try", ":", "formatted_data", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.write_lockfile
Write out the lockfile.
pipenv/project.py
def write_lockfile(self, content): """Write out the lockfile. """ s = self._lockfile_encoder.encode(content) open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"} with vistir.contextmanagers.atomic_open_for_write( self.lockfile_location, **open_kwargs ) as f: f.write(s) # Write newline at end of document. GH-319. # Only need '\n' here; the file object handles the rest. if not s.endswith(u"\n"): f.write(u"\n")
def write_lockfile(self, content): """Write out the lockfile. """ s = self._lockfile_encoder.encode(content) open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"} with vistir.contextmanagers.atomic_open_for_write( self.lockfile_location, **open_kwargs ) as f: f.write(s) # Write newline at end of document. GH-319. # Only need '\n' here; the file object handles the rest. if not s.endswith(u"\n"): f.write(u"\n")
[ "Write", "out", "the", "lockfile", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L817-L829
[ "def", "write_lockfile", "(", "self", ",", "content", ")", ":", "s", "=", "self", ".", "_lockfile_encoder", ".", "encode", "(", "content", ")", "open_kwargs", "=", "{", "\"newline\"", ":", "self", ".", "_lockfile_newlines", ",", "\"encoding\"", ":", "\"utf-8...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.find_source
Given a source, find it. source can be a url or an index name.
pipenv/project.py
def find_source(self, source): """ Given a source, find it. source can be a url or an index name. """ if not is_valid_url(source): try: source = self.get_source(name=source) except SourceNotFound: source = self.get_source(url=source) else: source = self.get_source(url=source) return source
def find_source(self, source): """ Given a source, find it. source can be a url or an index name. """ if not is_valid_url(source): try: source = self.get_source(name=source) except SourceNotFound: source = self.get_source(url=source) else: source = self.get_source(url=source) return source
[ "Given", "a", "source", "find", "it", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L854-L867
[ "def", "find_source", "(", "self", ",", "source", ")", ":", "if", "not", "is_valid_url", "(", "source", ")", ":", "try", ":", "source", "=", "self", ".", "get_source", "(", "name", "=", "source", ")", "except", "SourceNotFound", ":", "source", "=", "se...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.get_package_name_in_pipfile
Get the equivalent package name in pipfile
pipenv/project.py
def get_package_name_in_pipfile(self, package_name, dev=False): """Get the equivalent package name in pipfile""" key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): if pep423_name(name) == package_name: return name return None
def get_package_name_in_pipfile(self, package_name, dev=False): """Get the equivalent package name in pipfile""" key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): if pep423_name(name) == package_name: return name return None
[ "Get", "the", "equivalent", "package", "name", "in", "pipfile" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L898-L906
[ "def", "get_package_name_in_pipfile", "(", "self", ",", "package_name", ",", "dev", "=", "False", ")", ":", "key", "=", "\"dev-packages\"", "if", "dev", "else", "\"packages\"", "section", "=", "self", ".", "parsed_pipfile", ".", "get", "(", "key", ",", "{", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.add_index_to_pipfile
Adds a given index to the Pipfile.
pipenv/project.py
def add_index_to_pipfile(self, index, verify_ssl=True): """Adds a given index to the Pipfile.""" # Read and append Pipfile. p = self.parsed_pipfile try: self.get_source(url=index) except SourceNotFound: source = {"url": index, "verify_ssl": verify_ssl} else: return source["name"] = self.src_name_from_url(index) # Add the package to the group. if "source" not in p: p["source"] = [source] else: p["source"].append(source) # Write Pipfile. self.write_toml(p)
def add_index_to_pipfile(self, index, verify_ssl=True): """Adds a given index to the Pipfile.""" # Read and append Pipfile. p = self.parsed_pipfile try: self.get_source(url=index) except SourceNotFound: source = {"url": index, "verify_ssl": verify_ssl} else: return source["name"] = self.src_name_from_url(index) # Add the package to the group. if "source" not in p: p["source"] = [source] else: p["source"].append(source) # Write Pipfile. self.write_toml(p)
[ "Adds", "a", "given", "index", "to", "the", "Pipfile", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L969-L986
[ "def", "add_index_to_pipfile", "(", "self", ",", "index", ",", "verify_ssl", "=", "True", ")", ":", "# Read and append Pipfile.", "p", "=", "self", ".", "parsed_pipfile", "try", ":", "self", ".", "get_source", "(", "url", "=", "index", ")", "except", "Source...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.ensure_proper_casing
Ensures proper casing of Pipfile packages
pipenv/project.py
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
[ "Ensures", "proper", "casing", "of", "Pipfile", "packages" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1028-L1033
[ "def", "ensure_proper_casing", "(", "self", ")", ":", "pfile", "=", "self", ".", "parsed_pipfile", "casing_changed", "=", "self", ".", "proper_case_section", "(", "pfile", ".", "get", "(", "\"packages\"", ",", "{", "}", ")", ")", "casing_changed", "|=", "sel...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.proper_case_section
Verify proper casing is retrieved, when available, for each dependency in the section.
pipenv/project.py
def proper_case_section(self, section): """Verify proper casing is retrieved, when available, for each dependency in the section. """ # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Replace each package with proper casing. for dep in unknown_names: try: # Get new casing for package name. new_casing = proper_case(dep) except IOError: # Unable to normalize package name. continue if new_casing != dep: changed_values = True self.register_proper_name(new_casing) # Replace old value with new value. old_value = section[dep] section[new_casing] = old_value del section[dep] # Return whether or not values have been changed. return changed_values
def proper_case_section(self, section): """Verify proper casing is retrieved, when available, for each dependency in the section. """ # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Replace each package with proper casing. for dep in unknown_names: try: # Get new casing for package name. new_casing = proper_case(dep) except IOError: # Unable to normalize package name. continue if new_casing != dep: changed_values = True self.register_proper_name(new_casing) # Replace old value with new value. old_value = section[dep] section[new_casing] = old_value del section[dep] # Return whether or not values have been changed. return changed_values
[ "Verify", "proper", "casing", "is", "retrieved", "when", "available", "for", "each", "dependency", "in", "the", "section", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1035-L1059
[ "def", "proper_case_section", "(", "self", ",", "section", ")", ":", "# Casing for section.", "changed_values", "=", "False", "unknown_names", "=", "[", "k", "for", "k", "in", "section", ".", "keys", "(", ")", "if", "k", "not", "in", "set", "(", "self", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
native_concat
Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the string is returned.
pipenv/vendor/jinja2/nativetypes.py
def native_concat(nodes): """Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the string is returned. """ head = list(islice(nodes, 2)) if not head: return None if len(head) == 1: out = head[0] else: out = u''.join([text_type(v) for v in chain(head, nodes)]) try: return literal_eval(out) except (ValueError, SyntaxError, MemoryError): return out
def native_concat(nodes): """Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the string is returned. """ head = list(islice(nodes, 2)) if not head: return None if len(head) == 1: out = head[0] else: out = u''.join([text_type(v) for v in chain(head, nodes)]) try: return literal_eval(out) except (ValueError, SyntaxError, MemoryError): return out
[ "Return", "a", "native", "Python", "type", "from", "the", "list", "of", "compiled", "nodes", ".", "If", "the", "result", "is", "a", "single", "node", "its", "value", "is", "returned", ".", "Otherwise", "the", "nodes", "are", "concatenated", "as", "strings"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nativetypes.py#L11-L31
[ "def", "native_concat", "(", "nodes", ")", ":", "head", "=", "list", "(", "islice", "(", "nodes", ",", "2", ")", ")", "if", "not", "head", ":", "return", "None", "if", "len", "(", "head", ")", "==", "1", ":", "out", "=", "head", "[", "0", "]", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
NativeCodeGenerator.visit_Output
Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code.
pipenv/vendor/jinja2/nativetypes.py
def visit_Output(self, node, frame): """Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code. """ if self.has_known_extends and frame.require_output_check: return finalize = self.environment.finalize finalize_context = getattr(finalize, 'contextfunction', False) finalize_eval = getattr(finalize, 'evalcontextfunction', False) finalize_env = getattr(finalize, 'environmentfunction', False) if finalize is not None: if finalize_context or finalize_eval: const_finalize = None elif finalize_env: def const_finalize(x): return finalize(self.environment, x) else: const_finalize = finalize else: def const_finalize(x): return x # If we are inside a frame that requires output checking, we do so. outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # Try to evaluate as many chunks as possible into a static string at # compile time. body = [] for child in node.nodes: try: if const_finalize is None: raise nodes.Impossible() const = child.as_const(frame.eval_ctx) if not has_safe_repr(const): raise nodes.Impossible() except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, because otherwise the as_const # function would raise an Impossible exception at that point try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = const_finalize(const) except Exception: # if something goes wrong here we evaluate the node at runtime # for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(native_concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ',') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') close += 1 self.visit(item, frame) if close > 0: self.write(')' * close) if frame.buffer is not None: self.write(',') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(native_concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') self.indent() for argument in arguments: self.newline(argument) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') elif finalize_eval: self.write('context.eval_ctx, ') elif finalize_env: self.write('environment, ') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent()
def visit_Output(self, node, frame): """Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code. """ if self.has_known_extends and frame.require_output_check: return finalize = self.environment.finalize finalize_context = getattr(finalize, 'contextfunction', False) finalize_eval = getattr(finalize, 'evalcontextfunction', False) finalize_env = getattr(finalize, 'environmentfunction', False) if finalize is not None: if finalize_context or finalize_eval: const_finalize = None elif finalize_env: def const_finalize(x): return finalize(self.environment, x) else: const_finalize = finalize else: def const_finalize(x): return x # If we are inside a frame that requires output checking, we do so. outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # Try to evaluate as many chunks as possible into a static string at # compile time. body = [] for child in node.nodes: try: if const_finalize is None: raise nodes.Impossible() const = child.as_const(frame.eval_ctx) if not has_safe_repr(const): raise nodes.Impossible() except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, because otherwise the as_const # function would raise an Impossible exception at that point try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = const_finalize(const) except Exception: # if something goes wrong here we evaluate the node at runtime # for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(native_concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ',') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') close += 1 self.visit(item, frame) if close > 0: self.write(')' * close) if frame.buffer is not None: self.write(',') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(native_concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') self.indent() for argument in arguments: self.newline(argument) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') elif finalize_eval: self.write('context.eval_ctx, ') elif finalize_env: self.write('environment, ') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent()
[ "Same", "as", ":", "meth", ":", "CodeGenerator", ".", "visit_Output", "but", "do", "not", "call", "to_string", "on", "output", "nodes", "in", "generated", "code", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/nativetypes.py#L39-L195
[ "def", "visit_Output", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "self", ".", "has_known_extends", "and", "frame", ".", "require_output_check", ":", "return", "finalize", "=", "self", ".", "environment", ".", "finalize", "finalize_context", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.load
Clear all existing key:value items and import all key:value items from <mapping>. If multiple values exist for the same key in <mapping>, they are all be imported. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.load([(4,4), (4,44), (5,5)]) omd.allitems() == [(4,4), (4,44), (5,5)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def load(self, *args, **kwargs): """ Clear all existing key:value items and import all key:value items from <mapping>. If multiple values exist for the same key in <mapping>, they are all be imported. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.load([(4,4), (4,44), (5,5)]) omd.allitems() == [(4,4), (4,44), (5,5)] Returns: <self>. """ self.clear() self.updateall(*args, **kwargs) return self
def load(self, *args, **kwargs): """ Clear all existing key:value items and import all key:value items from <mapping>. If multiple values exist for the same key in <mapping>, they are all be imported. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.load([(4,4), (4,44), (5,5)]) omd.allitems() == [(4,4), (4,44), (5,5)] Returns: <self>. """ self.clear() self.updateall(*args, **kwargs) return self
[ "Clear", "all", "existing", "key", ":", "value", "items", "and", "import", "all", "key", ":", "value", "items", "from", "<mapping", ">", ".", "If", "multiple", "values", "exist", "for", "the", "same", "key", "in", "<mapping", ">", "they", "are", "all", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L156-L171
[ "def", "load", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "updateall", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.updateall
Update this dictionary with the items from <mapping>, replacing existing key:value items with shared keys before adding new key:value items. Example: omd = omdict([(1,1), (2,2)]) omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)]) omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def updateall(self, *args, **kwargs): """ Update this dictionary with the items from <mapping>, replacing existing key:value items with shared keys before adding new key:value items. Example: omd = omdict([(1,1), (2,2)]) omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)]) omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)] Returns: <self>. """ self._update_updateall(False, *args, **kwargs) return self
def updateall(self, *args, **kwargs): """ Update this dictionary with the items from <mapping>, replacing existing key:value items with shared keys before adding new key:value items. Example: omd = omdict([(1,1), (2,2)]) omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)]) omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)] Returns: <self>. """ self._update_updateall(False, *args, **kwargs) return self
[ "Update", "this", "dictionary", "with", "the", "items", "from", "<mapping", ">", "replacing", "existing", "key", ":", "value", "items", "with", "shared", "keys", "before", "adding", "new", "key", ":", "value", "items", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L201-L215
[ "def", "updateall", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_update_updateall", "(", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict._bin_update_items
<replacements and <leftovers> are modified directly, ala pass by reference.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): """ <replacements and <leftovers> are modified directly, ala pass by reference. """ for key, value in items: # If there are existing items with key <key> that have yet to be # marked for replacement, mark that item's value to be replaced by # <value> by appending it to <replacements>. if key in self and key not in replacements: replacements[key] = [value] elif (key in self and not replace_at_most_one and len(replacements[key]) < len(self.values(key))): replacements[key].append(value) else: if replace_at_most_one: replacements[key] = [value] else: leftovers.append((key, value))
def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): """ <replacements and <leftovers> are modified directly, ala pass by reference. """ for key, value in items: # If there are existing items with key <key> that have yet to be # marked for replacement, mark that item's value to be replaced by # <value> by appending it to <replacements>. if key in self and key not in replacements: replacements[key] = [value] elif (key in self and not replace_at_most_one and len(replacements[key]) < len(self.values(key))): replacements[key].append(value) else: if replace_at_most_one: replacements[key] = [value] else: leftovers.append((key, value))
[ "<replacements", "and", "<leftovers", ">", "are", "modified", "directly", "ala", "pass", "by", "reference", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L235-L254
[ "def", "_bin_update_items", "(", "self", ",", "items", ",", "replace_at_most_one", ",", "replacements", ",", "leftovers", ")", ":", "for", "key", ",", "value", "in", "items", ":", "# If there are existing items with key <key> that have yet to be", "# marked for replacemen...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.getlist
Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def getlist(self, key, default=[]): """ Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned. """ if key in self: return [node.value for node in self._map[key]] return default
def getlist(self, key, default=[]): """ Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned. """ if key in self: return [node.value for node in self._map[key]] return default
[ "Returns", ":", "The", "list", "of", "values", "for", "<key", ">", "if", "<key", ">", "is", "in", "the", "dictionary", "else", "<default", ">", ".", "If", "<default", ">", "is", "not", "provided", "an", "empty", "list", "is", "returned", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L274-L282
[ "def", "getlist", "(", "self", ",", "key", ",", "default", "=", "[", "]", ")", ":", "if", "key", "in", "self", ":", "return", "[", "node", ".", "value", "for", "node", "in", "self", ".", "_map", "[", "key", "]", "]", "return", "default" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.setdefaultlist
Similar to setdefault() except <defaultlist> is a list of values to set for <key>. If <key> already exists, its existing list of values is returned. If <key> isn't a key and <defaultlist> is an empty list, [], no values are added for <key> and <key> will not be added as a key. Returns: List of <key>'s values if <key> exists in the dictionary, otherwise <default>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def setdefaultlist(self, key, defaultlist=[None]): """ Similar to setdefault() except <defaultlist> is a list of values to set for <key>. If <key> already exists, its existing list of values is returned. If <key> isn't a key and <defaultlist> is an empty list, [], no values are added for <key> and <key> will not be added as a key. Returns: List of <key>'s values if <key> exists in the dictionary, otherwise <default>. """ if key in self: return self.getlist(key) self.addlist(key, defaultlist) return defaultlist
def setdefaultlist(self, key, defaultlist=[None]): """ Similar to setdefault() except <defaultlist> is a list of values to set for <key>. If <key> already exists, its existing list of values is returned. If <key> isn't a key and <defaultlist> is an empty list, [], no values are added for <key> and <key> will not be added as a key. Returns: List of <key>'s values if <key> exists in the dictionary, otherwise <default>. """ if key in self: return self.getlist(key) self.addlist(key, defaultlist) return defaultlist
[ "Similar", "to", "setdefault", "()", "except", "<defaultlist", ">", "is", "a", "list", "of", "values", "to", "set", "for", "<key", ">", ".", "If", "<key", ">", "already", "exists", "its", "existing", "list", "of", "values", "is", "returned", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L290-L305
[ "def", "setdefaultlist", "(", "self", ",", "key", ",", "defaultlist", "=", "[", "None", "]", ")", ":", "if", "key", "in", "self", ":", "return", "self", ".", "getlist", "(", "key", ")", "self", ".", "addlist", "(", "key", ",", "defaultlist", ")", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.addlist
Add the values in <valuelist> to the list of values for <key>. If <key> is not in the dictionary, the values in <valuelist> become the values for <key>. Example: omd = omdict([(1,1)]) omd.addlist(1, [11, 111]) omd.allitems() == [(1, 1), (1, 11), (1, 111)] omd.addlist(2, [2]) omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def addlist(self, key, valuelist=[]): """ Add the values in <valuelist> to the list of values for <key>. If <key> is not in the dictionary, the values in <valuelist> become the values for <key>. Example: omd = omdict([(1,1)]) omd.addlist(1, [11, 111]) omd.allitems() == [(1, 1), (1, 11), (1, 111)] omd.addlist(2, [2]) omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)] Returns: <self>. """ for value in valuelist: self.add(key, value) return self
def addlist(self, key, valuelist=[]): """ Add the values in <valuelist> to the list of values for <key>. If <key> is not in the dictionary, the values in <valuelist> become the values for <key>. Example: omd = omdict([(1,1)]) omd.addlist(1, [11, 111]) omd.allitems() == [(1, 1), (1, 11), (1, 111)] omd.addlist(2, [2]) omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)] Returns: <self>. """ for value in valuelist: self.add(key, value) return self
[ "Add", "the", "values", "in", "<valuelist", ">", "to", "the", "list", "of", "values", "for", "<key", ">", ".", "If", "<key", ">", "is", "not", "in", "the", "dictionary", "the", "values", "in", "<valuelist", ">", "become", "the", "values", "for", "<key"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L325-L342
[ "def", "addlist", "(", "self", ",", "key", ",", "valuelist", "=", "[", "]", ")", ":", "for", "value", "in", "valuelist", ":", "self", ".", "add", "(", "key", ",", "value", ")", "return", "self" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.setlist
Sets <key>'s list of values to <values>. Existing items with key <key> are first replaced with new values from <values>. Any remaining old items that haven't been replaced with new values are deleted, and any new values from <values> that don't have corresponding items with <key> to replace are appended to the end of the list of all items. If values is an empty list, [], <key> is deleted, equivalent in action to del self[<key>]. Example: omd = omdict([(1,1), (2,2)]) omd.setlist(1, [11, 111]) omd.allitems() == [(1,11), (2,2), (1,111)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, [None]) omd.allitems() == [(1,None), (2,2)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, []) omd.allitems() == [(2,2)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def setlist(self, key, values): """ Sets <key>'s list of values to <values>. Existing items with key <key> are first replaced with new values from <values>. Any remaining old items that haven't been replaced with new values are deleted, and any new values from <values> that don't have corresponding items with <key> to replace are appended to the end of the list of all items. If values is an empty list, [], <key> is deleted, equivalent in action to del self[<key>]. Example: omd = omdict([(1,1), (2,2)]) omd.setlist(1, [11, 111]) omd.allitems() == [(1,11), (2,2), (1,111)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, [None]) omd.allitems() == [(1,None), (2,2)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, []) omd.allitems() == [(2,2)] Returns: <self>. """ if not values and key in self: self.pop(key) else: it = zip_longest( list(self._map.get(key, [])), values, fillvalue=_absent) for node, value in it: if node is not _absent and value is not _absent: node.value = value elif node is _absent: self.add(key, value) elif value is _absent: self._map[key].remove(node) self._items.removenode(node) return self
def setlist(self, key, values): """ Sets <key>'s list of values to <values>. Existing items with key <key> are first replaced with new values from <values>. Any remaining old items that haven't been replaced with new values are deleted, and any new values from <values> that don't have corresponding items with <key> to replace are appended to the end of the list of all items. If values is an empty list, [], <key> is deleted, equivalent in action to del self[<key>]. Example: omd = omdict([(1,1), (2,2)]) omd.setlist(1, [11, 111]) omd.allitems() == [(1,11), (2,2), (1,111)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, [None]) omd.allitems() == [(1,None), (2,2)] omd = omdict([(1,1), (1,11), (2,2), (1,111)]) omd.setlist(1, []) omd.allitems() == [(2,2)] Returns: <self>. """ if not values and key in self: self.pop(key) else: it = zip_longest( list(self._map.get(key, [])), values, fillvalue=_absent) for node, value in it: if node is not _absent and value is not _absent: node.value = value elif node is _absent: self.add(key, value) elif value is _absent: self._map[key].remove(node) self._items.removenode(node) return self
[ "Sets", "<key", ">", "s", "list", "of", "values", "to", "<values", ">", ".", "Existing", "items", "with", "key", "<key", ">", "are", "first", "replaced", "with", "new", "values", "from", "<values", ">", ".", "Any", "remaining", "old", "items", "that", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L353-L392
[ "def", "setlist", "(", "self", ",", "key", ",", "values", ")", ":", "if", "not", "values", "and", "key", "in", "self", ":", "self", ".", "pop", "(", "key", ")", "else", ":", "it", "=", "zip_longest", "(", "list", "(", "self", ".", "_map", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.removevalues
Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.allitems() == [(1, 11)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def removevalues(self, key, values): """ Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.allitems() == [(1, 11)] Returns: <self>. """ self.setlist(key, [v for v in self.getlist(key) if v not in values]) return self
def removevalues(self, key, values): """ Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.allitems() == [(1, 11)] Returns: <self>. """ self.setlist(key, [v for v in self.getlist(key) if v not in values]) return self
[ "Removes", "all", "<values", ">", "from", "the", "values", "of", "<key", ">", ".", "If", "<key", ">", "has", "no", "remaining", "values", "after", "removevalues", "()", "the", "key", "is", "popped", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L394-L407
[ "def", "removevalues", "(", "self", ",", "key", ",", "values", ")", ":", "self", ".", "setlist", "(", "key", ",", "[", "v", "for", "v", "in", "self", ".", "getlist", "(", "key", ")", "if", "v", "not", "in", "values", "]", ")", "return", "self" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.poplist
If <key> is in the dictionary, pop it and return its list of values. If <key> is not in the dictionary, return <default>. KeyError is raised if <default> is not provided and <key> is not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplist(1) == [1, 11, 111] omd.allitems() == [(2,2), (3,3)] omd.poplist(2) == [2] omd.allitems() == [(3,3)] Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. Returns: List of <key>'s values.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def poplist(self, key, default=_absent): """ If <key> is in the dictionary, pop it and return its list of values. If <key> is not in the dictionary, return <default>. KeyError is raised if <default> is not provided and <key> is not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplist(1) == [1, 11, 111] omd.allitems() == [(2,2), (3,3)] omd.poplist(2) == [2] omd.allitems() == [(3,3)] Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. Returns: List of <key>'s values. """ if key in self: values = self.getlist(key) del self._map[key] for node, nodekey, nodevalue in self._items: if nodekey == key: self._items.removenode(node) return values elif key not in self._map and default is not _absent: return default raise KeyError(key)
def poplist(self, key, default=_absent): """ If <key> is in the dictionary, pop it and return its list of values. If <key> is not in the dictionary, return <default>. KeyError is raised if <default> is not provided and <key> is not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplist(1) == [1, 11, 111] omd.allitems() == [(2,2), (3,3)] omd.poplist(2) == [2] omd.allitems() == [(3,3)] Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. Returns: List of <key>'s values. """ if key in self: values = self.getlist(key) del self._map[key] for node, nodekey, nodevalue in self._items: if nodekey == key: self._items.removenode(node) return values elif key not in self._map and default is not _absent: return default raise KeyError(key)
[ "If", "<key", ">", "is", "in", "the", "dictionary", "pop", "it", "and", "return", "its", "list", "of", "values", ".", "If", "<key", ">", "is", "not", "in", "the", "dictionary", "return", "<default", ">", ".", "KeyError", "is", "raised", "if", "<default...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L416-L442
[ "def", "poplist", "(", "self", ",", "key", ",", "default", "=", "_absent", ")", ":", "if", "key", "in", "self", ":", "values", "=", "self", ".", "getlist", "(", "key", ")", "del", "self", ".", "_map", "[", "key", "]", "for", "node", ",", "nodekey...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.popvalue
If <value> is provided, pops the first or last (key,value) item in the dictionary if <key> is in the dictionary. If <value> is not provided, pops the first or last value for <key> if <key> is in the dictionary. If <key> no longer has any values after a popvalue() call, <key> is removed from the dictionary. If <key> isn't in the dictionary and <default> was provided, return default. KeyError is raised if <default> is not provided and <key> is not in the dictionary. ValueError is raised if <value> is provided but isn't a value for <key>. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)]) omd.popvalue(1) == 111 omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)] omd.popvalue(1, last=False) == 1 omd.allitems() == [(1,11), (2,2), (3,3), (2,22)] omd.popvalue(2, 2) == 2 omd.allitems() == [(1,11), (3,3), (2,22)] omd.popvalue(1, 11) == 11 omd.allitems() == [(3,3), (2,22)] omd.popvalue('not a key', default='sup') == 'sup' Params: last: Boolean whether to return <key>'s first value (<last> is False) or last value (<last> is True). Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. ValueError if <value> isn't a value for <key>. Returns: The first or last of <key>'s values.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def popvalue(self, key, value=_absent, default=_absent, last=True): """ If <value> is provided, pops the first or last (key,value) item in the dictionary if <key> is in the dictionary. If <value> is not provided, pops the first or last value for <key> if <key> is in the dictionary. If <key> no longer has any values after a popvalue() call, <key> is removed from the dictionary. If <key> isn't in the dictionary and <default> was provided, return default. KeyError is raised if <default> is not provided and <key> is not in the dictionary. ValueError is raised if <value> is provided but isn't a value for <key>. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)]) omd.popvalue(1) == 111 omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)] omd.popvalue(1, last=False) == 1 omd.allitems() == [(1,11), (2,2), (3,3), (2,22)] omd.popvalue(2, 2) == 2 omd.allitems() == [(1,11), (3,3), (2,22)] omd.popvalue(1, 11) == 11 omd.allitems() == [(3,3), (2,22)] omd.popvalue('not a key', default='sup') == 'sup' Params: last: Boolean whether to return <key>'s first value (<last> is False) or last value (<last> is True). Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. ValueError if <value> isn't a value for <key>. Returns: The first or last of <key>'s values. """ def pop_node_with_index(key, index): node = self._map[key].pop(index) if not self._map[key]: del self._map[key] self._items.removenode(node) return node if key in self: if value is not _absent: if last: pos = self.values(key)[::-1].index(value) else: pos = self.values(key).index(value) if pos == -1: raise ValueError(value) else: index = (len(self.values(key)) - 1 - pos) if last else pos return pop_node_with_index(key, index).value else: return pop_node_with_index(key, -1 if last else 0).value elif key not in self._map and default is not _absent: return default raise KeyError(key)
def popvalue(self, key, value=_absent, default=_absent, last=True): """ If <value> is provided, pops the first or last (key,value) item in the dictionary if <key> is in the dictionary. If <value> is not provided, pops the first or last value for <key> if <key> is in the dictionary. If <key> no longer has any values after a popvalue() call, <key> is removed from the dictionary. If <key> isn't in the dictionary and <default> was provided, return default. KeyError is raised if <default> is not provided and <key> is not in the dictionary. ValueError is raised if <value> is provided but isn't a value for <key>. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)]) omd.popvalue(1) == 111 omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)] omd.popvalue(1, last=False) == 1 omd.allitems() == [(1,11), (2,2), (3,3), (2,22)] omd.popvalue(2, 2) == 2 omd.allitems() == [(1,11), (3,3), (2,22)] omd.popvalue(1, 11) == 11 omd.allitems() == [(3,3), (2,22)] omd.popvalue('not a key', default='sup') == 'sup' Params: last: Boolean whether to return <key>'s first value (<last> is False) or last value (<last> is True). Raises: KeyError if <key> isn't in the dictionary and <default> isn't provided. ValueError if <value> isn't a value for <key>. Returns: The first or last of <key>'s values. """ def pop_node_with_index(key, index): node = self._map[key].pop(index) if not self._map[key]: del self._map[key] self._items.removenode(node) return node if key in self: if value is not _absent: if last: pos = self.values(key)[::-1].index(value) else: pos = self.values(key).index(value) if pos == -1: raise ValueError(value) else: index = (len(self.values(key)) - 1 - pos) if last else pos return pop_node_with_index(key, index).value else: return pop_node_with_index(key, -1 if last else 0).value elif key not in self._map and default is not _absent: return default raise KeyError(key)
[ "If", "<value", ">", "is", "provided", "pops", "the", "first", "or", "last", "(", "key", "value", ")", "item", "in", "the", "dictionary", "if", "<key", ">", "is", "in", "the", "dictionary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L444-L501
[ "def", "popvalue", "(", "self", ",", "key", ",", "value", "=", "_absent", ",", "default", "=", "_absent", ",", "last", "=", "True", ")", ":", "def", "pop_node_with_index", "(", "key", ",", "index", ")", ":", "node", "=", "self", ".", "_map", "[", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.popitem
Pop and return a key:value item. If <fromall> is False, items()[0] is popped if <last> is False or items()[-1] is popped if <last> is True. All remaining items with the same key are removed. If <fromall> is True, allitems()[0] is popped if <last> is False or allitems()[-1] is popped if <last> is True. Any remaining items with the same key remain. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem() == (3,3) omd.popitem(fromall=False, last=False) == (1,1) omd.popitem(fromall=False, last=False) == (2,2) omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem(fromall=True, last=False) == (1,1) omd.popitem(fromall=True, last=False) == (1,11) omd.popitem(fromall=True, last=True) == (3,3) omd.popitem(fromall=True, last=False) == (1,111) Params: fromall: Whether to pop an item from items() (<fromall> is True) or allitems() (<fromall> is False). last: Boolean whether to pop the first item or last item of items() or allitems(). Raises: KeyError if the dictionary is empty. Returns: The first or last item from item() or allitem().
pipenv/vendor/orderedmultidict/orderedmultidict.py
def popitem(self, fromall=False, last=True): """ Pop and return a key:value item. If <fromall> is False, items()[0] is popped if <last> is False or items()[-1] is popped if <last> is True. All remaining items with the same key are removed. If <fromall> is True, allitems()[0] is popped if <last> is False or allitems()[-1] is popped if <last> is True. Any remaining items with the same key remain. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem() == (3,3) omd.popitem(fromall=False, last=False) == (1,1) omd.popitem(fromall=False, last=False) == (2,2) omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem(fromall=True, last=False) == (1,1) omd.popitem(fromall=True, last=False) == (1,11) omd.popitem(fromall=True, last=True) == (3,3) omd.popitem(fromall=True, last=False) == (1,111) Params: fromall: Whether to pop an item from items() (<fromall> is True) or allitems() (<fromall> is False). last: Boolean whether to pop the first item or last item of items() or allitems(). Raises: KeyError if the dictionary is empty. Returns: The first or last item from item() or allitem(). """ if not self._items: raise KeyError('popitem(): %s is empty' % self.__class__.__name__) if fromall: node = self._items[-1 if last else 0] key = node.key return key, self.popvalue(key, last=last) else: key = list(self._map.keys())[-1 if last else 0] return key, self.pop(key)
def popitem(self, fromall=False, last=True): """ Pop and return a key:value item. If <fromall> is False, items()[0] is popped if <last> is False or items()[-1] is popped if <last> is True. All remaining items with the same key are removed. If <fromall> is True, allitems()[0] is popped if <last> is False or allitems()[-1] is popped if <last> is True. Any remaining items with the same key remain. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem() == (3,3) omd.popitem(fromall=False, last=False) == (1,1) omd.popitem(fromall=False, last=False) == (2,2) omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.popitem(fromall=True, last=False) == (1,1) omd.popitem(fromall=True, last=False) == (1,11) omd.popitem(fromall=True, last=True) == (3,3) omd.popitem(fromall=True, last=False) == (1,111) Params: fromall: Whether to pop an item from items() (<fromall> is True) or allitems() (<fromall> is False). last: Boolean whether to pop the first item or last item of items() or allitems(). Raises: KeyError if the dictionary is empty. Returns: The first or last item from item() or allitem(). """ if not self._items: raise KeyError('popitem(): %s is empty' % self.__class__.__name__) if fromall: node = self._items[-1 if last else 0] key = node.key return key, self.popvalue(key, last=last) else: key = list(self._map.keys())[-1 if last else 0] return key, self.pop(key)
[ "Pop", "and", "return", "a", "key", ":", "value", "item", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L503-L544
[ "def", "popitem", "(", "self", ",", "fromall", "=", "False", ",", "last", "=", "True", ")", ":", "if", "not", "self", ".", "_items", ":", "raise", "KeyError", "(", "'popitem(): %s is empty'", "%", "self", ".", "__class__", ".", "__name__", ")", "if", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.poplistitem
Pop and return a key:valuelist item comprised of a key and that key's list of values. If <last> is False, a key:valuelist item comprised of keys()[0] and its list of values is popped and returned. If <last> is True, a key:valuelist item comprised of keys()[-1] and its list of values is popped and returned. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplistitem(last=True) == (3,[3]) omd.poplistitem(last=False) == (1,[1,11,111]) Params: last: Boolean whether to pop the first or last key and its associated list of values. Raises: KeyError if the dictionary is empty. Returns: A two-tuple comprised of the first or last key and its associated list of values.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def poplistitem(self, last=True): """ Pop and return a key:valuelist item comprised of a key and that key's list of values. If <last> is False, a key:valuelist item comprised of keys()[0] and its list of values is popped and returned. If <last> is True, a key:valuelist item comprised of keys()[-1] and its list of values is popped and returned. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplistitem(last=True) == (3,[3]) omd.poplistitem(last=False) == (1,[1,11,111]) Params: last: Boolean whether to pop the first or last key and its associated list of values. Raises: KeyError if the dictionary is empty. Returns: A two-tuple comprised of the first or last key and its associated list of values. """ if not self._items: s = 'poplistitem(): %s is empty' % self.__class__.__name__ raise KeyError(s) key = self.keys()[-1 if last else 0] return key, self.poplist(key)
def poplistitem(self, last=True): """ Pop and return a key:valuelist item comprised of a key and that key's list of values. If <last> is False, a key:valuelist item comprised of keys()[0] and its list of values is popped and returned. If <last> is True, a key:valuelist item comprised of keys()[-1] and its list of values is popped and returned. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.poplistitem(last=True) == (3,[3]) omd.poplistitem(last=False) == (1,[1,11,111]) Params: last: Boolean whether to pop the first or last key and its associated list of values. Raises: KeyError if the dictionary is empty. Returns: A two-tuple comprised of the first or last key and its associated list of values. """ if not self._items: s = 'poplistitem(): %s is empty' % self.__class__.__name__ raise KeyError(s) key = self.keys()[-1 if last else 0] return key, self.poplist(key)
[ "Pop", "and", "return", "a", "key", ":", "valuelist", "item", "comprised", "of", "a", "key", "and", "that", "key", "s", "list", "of", "values", ".", "If", "<last", ">", "is", "False", "a", "key", ":", "valuelist", "item", "comprised", "of", "keys", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L546-L571
[ "def", "poplistitem", "(", "self", ",", "last", "=", "True", ")", ":", "if", "not", "self", ".", "_items", ":", "s", "=", "'poplistitem(): %s is empty'", "%", "self", ".", "__class__", ".", "__name__", "raise", "KeyError", "(", "s", ")", "key", "=", "s...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.values
Raises: KeyError if <key> is provided and not in the dictionary. Returns: List created from itervalues(<key>).If <key> is provided and is a dictionary key, only values of items with key <key> are returned.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def values(self, key=_absent): """ Raises: KeyError if <key> is provided and not in the dictionary. Returns: List created from itervalues(<key>).If <key> is provided and is a dictionary key, only values of items with key <key> are returned. """ if key is not _absent and key in self._map: return self.getlist(key) return list(self.itervalues())
def values(self, key=_absent): """ Raises: KeyError if <key> is provided and not in the dictionary. Returns: List created from itervalues(<key>).If <key> is provided and is a dictionary key, only values of items with key <key> are returned. """ if key is not _absent and key in self._map: return self.getlist(key) return list(self.itervalues())
[ "Raises", ":", "KeyError", "if", "<key", ">", "is", "provided", "and", "not", "in", "the", "dictionary", ".", "Returns", ":", "List", "created", "from", "itervalues", "(", "<key", ">", ")", ".", "If", "<key", ">", "is", "provided", "and", "is", "a", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L584-L593
[ "def", "values", "(", "self", ",", "key", "=", "_absent", ")", ":", "if", "key", "is", "not", "_absent", "and", "key", "in", "self", ".", "_map", ":", "return", "self", ".", "getlist", "(", "key", ")", "return", "list", "(", "self", ".", "itervalue...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.iteritems
Parity with dict.iteritems() except the optional <key> parameter has been added. If <key> is provided, only items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111) omd.iteritems() -> (1,1) -> (2,2) -> (3,3) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over the items() of the dictionary, or only items with the key <key> if <key> is provided.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def iteritems(self, key=_absent): """ Parity with dict.iteritems() except the optional <key> parameter has been added. If <key> is provided, only items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111) omd.iteritems() -> (1,1) -> (2,2) -> (3,3) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over the items() of the dictionary, or only items with the key <key> if <key> is provided. """ if key is not _absent: if key in self: items = [(node.key, node.value) for node in self._map[key]] return iter(items) raise KeyError(key) items = six.iteritems(self._map) return iter((key, nodes[0].value) for (key, nodes) in items)
def iteritems(self, key=_absent): """ Parity with dict.iteritems() except the optional <key> parameter has been added. If <key> is provided, only items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111) omd.iteritems() -> (1,1) -> (2,2) -> (3,3) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over the items() of the dictionary, or only items with the key <key> if <key> is provided. """ if key is not _absent: if key in self: items = [(node.key, node.value) for node in self._map[key]] return iter(items) raise KeyError(key) items = six.iteritems(self._map) return iter((key, nodes[0].value) for (key, nodes) in items)
[ "Parity", "with", "dict", ".", "iteritems", "()", "except", "the", "optional", "<key", ">", "parameter", "has", "been", "added", ".", "If", "<key", ">", "is", "provided", "only", "items", "with", "the", "provided", "key", "are", "iterated", "over", ".", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L607-L629
[ "def", "iteritems", "(", "self", ",", "key", "=", "_absent", ")", ":", "if", "key", "is", "not", "_absent", ":", "if", "key", "in", "self", ":", "items", "=", "[", "(", "node", ".", "key", ",", "node", ".", "value", ")", "for", "node", "in", "s...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.itervalues
Parity with dict.itervalues() except the optional <key> parameter has been added. If <key> is provided, only values from items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.itervalues(1) -> 1 -> 11 -> 111 omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3 Raises: KeyError if <key> is provided and isn't in the dictionary. Returns: An iterator over the values() of the dictionary, or only the values of key <key> if <key> is provided.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def itervalues(self, key=_absent): """ Parity with dict.itervalues() except the optional <key> parameter has been added. If <key> is provided, only values from items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.itervalues(1) -> 1 -> 11 -> 111 omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3 Raises: KeyError if <key> is provided and isn't in the dictionary. Returns: An iterator over the values() of the dictionary, or only the values of key <key> if <key> is provided. """ if key is not _absent: if key in self: return iter([node.value for node in self._map[key]]) raise KeyError(key) return iter([nodes[0].value for nodes in six.itervalues(self._map)])
def itervalues(self, key=_absent): """ Parity with dict.itervalues() except the optional <key> parameter has been added. If <key> is provided, only values from items with the provided key are iterated over. KeyError is raised if <key> is provided and not in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.itervalues(1) -> 1 -> 11 -> 111 omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3 Raises: KeyError if <key> is provided and isn't in the dictionary. Returns: An iterator over the values() of the dictionary, or only the values of key <key> if <key> is provided. """ if key is not _absent: if key in self: return iter([node.value for node in self._map[key]]) raise KeyError(key) return iter([nodes[0].value for nodes in six.itervalues(self._map)])
[ "Parity", "with", "dict", ".", "itervalues", "()", "except", "the", "optional", "<key", ">", "parameter", "has", "been", "added", ".", "If", "<key", ">", "is", "provided", "only", "values", "from", "items", "with", "the", "provided", "key", "are", "iterate...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L634-L654
[ "def", "itervalues", "(", "self", ",", "key", "=", "_absent", ")", ":", "if", "key", "is", "not", "_absent", ":", "if", "key", "in", "self", ":", "return", "iter", "(", "[", "node", ".", "value", "for", "node", "in", "self", ".", "_map", "[", "ke...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.iterallitems
Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3) omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over every item in the diciontary. If <key> is provided, only items with the key <key> are iterated over.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def iterallitems(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3) omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over every item in the diciontary. If <key> is provided, only items with the key <key> are iterated over. ''' if key is not _absent: # Raises KeyError if <key> is not in self._map. return self.iteritems(key) return self._items.iteritems()
def iterallitems(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3) omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111) Raises: KeyError if <key> is provided and not in the dictionary. Returns: An iterator over every item in the diciontary. If <key> is provided, only items with the key <key> are iterated over. ''' if key is not _absent: # Raises KeyError if <key> is not in self._map. return self.iteritems(key) return self._items.iteritems()
[ "Example", ":", "omd", "=", "omdict", "(", "[", "(", "1", "1", ")", "(", "1", "11", ")", "(", "1", "111", ")", "(", "2", "2", ")", "(", "3", "3", ")", "]", ")", "omd", ".", "iterallitems", "()", "==", "(", "1", "1", ")", "-", ">", "(", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L685-L699
[ "def", "iterallitems", "(", "self", ",", "key", "=", "_absent", ")", ":", "if", "key", "is", "not", "_absent", ":", "# Raises KeyError if <key> is not in self._map.", "return", "self", ".", "iteritems", "(", "key", ")", "return", "self", ".", "_items", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.iterallvalues
Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3 Returns: An iterator over the values of every item in the dictionary.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def iterallvalues(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3 Returns: An iterator over the values of every item in the dictionary. ''' if key is not _absent: if key in self: return iter(self.getlist(key)) raise KeyError(key) return self._items.itervalues()
def iterallvalues(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3 Returns: An iterator over the values of every item in the dictionary. ''' if key is not _absent: if key in self: return iter(self.getlist(key)) raise KeyError(key) return self._items.itervalues()
[ "Example", ":", "omd", "=", "omdict", "(", "[", "(", "1", "1", ")", "(", "1", "11", ")", "(", "1", "111", ")", "(", "2", "2", ")", "(", "3", "3", ")", "]", ")", "omd", ".", "iterallvalues", "()", "==", "1", "-", ">", "11", "-", ">", "11...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L711-L723
[ "def", "iterallvalues", "(", "self", ",", "key", "=", "_absent", ")", ":", "if", "key", "is", "not", "_absent", ":", "if", "key", "in", "self", ":", "return", "iter", "(", "self", ".", "getlist", "(", "key", ")", ")", "raise", "KeyError", "(", "key...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
omdict.reverse
Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>.
pipenv/vendor/orderedmultidict/orderedmultidict.py
def reverse(self): """ Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>. """ for key in six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
def reverse(self): """ Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>. """ for key in six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
[ "Reverse", "the", "order", "of", "all", "items", "in", "the", "dictionary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L746-L760
[ "def", "reverse", "(", "self", ")", ":", "for", "key", "in", "six", ".", "iterkeys", "(", "self", ".", "_map", ")", ":", "self", ".", "_map", "[", "key", "]", ".", "reverse", "(", ")", "self", ".", "_items", ".", "reverse", "(", ")", "return", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BuildEnvironment.check_requirements
Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs
pipenv/patched/notpip/_internal/build_env.py
def check_requirements(self, reqs): # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]] """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = set() if reqs: ws = WorkingSet(self._lib_dirs) for req in reqs: try: if ws.find(Requirement.parse(req)) is None: missing.add(req) except VersionConflict as e: conflicting.add((str(e.args[0].as_requirement()), str(e.args[1]))) return conflicting, missing
def check_requirements(self, reqs): # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]] """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = set() if reqs: ws = WorkingSet(self._lib_dirs) for req in reqs: try: if ws.find(Requirement.parse(req)) is None: missing.add(req) except VersionConflict as e: conflicting.add((str(e.args[0].as_requirement()), str(e.args[1]))) return conflicting, missing
[ "Return", "2", "sets", ":", "-", "conflicting", "requirements", ":", "set", "of", "(", "installed", "wanted", ")", "reqs", "tuples", "-", "missing", "requirements", ":", "set", "of", "reqs" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/build_env.py#L137-L154
[ "def", "check_requirements", "(", "self", ",", "reqs", ")", ":", "# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]", "missing", "=", "set", "(", ")", "conflicting", "=", "set", "(", ")", "if", "reqs", ":", "ws", "=", "WorkingSet", "(", "self", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_unpack_args
Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`.
pipenv/vendor/click/parser.py
def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args)
def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args)
[ "Given", "an", "iterable", "of", "arguments", "and", "an", "iterable", "of", "nargs", "specifications", "it", "returns", "a", "tuple", "with", "all", "the", "unpacked", "arguments", "at", "the", "first", "index", "and", "all", "remaining", "arguments", "as", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L25-L73
[ "def", "_unpack_args", "(", "args", ",", "nargs_spec", ")", ":", "args", "=", "deque", "(", "args", ")", "nargs_spec", "=", "deque", "(", "nargs_spec", ")", "rv", "=", "[", "]", "spos", "=", "None", "def", "_fetch", "(", "c", ")", ":", "try", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
split_arg_string
Given an argument string this attempts to split it into small parts.
pipenv/vendor/click/parser.py
def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv
def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv
[ "Given", "an", "argument", "string", "this", "attempts", "to", "split", "it", "into", "small", "parts", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L98-L113
[ "def", "split_arg_string", "(", "string", ")", ":", "rv", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "r\"('([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\"", "r'|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"'", "r'|\\S+)\\s*'", ",", "string", ",", "re", ".", "S", ")...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
OptionParser.add_option
Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``appnd_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser.
pipenv/vendor/click/parser.py
def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``appnd_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``appnd_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
[ "Adds", "a", "new", "option", "named", "dest", "to", "the", "parser", ".", "The", "destination", "is", "not", "inferred", "(", "unlike", "with", "optparse", ")", "and", "needs", "to", "be", "explicitly", "provided", ".", "Action", "can", "be", "any", "of...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L228-L247
[ "def", "add_option", "(", "self", ",", "opts", ",", "dest", ",", "action", "=", "None", ",", "nargs", "=", "1", ",", "const", "=", "None", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "obj", "=", "dest", "opts", "=", "[", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
OptionParser.add_argument
Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser.
pipenv/vendor/click/parser.py
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
[ "Adds", "a", "positional", "argument", "named", "dest", "to", "the", "parser", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L249-L257
[ "def", "add_argument", "(", "self", ",", "dest", ",", "nargs", "=", "1", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "obj", "=", "dest", "self", ".", "_args", ".", "append", "(", "Argument", "(", "dest", "=", "dest", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
OptionParser.parse_args
Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.
pipenv/vendor/click/parser.py
def parse_args(self, args): """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order
def parse_args(self, args): """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order
[ "Parses", "positional", "arguments", "and", "returns", "(", "values", "args", "order", ")", "for", "the", "parsed", "options", "and", "arguments", "as", "well", "as", "the", "leftover", "arguments", "if", "there", "are", "any", ".", "The", "order", "is", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L259-L273
[ "def", "parse_args", "(", "self", ",", "args", ")", ":", "state", "=", "ParsingState", "(", "args", ")", "try", ":", "self", ".", "_process_args_for_options", "(", "state", ")", "self", ".", "_process_args_for_args", "(", "state", ")", "except", "UsageError"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_graph
Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance
pipenv/vendor/distlib/database.py
def make_graph(dists, scheme='default'): """Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance """ scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_distribution(dist) for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) provided.setdefault(name, []).append((version, dist)) # now make the edges for dist in dists: requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires) for req in requires: try: matcher = scheme.matcher(req) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive matched = False if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: graph.add_edge(dist, provider, req) matched = True break if not matched: graph.add_missing(dist, req) return graph
def make_graph(dists, scheme='default'): """Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance """ scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_distribution(dist) for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) provided.setdefault(name, []).append((version, dist)) # now make the edges for dist in dists: requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires) for req in requires: try: matcher = scheme.matcher(req) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive matched = False if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: graph.add_edge(dist, provider, req) matched = True break if not matched: graph.add_missing(dist, req) return graph
[ "Makes", "a", "dependency", "graph", "from", "the", "given", "distributions", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1225-L1276
[ "def", "make_graph", "(", "dists", ",", "scheme", "=", "'default'", ")", ":", "scheme", "=", "get_scheme", "(", "scheme", ")", "graph", "=", "DependencyGraph", "(", ")", "provided", "=", "{", "}", "# maps names to lists of (version, dist) tuples", "# first, build ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_dependent_dists
Recursively generate a list of distributions from *dists* that are dependent on *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested
pipenv/vendor/distlib/database.py
def get_dependent_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are dependent on *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) dep = [dist] # dependent distributions todo = graph.reverse_list[dist] # list of nodes we should inspect while todo: d = todo.pop() dep.append(d) for succ in graph.reverse_list[d]: if succ not in dep: todo.append(succ) dep.pop(0) # remove dist from dep, was there to prevent infinite loops return dep
def get_dependent_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are dependent on *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) dep = [dist] # dependent distributions todo = graph.reverse_list[dist] # list of nodes we should inspect while todo: d = todo.pop() dep.append(d) for succ in graph.reverse_list[d]: if succ not in dep: todo.append(succ) dep.pop(0) # remove dist from dep, was there to prevent infinite loops return dep
[ "Recursively", "generate", "a", "list", "of", "distributions", "from", "*", "dists", "*", "that", "are", "dependent", "on", "*", "dist", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1279-L1302
[ "def", "get_dependent_dists", "(", "dists", ",", "dist", ")", ":", "if", "dist", "not", "in", "dists", ":", "raise", "DistlibException", "(", "'given distribution %r is not a member '", "'of the list'", "%", "dist", ".", "name", ")", "graph", "=", "make_graph", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_required_dists
Recursively generate a list of distributions from *dists* that are required by *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested
pipenv/vendor/distlib/database.py
def get_required_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are required by *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) req = [] # required distributions todo = graph.adjacency_list[dist] # list of nodes we should inspect while todo: d = todo.pop()[0] req.append(d) for pred in graph.adjacency_list[d]: if pred not in req: todo.append(pred) return req
def get_required_dists(dists, dist): """Recursively generate a list of distributions from *dists* that are required by *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested """ if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) req = [] # required distributions todo = graph.adjacency_list[dist] # list of nodes we should inspect while todo: d = todo.pop()[0] req.append(d) for pred in graph.adjacency_list[d]: if pred not in req: todo.append(pred) return req
[ "Recursively", "generate", "a", "list", "of", "distributions", "from", "*", "dists", "*", "that", "are", "required", "by", "*", "dist", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1305-L1327
[ "def", "get_required_dists", "(", "dists", ",", "dist", ")", ":", "if", "dist", "not", "in", "dists", ":", "raise", "DistlibException", "(", "'given distribution %r is not a member '", "'of the list'", "%", "dist", ".", "name", ")", "graph", "=", "make_graph", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_dist
A convenience method for making a dist given just a name and version.
pipenv/vendor/distlib/database.py
def make_dist(name, version, **kwargs): """ A convenience method for making a dist given just a name and version. """ summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' return Distribution(md)
def make_dist(name, version, **kwargs): """ A convenience method for making a dist given just a name and version. """ summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' return Distribution(md)
[ "A", "convenience", "method", "for", "making", "a", "dist", "given", "just", "a", "name", "and", "version", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1330-L1339
[ "def", "make_dist", "(", "name", ",", "version", ",", "*", "*", "kwargs", ")", ":", "summary", "=", "kwargs", ".", "pop", "(", "'summary'", ",", "'Placeholder for summary'", ")", "md", "=", "Metadata", "(", "*", "*", "kwargs", ")", "md", ".", "name", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Cache.clear
Clear the cache, setting it to its initial state.
pipenv/vendor/distlib/database.py
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
[ "Clear", "the", "cache", "setting", "it", "to", "its", "initial", "state", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L57-L63
[ "def", "clear", "(", "self", ")", ":", "self", ".", "name", ".", "clear", "(", ")", "self", ".", "path", ".", "clear", "(", ")", "self", ".", "generated", "=", "False" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Cache.add
Add a distribution to the cache. :param dist: The distribution to add.
pipenv/vendor/distlib/database.py
def add(self, dist): """ Add a distribution to the cache. :param dist: The distribution to add. """ if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
def add(self, dist): """ Add a distribution to the cache. :param dist: The distribution to add. """ if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
[ "Add", "a", "distribution", "to", "the", "cache", ".", ":", "param", "dist", ":", "The", "distribution", "to", "add", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L65-L72
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "dist", ".", "path", "not", "in", "self", ".", "path", ":", "self", ".", "path", "[", "dist", ".", "path", "]", "=", "dist", "self", ".", "name", ".", "setdefault", "(", "dist", ".", "key"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath._generate_cache
Scan the path for distributions and populate the cache with those that are found.
pipenv/vendor/distlib/database.py
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in self._yield_distributions(): if isinstance(dist, InstalledDistribution): self._cache.add(dist) else: self._cache_egg.add(dist) if gen_dist: self._cache.generated = True if gen_egg: self._cache_egg.generated = True
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in self._yield_distributions(): if isinstance(dist, InstalledDistribution): self._cache.add(dist) else: self._cache_egg.add(dist) if gen_dist: self._cache.generated = True if gen_egg: self._cache_egg.generated = True
[ "Scan", "the", "path", "for", "distributions", "and", "populate", "the", "cache", "with", "those", "that", "are", "found", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L159-L176
[ "def", "_generate_cache", "(", "self", ")", ":", "gen_dist", "=", "not", "self", ".", "_cache", ".", "generated", "gen_egg", "=", "self", ".", "_include_egg", "and", "not", "self", ".", "_cache_egg", ".", "generated", "if", "gen_dist", "or", "gen_egg", ":"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.distinfo_dirname
The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` other than the one in ``'dist-info'`` and the one separating the name from the version number. :parameter name: is converted to a standard distribution name by replacing any runs of non- alphanumeric characters with a single ``'-'``. :type name: string :parameter version: is converted to a standard version string. Spaces become dots, and all other non-alphanumeric characters (except dots) become dashes, with runs of multiple dashes condensed to a single dash. :type version: string :returns: directory name :rtype: string
pipenv/vendor/distlib/database.py
def distinfo_dirname(cls, name, version): """ The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` other than the one in ``'dist-info'`` and the one separating the name from the version number. :parameter name: is converted to a standard distribution name by replacing any runs of non- alphanumeric characters with a single ``'-'``. :type name: string :parameter version: is converted to a standard version string. Spaces become dots, and all other non-alphanumeric characters (except dots) become dashes, with runs of multiple dashes condensed to a single dash. :type version: string :returns: directory name :rtype: string""" name = name.replace('-', '_') return '-'.join([name, version]) + DISTINFO_EXT
def distinfo_dirname(cls, name, version): """ The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` other than the one in ``'dist-info'`` and the one separating the name from the version number. :parameter name: is converted to a standard distribution name by replacing any runs of non- alphanumeric characters with a single ``'-'``. :type name: string :parameter version: is converted to a standard version string. Spaces become dots, and all other non-alphanumeric characters (except dots) become dashes, with runs of multiple dashes condensed to a single dash. :type version: string :returns: directory name :rtype: string""" name = name.replace('-', '_') return '-'.join([name, version]) + DISTINFO_EXT
[ "The", "*", "name", "*", "and", "*", "version", "*", "parameters", "are", "converted", "into", "their", "filename", "-", "escaped", "form", "i", ".", "e", ".", "any", "-", "characters", "are", "replaced", "with", "_", "other", "than", "the", "one", "in...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L179-L198
[ "def", "distinfo_dirname", "(", "cls", ",", "name", ",", "version", ")", ":", "name", "=", "name", ".", "replace", "(", "'-'", ",", "'_'", ")", "return", "'-'", ".", "join", "(", "[", "name", ",", "version", "]", ")", "+", "DISTINFO_EXT" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.get_distributions
Provides an iterator that looks for distributions and returns :class:`InstalledDistribution` or :class:`EggInfoDistribution` instances for each one of them. :rtype: iterator of :class:`InstalledDistribution` and :class:`EggInfoDistribution` instances
pipenv/vendor/distlib/database.py
def get_distributions(self): """ Provides an iterator that looks for distributions and returns :class:`InstalledDistribution` or :class:`EggInfoDistribution` instances for each one of them. :rtype: iterator of :class:`InstalledDistribution` and :class:`EggInfoDistribution` instances """ if not self._cache_enabled: for dist in self._yield_distributions(): yield dist else: self._generate_cache() for dist in self._cache.path.values(): yield dist if self._include_egg: for dist in self._cache_egg.path.values(): yield dist
def get_distributions(self): """ Provides an iterator that looks for distributions and returns :class:`InstalledDistribution` or :class:`EggInfoDistribution` instances for each one of them. :rtype: iterator of :class:`InstalledDistribution` and :class:`EggInfoDistribution` instances """ if not self._cache_enabled: for dist in self._yield_distributions(): yield dist else: self._generate_cache() for dist in self._cache.path.values(): yield dist if self._include_egg: for dist in self._cache_egg.path.values(): yield dist
[ "Provides", "an", "iterator", "that", "looks", "for", "distributions", "and", "returns", ":", "class", ":", "InstalledDistribution", "or", ":", "class", ":", "EggInfoDistribution", "instances", "for", "each", "one", "of", "them", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L200-L220
[ "def", "get_distributions", "(", "self", ")", ":", "if", "not", "self", ".", "_cache_enabled", ":", "for", "dist", "in", "self", ".", "_yield_distributions", "(", ")", ":", "yield", "dist", "else", ":", "self", ".", "_generate_cache", "(", ")", "for", "d...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.get_distribution
Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None``
pipenv/vendor/distlib/database.py
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
[ "Looks", "for", "a", "named", "distribution", "on", "the", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L222-L246
[ "def", "get_distribution", "(", "self", ",", "name", ")", ":", "result", "=", "None", "name", "=", "name", ".", "lower", "(", ")", "if", "not", "self", ".", "_cache_enabled", ":", "for", "dist", "in", "self", ".", "_yield_distributions", "(", ")", ":",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.provides_distribution
Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string
pipenv/vendor/distlib/database.py
def provides_distribution(self, name, version=None): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string """ matcher = None if version is not None: try: matcher = self._scheme.matcher('%s (%s)' % (name, version)) except ValueError: raise DistlibException('invalid name or version: %r, %r' % (name, version)) for dist in self.get_distributions(): # We hit a problem on Travis where enum34 was installed and doesn't # have a provides attribute ... if not hasattr(dist, 'provides'): logger.debug('No "provides": %s', dist) else: provided = dist.provides for p in provided: p_name, p_ver = parse_name_and_version(p) if matcher is None: if p_name == name: yield dist break else: if p_name == name and matcher.match(p_ver): yield dist break
def provides_distribution(self, name, version=None): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string """ matcher = None if version is not None: try: matcher = self._scheme.matcher('%s (%s)' % (name, version)) except ValueError: raise DistlibException('invalid name or version: %r, %r' % (name, version)) for dist in self.get_distributions(): # We hit a problem on Travis where enum34 was installed and doesn't # have a provides attribute ... if not hasattr(dist, 'provides'): logger.debug('No "provides": %s', dist) else: provided = dist.provides for p in provided: p_name, p_ver = parse_name_and_version(p) if matcher is None: if p_name == name: yield dist break else: if p_name == name and matcher.match(p_ver): yield dist break
[ "Iterates", "over", "all", "distributions", "to", "find", "which", "distributions", "provide", "*", "name", "*", ".", "If", "a", "*", "version", "*", "is", "provided", "it", "will", "be", "used", "to", "filter", "the", "results", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L248-L287
[ "def", "provides_distribution", "(", "self", ",", "name", ",", "version", "=", "None", ")", ":", "matcher", "=", "None", "if", "version", "is", "not", "None", ":", "try", ":", "matcher", "=", "self", ".", "_scheme", ".", "matcher", "(", "'%s (%s)'", "%...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.get_file_path
Return the path to a resource file.
pipenv/vendor/distlib/database.py
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
[ "Return", "the", "path", "to", "a", "resource", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L289-L296
[ "def", "get_file_path", "(", "self", ",", "name", ",", "relative_path", ")", ":", "dist", "=", "self", ".", "get_distribution", "(", "name", ")", "if", "dist", "is", "None", ":", "raise", "LookupError", "(", "'no distribution named %r found'", "%", "name", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DistributionPath.get_exported_entries
Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned.
pipenv/vendor/distlib/database.py
def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned. """ for dist in self.get_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: yield d[name] else: for v in d.values(): yield v
def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned. """ for dist in self.get_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: yield d[name] else: for v in d.values(): yield v
[ "Return", "all", "of", "the", "exported", "entries", "in", "a", "particular", "category", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L298-L314
[ "def", "get_exported_entries", "(", "self", ",", "category", ",", "name", "=", "None", ")", ":", "for", "dist", "in", "self", ".", "get_distributions", "(", ")", ":", "r", "=", "dist", ".", "exports", "if", "category", "in", "r", ":", "d", "=", "r", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Distribution.provides
A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings.
pipenv/vendor/distlib/database.py
def provides(self): """ A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings. """ plist = self.metadata.provides s = '%s (%s)' % (self.name, self.version) if s not in plist: plist.append(s) return plist
def provides(self): """ A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings. """ plist = self.metadata.provides s = '%s (%s)' % (self.name, self.version) if s not in plist: plist.append(s) return plist
[ "A", "set", "of", "distribution", "names", "and", "versions", "provided", "by", "this", "distribution", ".", ":", "return", ":", "A", "set", "of", "name", "(", "version", ")", "strings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L369-L378
[ "def", "provides", "(", "self", ")", ":", "plist", "=", "self", ".", "metadata", ".", "provides", "s", "=", "'%s (%s)'", "%", "(", "self", ".", "name", ",", "self", ".", "version", ")", "if", "s", "not", "in", "plist", ":", "plist", ".", "append", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Distribution.matches_requirement
Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False.
pipenv/vendor/distlib/database.py
def matches_requirement(self, req): """ Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. """ # Requirement may contain extras - parse to lose those # from what's passed to the matcher r = parse_requirement(req) scheme = get_scheme(self.metadata.scheme) try: matcher = scheme.matcher(r.requirement) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive result = False for p in self.provides: p_name, p_ver = parse_name_and_version(p) if p_name != name: continue try: result = matcher.match(p_ver) break except UnsupportedVersionError: pass return result
def matches_requirement(self, req): """ Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. """ # Requirement may contain extras - parse to lose those # from what's passed to the matcher r = parse_requirement(req) scheme = get_scheme(self.metadata.scheme) try: matcher = scheme.matcher(r.requirement) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive result = False for p in self.provides: p_name, p_ver = parse_name_and_version(p) if p_name != name: continue try: result = matcher.match(p_ver) break except UnsupportedVersionError: pass return result
[ "Say", "if", "this", "instance", "matches", "(", "fulfills", ")", "a", "requirement", ".", ":", "param", "req", ":", "The", "requirement", "to", "match", ".", ":", "rtype", "req", ":", "str", ":", "return", ":", "True", "if", "it", "matches", "else", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L407-L439
[ "def", "matches_requirement", "(", "self", ",", "req", ")", ":", "# Requirement may contain extras - parse to lose those", "# from what's passed to the matcher", "r", "=", "parse_requirement", "(", "req", ")", "scheme", "=", "get_scheme", "(", "self", ".", "metadata", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BaseInstalledDistribution.get_hash
Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str
pipenv/vendor/distlib/database.py
def get_hash(self, data, hasher=None): """ Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str """ if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(data).digest() digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii') return '%s%s' % (prefix, digest)
def get_hash(self, data, hasher=None): """ Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str """ if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(data).digest() digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii') return '%s%s' % (prefix, digest)
[ "Get", "the", "hash", "of", "some", "data", "using", "a", "particular", "hash", "algorithm", "if", "specified", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L497-L526
[ "def", "get_hash", "(", "self", ",", "data", ",", "hasher", "=", "None", ")", ":", "if", "hasher", "is", "None", ":", "hasher", "=", "self", ".", "hasher", "if", "hasher", "is", "None", ":", "hasher", "=", "hashlib", ".", "md5", "prefix", "=", "''"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution._get_records
Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376).
pipenv/vendor/distlib/database.py
def _get_records(self): """ Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376). """ results = [] r = self.get_distinfo_resource('RECORD') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as record_reader: # Base location is parent dir of .dist-info dir #base_location = os.path.dirname(self.path) #base_location = os.path.abspath(base_location) for row in record_reader: missing = [None for i in range(len(row), 3)] path, checksum, size = row + missing #if not os.path.isabs(path): # path = path.replace('/', os.sep) # path = os.path.join(base_location, path) results.append((path, checksum, size)) return results
def _get_records(self): """ Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376). """ results = [] r = self.get_distinfo_resource('RECORD') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as record_reader: # Base location is parent dir of .dist-info dir #base_location = os.path.dirname(self.path) #base_location = os.path.abspath(base_location) for row in record_reader: missing = [None for i in range(len(row), 3)] path, checksum, size = row + missing #if not os.path.isabs(path): # path = path.replace('/', os.sep) # path = os.path.join(base_location, path) results.append((path, checksum, size)) return results
[ "Get", "the", "list", "of", "installed", "files", "for", "the", "distribution", ":", "return", ":", "A", "list", "of", "tuples", "of", "path", "hash", "and", "size", ".", "Note", "that", "hash", "and", "size", "might", "be", "None", "for", "some", "ent...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L580-L601
[ "def", "_get_records", "(", "self", ")", ":", "results", "=", "[", "]", "r", "=", "self", ".", "get_distinfo_resource", "(", "'RECORD'", ")", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "with", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.exports
Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name.
pipenv/vendor/distlib/database.py
def exports(self): """ Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: result = self.read_exports() return result
def exports(self): """ Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: result = self.read_exports() return result
[ "Return", "the", "information", "exported", "by", "this", "distribution", ".", ":", "return", ":", "A", "dictionary", "of", "exports", "mapping", "an", "export", "category", "to", "a", "dict", "of", ":", "class", ":", "ExportEntry", "instances", "describing", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L604-L615
[ "def", "exports", "(", "self", ")", ":", "result", "=", "{", "}", "r", "=", "self", ".", "get_distinfo_resource", "(", "EXPORTS_FILENAME", ")", "if", "r", ":", "result", "=", "self", ".", "read_exports", "(", ")", "return", "result" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.read_exports
Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
pipenv/vendor/distlib/database.py
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
[ "Read", "exports", "data", "from", "a", "file", "in", ".", "ini", "format", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L617-L630
[ "def", "read_exports", "(", "self", ")", ":", "result", "=", "{", "}", "r", "=", "self", ".", "get_distinfo_resource", "(", "EXPORTS_FILENAME", ")", "if", "r", ":", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.write_exports
Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
pipenv/vendor/distlib/database.py
def write_exports(self, exports): """ Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
def write_exports(self, exports): """ Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
[ "Write", "a", "dictionary", "of", "exports", "to", "a", "file", "in", ".", "ini", "format", ".", ":", "param", "exports", ":", "A", "dictionary", "of", "exports", "mapping", "an", "export", "category", "to", "a", "list", "of", ":", "class", ":", "Expor...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L632-L641
[ "def", "write_exports", "(", "self", ",", "exports", ")", ":", "rf", "=", "self", ".", "get_distinfo_file", "(", "EXPORTS_FILENAME", ")", "with", "open", "(", "rf", ",", "'w'", ")", "as", "f", ":", "write_exports", "(", "exports", ",", "f", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.get_resource_path
NOTE: This API may change in the future. Return the absolute path to a resource file with the given relative path. :param relative_path: The path, relative to .dist-info, of the resource of interest. :return: The absolute path where the resource is to be found.
pipenv/vendor/distlib/database.py
def get_resource_path(self, relative_path): """ NOTE: This API may change in the future. Return the absolute path to a resource file with the given relative path. :param relative_path: The path, relative to .dist-info, of the resource of interest. :return: The absolute path where the resource is to be found. """ r = self.get_distinfo_resource('RESOURCES') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as resources_reader: for relative, destination in resources_reader: if relative == relative_path: return destination raise KeyError('no resource file with relative path %r ' 'is installed' % relative_path)
def get_resource_path(self, relative_path): """ NOTE: This API may change in the future. Return the absolute path to a resource file with the given relative path. :param relative_path: The path, relative to .dist-info, of the resource of interest. :return: The absolute path where the resource is to be found. """ r = self.get_distinfo_resource('RESOURCES') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as resources_reader: for relative, destination in resources_reader: if relative == relative_path: return destination raise KeyError('no resource file with relative path %r ' 'is installed' % relative_path)
[ "NOTE", ":", "This", "API", "may", "change", "in", "the", "future", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L643-L661
[ "def", "get_resource_path", "(", "self", ",", "relative_path", ")", ":", "r", "=", "self", ".", "get_distinfo_resource", "(", "'RESOURCES'", ")", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "with", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.write_installed_files
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths.
pipenv/vendor/distlib/database.py
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
[ "Writes", "the", "RECORD", "file", "using", "the", "paths", "iterable", "passed", "in", ".", "Any", "existing", "RECORD", "file", "is", "silently", "overwritten", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L673-L706
[ "def", "write_installed_files", "(", "self", ",", "paths", ",", "prefix", ",", "dry_run", "=", "False", ")", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "''", ")", "base", "=", "os", ".", "path", ".", "dirname", "(", "se...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.check_installed_files
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
pipenv/vendor/distlib/database.py
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] base = os.path.dirname(self.path) record_path = self.get_distinfo_file('RECORD') for path, hash_value, size in self.list_installed_files(): if not os.path.isabs(path): path = os.path.join(base, path) if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) elif os.path.isfile(path): actual_size = str(os.path.getsize(path)) if size and actual_size != size: mismatches.append((path, 'size', size, actual_size)) elif hash_value: if '=' in hash_value: hasher = hash_value.split('=', 1)[0] else: hasher = None with open(path, 'rb') as f: actual_hash = self.get_hash(f.read(), hasher) if actual_hash != hash_value: mismatches.append((path, 'hash', hash_value, actual_hash)) return mismatches
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] base = os.path.dirname(self.path) record_path = self.get_distinfo_file('RECORD') for path, hash_value, size in self.list_installed_files(): if not os.path.isabs(path): path = os.path.join(base, path) if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) elif os.path.isfile(path): actual_size = str(os.path.getsize(path)) if size and actual_size != size: mismatches.append((path, 'size', size, actual_size)) elif hash_value: if '=' in hash_value: hasher = hash_value.split('=', 1)[0] else: hasher = None with open(path, 'rb') as f: actual_hash = self.get_hash(f.read(), hasher) if actual_hash != hash_value: mismatches.append((path, 'hash', hash_value, actual_hash)) return mismatches
[ "Checks", "that", "the", "hashes", "and", "sizes", "of", "the", "files", "in", "RECORD", "are", "matched", "by", "the", "files", "themselves", ".", "Returns", "a", "(", "possibly", "empty", ")", "list", "of", "mismatches", ".", "Each", "entry", "in", "th...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L708-L741
[ "def", "check_installed_files", "(", "self", ")", ":", "mismatches", "=", "[", "]", "base", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "record_path", "=", "self", ".", "get_distinfo_file", "(", "'RECORD'", ")", "for", "path", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.shared_locations
A dictionary of shared locations whose keys are in the set 'prefix', 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'. The corresponding value is the absolute path of that category for this distribution, and takes into account any paths selected by the user at installation time (e.g. via command-line arguments). In the case of the 'namespace' key, this would be a list of absolute paths for the roots of namespace packages in this distribution. The first time this property is accessed, the relevant information is read from the SHARED file in the .dist-info directory.
pipenv/vendor/distlib/database.py
def shared_locations(self): """ A dictionary of shared locations whose keys are in the set 'prefix', 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'. The corresponding value is the absolute path of that category for this distribution, and takes into account any paths selected by the user at installation time (e.g. via command-line arguments). In the case of the 'namespace' key, this would be a list of absolute paths for the roots of namespace packages in this distribution. The first time this property is accessed, the relevant information is read from the SHARED file in the .dist-info directory. """ result = {} shared_path = os.path.join(self.path, 'SHARED') if os.path.isfile(shared_path): with codecs.open(shared_path, 'r', encoding='utf-8') as f: lines = f.read().splitlines() for line in lines: key, value = line.split('=', 1) if key == 'namespace': result.setdefault(key, []).append(value) else: result[key] = value return result
def shared_locations(self): """ A dictionary of shared locations whose keys are in the set 'prefix', 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'. The corresponding value is the absolute path of that category for this distribution, and takes into account any paths selected by the user at installation time (e.g. via command-line arguments). In the case of the 'namespace' key, this would be a list of absolute paths for the roots of namespace packages in this distribution. The first time this property is accessed, the relevant information is read from the SHARED file in the .dist-info directory. """ result = {} shared_path = os.path.join(self.path, 'SHARED') if os.path.isfile(shared_path): with codecs.open(shared_path, 'r', encoding='utf-8') as f: lines = f.read().splitlines() for line in lines: key, value = line.split('=', 1) if key == 'namespace': result.setdefault(key, []).append(value) else: result[key] = value return result
[ "A", "dictionary", "of", "shared", "locations", "whose", "keys", "are", "in", "the", "set", "prefix", "purelib", "platlib", "scripts", "headers", "data", "and", "namespace", ".", "The", "corresponding", "value", "is", "the", "absolute", "path", "of", "that", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L744-L768
[ "def", "shared_locations", "(", "self", ")", ":", "result", "=", "{", "}", "shared_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'SHARED'", ")", "if", "os", ".", "path", ".", "isfile", "(", "shared_path", ")", ":", "wi...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.write_shared_locations
Write shared location information to the SHARED file in .dist-info. :param paths: A dictionary as described in the documentation for :meth:`shared_locations`. :param dry_run: If True, the action is logged but no file is actually written. :return: The path of the file written to.
pipenv/vendor/distlib/database.py
def write_shared_locations(self, paths, dry_run=False): """ Write shared location information to the SHARED file in .dist-info. :param paths: A dictionary as described in the documentation for :meth:`shared_locations`. :param dry_run: If True, the action is logged but no file is actually written. :return: The path of the file written to. """ shared_path = os.path.join(self.path, 'SHARED') logger.info('creating %s', shared_path) if dry_run: return None lines = [] for key in ('prefix', 'lib', 'headers', 'scripts', 'data'): path = paths[key] if os.path.isdir(paths[key]): lines.append('%s=%s' % (key, path)) for ns in paths.get('namespace', ()): lines.append('namespace=%s' % ns) with codecs.open(shared_path, 'w', encoding='utf-8') as f: f.write('\n'.join(lines)) return shared_path
def write_shared_locations(self, paths, dry_run=False): """ Write shared location information to the SHARED file in .dist-info. :param paths: A dictionary as described in the documentation for :meth:`shared_locations`. :param dry_run: If True, the action is logged but no file is actually written. :return: The path of the file written to. """ shared_path = os.path.join(self.path, 'SHARED') logger.info('creating %s', shared_path) if dry_run: return None lines = [] for key in ('prefix', 'lib', 'headers', 'scripts', 'data'): path = paths[key] if os.path.isdir(paths[key]): lines.append('%s=%s' % (key, path)) for ns in paths.get('namespace', ()): lines.append('namespace=%s' % ns) with codecs.open(shared_path, 'w', encoding='utf-8') as f: f.write('\n'.join(lines)) return shared_path
[ "Write", "shared", "location", "information", "to", "the", "SHARED", "file", "in", ".", "dist", "-", "info", ".", ":", "param", "paths", ":", "A", "dictionary", "as", "described", "in", "the", "documentation", "for", ":", "meth", ":", "shared_locations", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L770-L793
[ "def", "write_shared_locations", "(", "self", ",", "paths", ",", "dry_run", "=", "False", ")", ":", "shared_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'SHARED'", ")", "logger", ".", "info", "(", "'creating %s'", ",", "s...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.get_distinfo_file
Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str
pipenv/vendor/distlib/database.py
def get_distinfo_file(self, path): """ Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str """ # Check if it is an absolute path # XXX use relpath, add tests if path.find(os.sep) >= 0: # it's an absolute path? distinfo_dirname, path = path.split(os.sep)[-2:] if distinfo_dirname != self.path.split(os.sep)[-1]: raise DistlibException( 'dist-info file %r does not belong to the %r %s ' 'distribution' % (path, self.name, self.version)) # The file must be relative if path not in DIST_FILES: raise DistlibException('invalid path for a dist-info file: ' '%r at %r' % (path, self.path)) return os.path.join(self.path, path)
def get_distinfo_file(self, path): """ Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str """ # Check if it is an absolute path # XXX use relpath, add tests if path.find(os.sep) >= 0: # it's an absolute path? distinfo_dirname, path = path.split(os.sep)[-2:] if distinfo_dirname != self.path.split(os.sep)[-1]: raise DistlibException( 'dist-info file %r does not belong to the %r %s ' 'distribution' % (path, self.name, self.version)) # The file must be relative if path not in DIST_FILES: raise DistlibException('invalid path for a dist-info file: ' '%r at %r' % (path, self.path)) return os.path.join(self.path, path)
[ "Returns", "a", "path", "located", "under", "the", ".", "dist", "-", "info", "directory", ".", "Returns", "a", "string", "representing", "the", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L804-L831
[ "def", "get_distinfo_file", "(", "self", ",", "path", ")", ":", "# Check if it is an absolute path # XXX use relpath, add tests", "if", "path", ".", "find", "(", "os", ".", "sep", ")", ">=", "0", ":", "# it's an absolute path?", "distinfo_dirname", ",", "path", "="...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InstalledDistribution.list_distinfo_files
Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths
pipenv/vendor/distlib/database.py
def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths """ base = os.path.dirname(self.path) for path, checksum, size in self._get_records(): # XXX add separator or use real relpath algo if not os.path.isabs(path): path = os.path.join(base, path) if path.startswith(self.path): yield path
def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths """ base = os.path.dirname(self.path) for path, checksum, size in self._get_records(): # XXX add separator or use real relpath algo if not os.path.isabs(path): path = os.path.join(base, path) if path.startswith(self.path): yield path
[ "Iterates", "over", "the", "RECORD", "entries", "and", "returns", "paths", "for", "each", "line", "if", "the", "path", "is", "pointing", "to", "a", "file", "located", "in", "the", ".", "dist", "-", "info", "directory", "or", "one", "of", "its", "subdirec...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L833-L847
[ "def", "list_distinfo_files", "(", "self", ")", ":", "base", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "for", "path", ",", "checksum", ",", "size", "in", "self", ".", "_get_records", "(", ")", ":", "# XXX add separator or use...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
EggInfoDistribution.check_installed_files
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
pipenv/vendor/distlib/database.py
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) return mismatches
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) return mismatches
[ "Checks", "that", "the", "hashes", "and", "sizes", "of", "the", "files", "in", "RECORD", "are", "matched", "by", "the", "files", "themselves", ".", "Returns", "a", "(", "possibly", "empty", ")", "list", "of", "mismatches", ".", "Each", "entry", "in", "th...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L984-L1001
[ "def", "check_installed_files", "(", "self", ")", ":", "mismatches", "=", "[", "]", "record_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'installed-files.txt'", ")", "if", "os", ".", "path", ".", "exists", "(", "record_path...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
EggInfoDistribution.list_installed_files
Iterates over the ``installed-files.txt`` entries and returns a tuple ``(path, hash, size)`` for each line. :returns: a list of (path, hash, size)
pipenv/vendor/distlib/database.py
def list_installed_files(self): """ Iterates over the ``installed-files.txt`` entries and returns a tuple ``(path, hash, size)`` for each line. :returns: a list of (path, hash, size) """ def _md5(path): f = open(path, 'rb') try: content = f.read() finally: f.close() return hashlib.md5(content).hexdigest() def _size(path): return os.stat(path).st_size record_path = os.path.join(self.path, 'installed-files.txt') result = [] if os.path.exists(record_path): with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() p = os.path.normpath(os.path.join(self.path, line)) # "./" is present as a marker between installed files # and installation metadata files if not os.path.exists(p): logger.warning('Non-existent file: %s', p) if p.endswith(('.pyc', '.pyo')): continue #otherwise fall through and fail if not os.path.isdir(p): result.append((p, _md5(p), _size(p))) result.append((record_path, None, None)) return result
def list_installed_files(self): """ Iterates over the ``installed-files.txt`` entries and returns a tuple ``(path, hash, size)`` for each line. :returns: a list of (path, hash, size) """ def _md5(path): f = open(path, 'rb') try: content = f.read() finally: f.close() return hashlib.md5(content).hexdigest() def _size(path): return os.stat(path).st_size record_path = os.path.join(self.path, 'installed-files.txt') result = [] if os.path.exists(record_path): with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() p = os.path.normpath(os.path.join(self.path, line)) # "./" is present as a marker between installed files # and installation metadata files if not os.path.exists(p): logger.warning('Non-existent file: %s', p) if p.endswith(('.pyc', '.pyo')): continue #otherwise fall through and fail if not os.path.isdir(p): result.append((p, _md5(p), _size(p))) result.append((record_path, None, None)) return result
[ "Iterates", "over", "the", "installed", "-", "files", ".", "txt", "entries", "and", "returns", "a", "tuple", "(", "path", "hash", "size", ")", "for", "each", "line", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1003-L1039
[ "def", "list_installed_files", "(", "self", ")", ":", "def", "_md5", "(", "path", ")", ":", "f", "=", "open", "(", "path", ",", "'rb'", ")", "try", ":", "content", "=", "f", ".", "read", "(", ")", "finally", ":", "f", ".", "close", "(", ")", "r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
EggInfoDistribution.list_distinfo_files
Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths
pipenv/vendor/distlib/database.py
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths """ record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): skip = True with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line == './': skip = False continue if not skip: p = os.path.normpath(os.path.join(self.path, line)) if p.startswith(self.path): if absolute: yield p else: yield line
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths """ record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): skip = True with codecs.open(record_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line == './': skip = False continue if not skip: p = os.path.normpath(os.path.join(self.path, line)) if p.startswith(self.path): if absolute: yield p else: yield line
[ "Iterates", "over", "the", "installed", "-", "files", ".", "txt", "entries", "and", "returns", "paths", "for", "each", "line", "if", "the", "path", "is", "pointing", "to", "a", "file", "located", "in", "the", ".", "egg", "-", "info", "directory", "or", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1041-L1068
[ "def", "list_distinfo_files", "(", "self", ",", "absolute", "=", "False", ")", ":", "record_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'installed-files.txt'", ")", "if", "os", ".", "path", ".", "exists", "(", "record_path...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DependencyGraph.add_edge
Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type label: ``str`` or ``None``
pipenv/vendor/distlib/database.py
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type label: ``str`` or ``None`` """ self.adjacency_list[x].append((y, label)) # multiple edges are allowed, so be careful if x not in self.reverse_list[y]: self.reverse_list[y].append(x)
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type label: ``str`` or ``None`` """ self.adjacency_list[x].append((y, label)) # multiple edges are allowed, so be careful if x not in self.reverse_list[y]: self.reverse_list[y].append(x)
[ "Add", "an", "edge", "from", "distribution", "*", "x", "*", "to", "distribution", "*", "y", "*", "with", "the", "given", "*", "label", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1112-L1125
[ "def", "add_edge", "(", "self", ",", "x", ",", "y", ",", "label", "=", "None", ")", ":", "self", ".", "adjacency_list", "[", "x", "]", ".", "append", "(", "(", "y", ",", "label", ")", ")", "# multiple edges are allowed, so be careful", "if", "x", "not"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DependencyGraph.add_missing
Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str``
pipenv/vendor/distlib/database.py
def add_missing(self, distribution, requirement): """ Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str`` """ logger.debug('%s missing %r', distribution, requirement) self.missing.setdefault(distribution, []).append(requirement)
def add_missing(self, distribution, requirement): """ Add a missing *requirement* for the given *distribution*. :type distribution: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type requirement: ``str`` """ logger.debug('%s missing %r', distribution, requirement) self.missing.setdefault(distribution, []).append(requirement)
[ "Add", "a", "missing", "*", "requirement", "*", "for", "the", "given", "*", "distribution", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1127-L1136
[ "def", "add_missing", "(", "self", ",", "distribution", ",", "requirement", ")", ":", "logger", ".", "debug", "(", "'%s missing %r'", ",", "distribution", ",", "requirement", ")", "self", ".", "missing", ".", "setdefault", "(", "distribution", ",", "[", "]",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DependencyGraph.repr_node
Prints only a subgraph
pipenv/vendor/distlib/database.py
def repr_node(self, dist, level=1): """Prints only a subgraph""" output = [self._repr_dist(dist)] for other, label in self.adjacency_list[dist]: dist = self._repr_dist(other) if label is not None: dist = '%s [%s]' % (dist, label) output.append(' ' * level + str(dist)) suboutput = self.repr_node(other, level + 1) subs = suboutput.split('\n') output.extend(subs[1:]) return '\n'.join(output)
def repr_node(self, dist, level=1): """Prints only a subgraph""" output = [self._repr_dist(dist)] for other, label in self.adjacency_list[dist]: dist = self._repr_dist(other) if label is not None: dist = '%s [%s]' % (dist, label) output.append(' ' * level + str(dist)) suboutput = self.repr_node(other, level + 1) subs = suboutput.split('\n') output.extend(subs[1:]) return '\n'.join(output)
[ "Prints", "only", "a", "subgraph" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1141-L1152
[ "def", "repr_node", "(", "self", ",", "dist", ",", "level", "=", "1", ")", ":", "output", "=", "[", "self", ".", "_repr_dist", "(", "dist", ")", "]", "for", "other", ",", "label", "in", "self", ".", "adjacency_list", "[", "dist", "]", ":", "dist", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DependencyGraph.to_dot
Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations :type skip_disconnected: ``bool``
pipenv/vendor/distlib/database.py
def to_dot(self, f, skip_disconnected=True): """Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations :type skip_disconnected: ``bool`` """ disconnected = [] f.write("digraph dependencies {\n") for dist, adjs in self.adjacency_list.items(): if len(adjs) == 0 and not skip_disconnected: disconnected.append(dist) for other, label in adjs: if not label is None: f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, other.name, label)) else: f.write('"%s" -> "%s"\n' % (dist.name, other.name)) if not skip_disconnected and len(disconnected) > 0: f.write('subgraph disconnected {\n') f.write('label = "Disconnected"\n') f.write('bgcolor = red\n') for dist in disconnected: f.write('"%s"' % dist.name) f.write('\n') f.write('}\n') f.write('}\n')
def to_dot(self, f, skip_disconnected=True): """Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations :type skip_disconnected: ``bool`` """ disconnected = [] f.write("digraph dependencies {\n") for dist, adjs in self.adjacency_list.items(): if len(adjs) == 0 and not skip_disconnected: disconnected.append(dist) for other, label in adjs: if not label is None: f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, other.name, label)) else: f.write('"%s" -> "%s"\n' % (dist.name, other.name)) if not skip_disconnected and len(disconnected) > 0: f.write('subgraph disconnected {\n') f.write('label = "Disconnected"\n') f.write('bgcolor = red\n') for dist in disconnected: f.write('"%s"' % dist.name) f.write('\n') f.write('}\n') f.write('}\n')
[ "Writes", "a", "DOT", "output", "for", "the", "graph", "to", "the", "provided", "file", "*", "f", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1154-L1184
[ "def", "to_dot", "(", "self", ",", "f", ",", "skip_disconnected", "=", "True", ")", ":", "disconnected", "=", "[", "]", "f", ".", "write", "(", "\"digraph dependencies {\\n\"", ")", "for", "dist", ",", "adjs", "in", "self", ".", "adjacency_list", ".", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
DependencyGraph.topological_sort
Perform a topological sort of the graph. :return: A tuple, the first element of which is a topologically sorted list of distributions, and the second element of which is a list of distributions that cannot be sorted because they have circular dependencies and so form a cycle.
pipenv/vendor/distlib/database.py
def topological_sort(self): """ Perform a topological sort of the graph. :return: A tuple, the first element of which is a topologically sorted list of distributions, and the second element of which is a list of distributions that cannot be sorted because they have circular dependencies and so form a cycle. """ result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): alist[k] = v[:] while True: # See what we can remove in this run to_remove = [] for k, v in list(alist.items())[:]: if not v: to_remove.append(k) del alist[k] if not to_remove: # What's left in alist (if anything) is a cycle. break # Remove from the adjacency list of others for k, v in alist.items(): alist[k] = [(d, r) for d, r in v if d not in to_remove] logger.debug('Moving to result: %s', ['%s (%s)' % (d.name, d.version) for d in to_remove]) result.extend(to_remove) return result, list(alist.keys())
def topological_sort(self): """ Perform a topological sort of the graph. :return: A tuple, the first element of which is a topologically sorted list of distributions, and the second element of which is a list of distributions that cannot be sorted because they have circular dependencies and so form a cycle. """ result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): alist[k] = v[:] while True: # See what we can remove in this run to_remove = [] for k, v in list(alist.items())[:]: if not v: to_remove.append(k) del alist[k] if not to_remove: # What's left in alist (if anything) is a cycle. break # Remove from the adjacency list of others for k, v in alist.items(): alist[k] = [(d, r) for d, r in v if d not in to_remove] logger.debug('Moving to result: %s', ['%s (%s)' % (d.name, d.version) for d in to_remove]) result.extend(to_remove) return result, list(alist.keys())
[ "Perform", "a", "topological", "sort", "of", "the", "graph", ".", ":", "return", ":", "A", "tuple", "the", "first", "element", "of", "which", "is", "a", "topologically", "sorted", "list", "of", "distributions", "and", "the", "second", "element", "of", "whi...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1186-L1215
[ "def", "topological_sort", "(", "self", ")", ":", "result", "=", "[", "]", "# Make a shallow copy of the adjacency list", "alist", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "adjacency_list", ".", "items", "(", ")", ":", "alist", "[", "k", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
encode_unicode
Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function.
pipenv/vendor/cerberus/errors.py
def encode_unicode(f): """Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function. """ @wraps(f) def wrapped(obj, error): def _encode(value): """Helper encoding unicode strings into binary utf-8""" if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) error.document_path = _encode(error.document_path) error.schema_path = _encode(error.schema_path) error.constraint = _encode(error.constraint) error.value = _encode(error.value) error.info = _encode(error.info) return f(obj, error) return wrapped if PYTHON_VERSION < 3 else f
def encode_unicode(f): """Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function. """ @wraps(f) def wrapped(obj, error): def _encode(value): """Helper encoding unicode strings into binary utf-8""" if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) error.document_path = _encode(error.document_path) error.schema_path = _encode(error.schema_path) error.constraint = _encode(error.constraint) error.value = _encode(error.value) error.info = _encode(error.info) return f(obj, error) return wrapped if PYTHON_VERSION < 3 else f
[ "Cerberus", "error", "messages", "expect", "regular", "binary", "strings", ".", "If", "unicode", "is", "used", "in", "a", "ValidationError", "message", "can", "t", "be", "printed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L407-L431
[ "def", "encode_unicode", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "obj", ",", "error", ")", ":", "def", "_encode", "(", "value", ")", ":", "\"\"\"Helper encoding unicode strings into binary utf-8\"\"\"", "if", "isinstance", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ValidationError.definitions_errors
Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns :obj:`None` if not applicable.
pipenv/vendor/cerberus/errors.py
def definitions_errors(self): """ Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns :obj:`None` if not applicable. """ if not self.is_logic_error: return None result = defaultdict(list) for error in self.child_errors: i = error.schema_path[len(self.schema_path)] result[i].append(error) return result
def definitions_errors(self): """ Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns :obj:`None` if not applicable. """ if not self.is_logic_error: return None result = defaultdict(list) for error in self.child_errors: i = error.schema_path[len(self.schema_path)] result[i].append(error) return result
[ "Dictionary", "with", "errors", "of", "an", "*", "of", "-", "rule", "mapped", "to", "the", "index", "of", "the", "definition", "it", "occurred", "in", ".", "Returns", ":", "obj", ":", "None", "if", "not", "applicable", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L151-L162
[ "def", "definitions_errors", "(", "self", ")", ":", "if", "not", "self", ".", "is_logic_error", ":", "return", "None", "result", "=", "defaultdict", "(", "list", ")", "for", "error", "in", "self", ".", "child_errors", ":", "i", "=", "error", ".", "schema...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ErrorTree.add
Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError`
pipenv/vendor/cerberus/errors.py
def add(self, error): """ Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` """ if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
def add(self, error): """ Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` """ if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
[ "Add", "an", "error", "to", "the", "tree", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L286-L295
[ "def", "add", "(", "self", ",", "error", ")", ":", "if", "not", "self", ".", "_path_of_", "(", "error", ")", ":", "self", ".", "errors", ".", "append", "(", "error", ")", "self", ".", "errors", ".", "sort", "(", ")", "else", ":", "super", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ErrorTree.fetch_errors_from
Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList`
pipenv/vendor/cerberus/errors.py
def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
[ "Returns", "all", "errors", "for", "a", "particular", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L297-L307
[ "def", "fetch_errors_from", "(", "self", ",", "path", ")", ":", "node", "=", "self", ".", "fetch_node_from", "(", "path", ")", "if", "node", "is", "not", "None", ":", "return", "node", ".", "errors", "else", ":", "return", "ErrorList", "(", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ErrorTree.fetch_node_from
Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None`
pipenv/vendor/cerberus/errors.py
def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None: break return context
def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None: break return context
[ "Returns", "a", "node", "for", "a", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L309-L320
[ "def", "fetch_node_from", "(", "self", ",", "path", ")", ":", "context", "=", "self", "for", "key", "in", "path", ":", "context", "=", "context", "[", "key", "]", "if", "context", "is", "None", ":", "break", "return", "context" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BasicErrorHandler._insert_error
Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary.
pipenv/vendor/cerberus/errors.py
def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. """ field = path[0] if len(path) == 1: if field in self.tree: subtree = self.tree[field].pop() self.tree[field] += [node, subtree] else: self.tree[field] = [node, {}] elif len(path) >= 1: if field not in self.tree: self.tree[field] = [{}] subtree = self.tree[field][-1] if subtree: new = self.__class__(tree=copy(subtree)) else: new = self.__class__() new._insert_error(path[1:], node) subtree.update(new.tree)
def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. """ field = path[0] if len(path) == 1: if field in self.tree: subtree = self.tree[field].pop() self.tree[field] += [node, subtree] else: self.tree[field] = [node, {}] elif len(path) >= 1: if field not in self.tree: self.tree[field] = [{}] subtree = self.tree[field][-1] if subtree: new = self.__class__(tree=copy(subtree)) else: new = self.__class__() new._insert_error(path[1:], node) subtree.update(new.tree)
[ "Adds", "an", "error", "or", "sub", "-", "tree", "to", ":", "attr", ":", "tree", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L528-L553
[ "def", "_insert_error", "(", "self", ",", "path", ",", "node", ")", ":", "field", "=", "path", "[", "0", "]", "if", "len", "(", "path", ")", "==", "1", ":", "if", "field", "in", "self", ".", "tree", ":", "subtree", "=", "self", ".", "tree", "["...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BasicErrorHandler._rewrite_error_path
Recursively rewrites the error path to correctly represent logic errors
pipenv/vendor/cerberus/errors.py
def _rewrite_error_path(self, error, offset=0): """ Recursively rewrites the error path to correctly represent logic errors """ if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
def _rewrite_error_path(self, error, offset=0): """ Recursively rewrites the error path to correctly represent logic errors """ if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
[ "Recursively", "rewrites", "the", "error", "path", "to", "correctly", "represent", "logic", "errors" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L589-L596
[ "def", "_rewrite_error_path", "(", "self", ",", "error", ",", "offset", "=", "0", ")", ":", "if", "error", ".", "is_logic_error", ":", "self", ".", "_rewrite_logic_error_path", "(", "error", ",", "offset", ")", "elif", "error", ".", "is_group_error", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
dispatch_hook
Dispatches a hook dictionary on a given piece of data.
pipenv/vendor/requests/hooks.py
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
[ "Dispatches", "a", "hook", "dictionary", "on", "a", "given", "piece", "of", "data", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/hooks.py#L23-L34
[ "def", "dispatch_hook", "(", "key", ",", "hooks", ",", "hook_data", ",", "*", "*", "kwargs", ")", ":", "hooks", "=", "hooks", "or", "{", "}", "hooks", "=", "hooks", ".", "get", "(", "key", ")", "if", "hooks", ":", "if", "hasattr", "(", "hooks", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
cli
This script is used to set, get or unset values from a .env file.
pipenv/vendor/dotenv/cli.py
def cli(ctx, file, quote): '''This script is used to set, get or unset values from a .env file.''' ctx.obj = {} ctx.obj['FILE'] = file ctx.obj['QUOTE'] = quote
def cli(ctx, file, quote): '''This script is used to set, get or unset values from a .env file.''' ctx.obj = {} ctx.obj['FILE'] = file ctx.obj['QUOTE'] = quote
[ "This", "script", "is", "used", "to", "set", "get", "or", "unset", "values", "from", "a", ".", "env", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L24-L28
[ "def", "cli", "(", "ctx", ",", "file", ",", "quote", ")", ":", "ctx", ".", "obj", "=", "{", "}", "ctx", ".", "obj", "[", "'FILE'", "]", "=", "file", "ctx", ".", "obj", "[", "'QUOTE'", "]", "=", "quote" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
list
Display all the stored key/value.
pipenv/vendor/dotenv/cli.py
def list(ctx): '''Display all the stored key/value.''' file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) for k, v in dotenv_as_dict.items(): click.echo('%s=%s' % (k, v))
def list(ctx): '''Display all the stored key/value.''' file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) for k, v in dotenv_as_dict.items(): click.echo('%s=%s' % (k, v))
[ "Display", "all", "the", "stored", "key", "/", "value", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L33-L38
[ "def", "list", "(", "ctx", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "dotenv_as_dict", "=", "dotenv_values", "(", "file", ")", "for", "k", ",", "v", "in", "dotenv_as_dict", ".", "items", "(", ")", ":", "click", ".", "echo", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
set
Store the given key/value.
pipenv/vendor/dotenv/cli.py
def set(ctx, key, value): '''Store the given key/value.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key, value = set_key(file, key, value, quote) if success: click.echo('%s=%s' % (key, value)) else: exit(1)
def set(ctx, key, value): '''Store the given key/value.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key, value = set_key(file, key, value, quote) if success: click.echo('%s=%s' % (key, value)) else: exit(1)
[ "Store", "the", "given", "key", "/", "value", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L45-L53
[ "def", "set", "(", "ctx", ",", "key", ",", "value", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "quote", "=", "ctx", ".", "obj", "[", "'QUOTE'", "]", "success", ",", "key", ",", "value", "=", "set_key", "(", "file", ",", "key"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get
Retrieve the value for the given key.
pipenv/vendor/dotenv/cli.py
def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
[ "Retrieve", "the", "value", "for", "the", "given", "key", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L59-L66
[ "def", "get", "(", "ctx", ",", "key", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "stored_value", "=", "get_key", "(", "file", ",", "key", ")", "if", "stored_value", ":", "click", ".", "echo", "(", "'%s=%s'", "%", "(", "key", ",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
unset
Removes the given key.
pipenv/vendor/dotenv/cli.py
def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
[ "Removes", "the", "given", "key", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L72-L80
[ "def", "unset", "(", "ctx", ",", "key", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "quote", "=", "ctx", ".", "obj", "[", "'QUOTE'", "]", "success", ",", "key", "=", "unset_key", "(", "file", ",", "key", ",", "quote", ")", "if...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
run
Run command with environment variables present.
pipenv/vendor/dotenv/cli.py
def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
[ "Run", "command", "with", "environment", "variables", "present", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L86-L94
[ "def", "run", "(", "ctx", ",", "commandline", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "dotenv_as_dict", "=", "dotenv_values", "(", "file", ")", "if", "not", "commandline", ":", "click", ".", "echo", "(", "'No command given.'", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_is_installation_local
Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them.
pipenv/vendor/passa/models/synchronizers.py
def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
[ "Check", "whether", "the", "distribution", "is", "in", "the", "current", "Python", "installation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L20-L28
[ "def", "_is_installation_local", "(", "name", ")", ":", "loc", "=", "os", ".", "path", ".", "normcase", "(", "pkg_resources", ".", "working_set", ".", "by_key", "[", "name", "]", ".", "location", ")", "pre", "=", "os", ".", "path", ".", "normcase", "("...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_group_installed_names
Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`.
pipenv/vendor/passa/models/synchronizers.py
def _group_installed_names(packages): """Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. """ groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unneeded.add(name) continue r = requirementslib.Requirement.from_pipfile(name, package) if not r.is_named: # Always mark non-named. I think pip does something similar? groupcoll.outdated.add(name) elif not _is_up_to_date(distro, r.get_version()): groupcoll.outdated.add(name) else: groupcoll.uptodate.add(name) return groupcoll
def _group_installed_names(packages): """Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. """ groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unneeded.add(name) continue r = requirementslib.Requirement.from_pipfile(name, package) if not r.is_named: # Always mark non-named. I think pip does something similar? groupcoll.outdated.add(name) elif not _is_up_to_date(distro, r.get_version()): groupcoll.outdated.add(name) else: groupcoll.uptodate.add(name) return groupcoll
[ "Group", "locally", "installed", "packages", "based", "on", "given", "specifications", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L41-L74
[ "def", "_group_installed_names", "(", "packages", ")", ":", "groupcoll", "=", "GroupCollection", "(", "set", "(", ")", ",", "set", "(", ")", ",", "set", "(", ")", ",", "set", "(", ")", ")", "for", "distro", "in", "pkg_resources", ".", "working_set", ":...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_build_paths
Prepare paths for distlib.wheel.Wheel to install into.
pipenv/vendor/passa/models/synchronizers.py
def _build_paths(): """Prepare paths for distlib.wheel.Wheel to install into. """ paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "platlib": paths["platlib"], }
def _build_paths(): """Prepare paths for distlib.wheel.Wheel to install into. """ paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "platlib": paths["platlib"], }
[ "Prepare", "paths", "for", "distlib", ".", "wheel", ".", "Wheel", "to", "install", "into", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L98-L109
[ "def", "_build_paths", "(", ")", ":", "paths", "=", "sysconfig", ".", "get_paths", "(", ")", "return", "{", "\"prefix\"", ":", "sys", ".", "prefix", ",", "\"data\"", ":", "paths", "[", "\"data\"", "]", ",", "\"scripts\"", ":", "paths", "[", "\"scripts\""...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
dumps
Dumps a TOMLDocument into a string.
pipenv/vendor/tomlkit/api.py
def dumps(data): # type: (_TOMLDocument) -> str """ Dumps a TOMLDocument into a string. """ if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
def dumps(data): # type: (_TOMLDocument) -> str """ Dumps a TOMLDocument into a string. """ if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
[ "Dumps", "a", "TOMLDocument", "into", "a", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/api.py#L35-L42
[ "def", "dumps", "(", "data", ")", ":", "# type: (_TOMLDocument) -> str", "if", "not", "isinstance", "(", "data", ",", "_TOMLDocument", ")", "and", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "item", "(", "data", ")", "return", "data", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest.findall
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found.
pipenv/vendor/distlib/manifest.py
def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() names = os.listdir(root) for name in names: fullname = os.path.join(root, name) # Avoid excess stat calls -- just one will do, thank you! stat = os.stat(fullname) mode = stat.st_mode if S_ISREG(mode): allfiles.append(fsdecode(fullname)) elif S_ISDIR(mode) and not S_ISLNK(mode): push(fullname)
def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() names = os.listdir(root) for name in names: fullname = os.path.join(root, name) # Avoid excess stat calls -- just one will do, thank you! stat = os.stat(fullname) mode = stat.st_mode if S_ISREG(mode): allfiles.append(fsdecode(fullname)) elif S_ISDIR(mode) and not S_ISLNK(mode): push(fullname)
[ "Find", "all", "files", "under", "the", "base", "and", "set", "allfiles", "to", "the", "absolute", "pathnames", "of", "files", "found", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L57-L82
[ "def", "findall", "(", "self", ")", ":", "from", "stat", "import", "S_ISREG", ",", "S_ISDIR", ",", "S_ISLNK", "self", ".", "allfiles", "=", "allfiles", "=", "[", "]", "root", "=", "self", ".", "base", "stack", "=", "[", "root", "]", "pop", "=", "st...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest.add
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base.
pipenv/vendor/distlib/manifest.py
def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
[ "Add", "a", "file", "to", "the", "manifest", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L84-L92
[ "def", "add", "(", "self", ",", "item", ")", ":", "if", "not", "item", ".", "startswith", "(", "self", ".", "prefix", ")", ":", "item", "=", "os", ".", "path", ".", "join", "(", "self", ".", "base", ",", "item", ")", "self", ".", "files", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest.sorted
Return sorted files in directory order
pipenv/vendor/distlib/manifest.py
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
[ "Return", "sorted", "files", "in", "directory", "order" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L103-L123
[ "def", "sorted", "(", "self", ",", "wantdirs", "=", "False", ")", ":", "def", "add_dir", "(", "dirs", ",", "d", ")", ":", "dirs", ".", "add", "(", "d", ")", "logger", ".", "debug", "(", "'add_dir added %s'", ",", "d", ")", "if", "d", "!=", "self"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest.process_directive
Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.org/distutils/sourcedist.html#commands
pipenv/vendor/distlib/manifest.py
def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.org/distutils/sourcedist.html#commands """ # Parse the line: split it up, make sure the right number of words # is there, and return the relevant words. 'action' is always # defined: it's the first word of the line. Which of the other # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dirpattern). action, patterns, thedir, dirpattern = self._parse_directive(directive) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=True): logger.warning('no files found matching %r', pattern) elif action == 'exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=True) #if not found: # logger.warning('no previously-included files ' # 'found matching %r', pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=False): logger.warning('no files found matching %r ' 'anywhere in distribution', pattern) elif action == 'global-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=False) #if not found: # logger.warning('no previously-included files ' # 'matching %r found anywhere in ' # 'distribution', pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=thedir): logger.warning('no files found matching %r ' 'under directory %r', pattern, thedir) elif action == 'recursive-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, prefix=thedir) #if not found: # logger.warning('no previously-included files ' # 'matching %r found under directory %r', # pattern, thedir) elif action == 'graft': if not self._include_pattern(None, prefix=dirpattern): logger.warning('no directories found matching %r', dirpattern) elif action == 'prune': if not self._exclude_pattern(None, prefix=dirpattern): logger.warning('no previously-included directories found ' 'matching %r', dirpattern) else: # pragma: no cover # This should never happen, as it should be caught in # _parse_template_line raise DistlibException( 'invalid action %r' % action)
def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.org/distutils/sourcedist.html#commands """ # Parse the line: split it up, make sure the right number of words # is there, and return the relevant words. 'action' is always # defined: it's the first word of the line. Which of the other # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dirpattern). action, patterns, thedir, dirpattern = self._parse_directive(directive) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=True): logger.warning('no files found matching %r', pattern) elif action == 'exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=True) #if not found: # logger.warning('no previously-included files ' # 'found matching %r', pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=False): logger.warning('no files found matching %r ' 'anywhere in distribution', pattern) elif action == 'global-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=False) #if not found: # logger.warning('no previously-included files ' # 'matching %r found anywhere in ' # 'distribution', pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=thedir): logger.warning('no files found matching %r ' 'under directory %r', pattern, thedir) elif action == 'recursive-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, prefix=thedir) #if not found: # logger.warning('no previously-included files ' # 'matching %r found under directory %r', # pattern, thedir) elif action == 'graft': if not self._include_pattern(None, prefix=dirpattern): logger.warning('no directories found matching %r', dirpattern) elif action == 'prune': if not self._exclude_pattern(None, prefix=dirpattern): logger.warning('no previously-included directories found ' 'matching %r', dirpattern) else: # pragma: no cover # This should never happen, as it should be caught in # _parse_template_line raise DistlibException( 'invalid action %r' % action)
[ "Process", "a", "directive", "which", "either", "adds", "some", "files", "from", "allfiles", "to", "files", "or", "removes", "some", "files", "from", "files", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L130-L203
[ "def", "process_directive", "(", "self", ",", "directive", ")", ":", "# Parse the line: split it up, make sure the right number of words", "# is there, and return the relevant words. 'action' is always", "# defined: it's the first word of the line. Which of the other", "# three are defined d...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest._parse_directive
Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns
pipenv/vendor/distlib/manifest.py
def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns """ words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', 'global-include', 'global-exclude', 'recursive-include', 'recursive-exclude', 'graft', 'prune'): # no action given, let's use the default 'include' words.insert(0, 'include') action = words[0] patterns = thedir = dir_pattern = None if action in ('include', 'exclude', 'global-include', 'global-exclude'): if len(words) < 2: raise DistlibException( '%r expects <pattern1> <pattern2> ...' % action) patterns = [convert_path(word) for word in words[1:]] elif action in ('recursive-include', 'recursive-exclude'): if len(words) < 3: raise DistlibException( '%r expects <dir> <pattern1> <pattern2> ...' % action) thedir = convert_path(words[1]) patterns = [convert_path(word) for word in words[2:]] elif action in ('graft', 'prune'): if len(words) != 2: raise DistlibException( '%r expects a single <dir_pattern>' % action) dir_pattern = convert_path(words[1]) else: raise DistlibException('unknown action %r' % action) return action, patterns, thedir, dir_pattern
def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns """ words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', 'global-include', 'global-exclude', 'recursive-include', 'recursive-exclude', 'graft', 'prune'): # no action given, let's use the default 'include' words.insert(0, 'include') action = words[0] patterns = thedir = dir_pattern = None if action in ('include', 'exclude', 'global-include', 'global-exclude'): if len(words) < 2: raise DistlibException( '%r expects <pattern1> <pattern2> ...' % action) patterns = [convert_path(word) for word in words[1:]] elif action in ('recursive-include', 'recursive-exclude'): if len(words) < 3: raise DistlibException( '%r expects <dir> <pattern1> <pattern2> ...' % action) thedir = convert_path(words[1]) patterns = [convert_path(word) for word in words[2:]] elif action in ('graft', 'prune'): if len(words) != 2: raise DistlibException( '%r expects a single <dir_pattern>' % action) dir_pattern = convert_path(words[1]) else: raise DistlibException('unknown action %r' % action) return action, patterns, thedir, dir_pattern
[ "Validate", "a", "directive", ".", ":", "param", "directive", ":", "The", "directive", "to", "validate", ".", ":", "return", ":", "A", "tuple", "of", "action", "patterns", "thedir", "dir_patterns" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L209-L254
[ "def", "_parse_directive", "(", "self", ",", "directive", ")", ":", "words", "=", "directive", ".", "split", "(", ")", "if", "len", "(", "words", ")", "==", "1", "and", "words", "[", "0", "]", "not", "in", "(", "'include'", ",", "'exclude'", ",", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest._include_pattern
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return True if files are found.
pipenv/vendor/distlib/manifest.py
def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return True if files are found. """ # XXX docstring lying about what the special chars are? found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) # delayed loading of allfiles list if self.allfiles is None: self.findall() for name in self.allfiles: if pattern_re.search(name): self.files.add(name) found = True return found
def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return True if files are found. """ # XXX docstring lying about what the special chars are? found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) # delayed loading of allfiles list if self.allfiles is None: self.findall() for name in self.allfiles: if pattern_re.search(name): self.files.add(name) found = True return found
[ "Select", "strings", "(", "presumably", "filenames", ")", "from", "self", ".", "files", "that", "match", "pattern", "a", "Unix", "-", "style", "wildcard", "(", "glob", ")", "pattern", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L256-L295
[ "def", "_include_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "# XXX docstring lying about what the special chars are?", "found", "=", "False", "pattern_re", "=", "self", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest._exclude_pattern
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions
pipenv/vendor/distlib/manifest.py
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions """ found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) for f in list(self.files): if pattern_re.search(f): self.files.remove(f) found = True return found
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions """ found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) for f in list(self.files): if pattern_re.search(f): self.files.remove(f) found = True return found
[ "Remove", "strings", "(", "presumably", "filenames", ")", "from", "files", "that", "match", "pattern", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L297-L315
[ "def", "_exclude_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "found", "=", "False", "pattern_re", "=", "self", ".", "_translate_pattern", "(", "pattern", ",", "an...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest._translate_pattern
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
pipenv/vendor/distlib/manifest.py
def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). """ if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern if _PYTHON_VERSION > (3, 2): # ditch start and end characters start, _, end = self._glob_to_re('_').partition('_') if pattern: pattern_re = self._glob_to_re(pattern) if _PYTHON_VERSION > (3, 2): assert pattern_re.startswith(start) and pattern_re.endswith(end) else: pattern_re = '' base = re.escape(os.path.join(self.base, '')) if prefix is not None: # ditch end of pattern character if _PYTHON_VERSION <= (3, 2): empty_pattern = self._glob_to_re('') prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] else: prefix_re = self._glob_to_re(prefix) assert prefix_re.startswith(start) and prefix_re.endswith(end) prefix_re = prefix_re[len(start): len(prefix_re) - len(end)] sep = os.sep if os.sep == '\\': sep = r'\\' if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + sep.join((prefix_re, '.*' + pattern_re)) else: pattern_re = pattern_re[len(start): len(pattern_re) - len(end)] pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep, pattern_re, end) else: # no prefix -- respect anchor flag if anchor: if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + pattern_re else: pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):]) return re.compile(pattern_re)
def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). """ if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern if _PYTHON_VERSION > (3, 2): # ditch start and end characters start, _, end = self._glob_to_re('_').partition('_') if pattern: pattern_re = self._glob_to_re(pattern) if _PYTHON_VERSION > (3, 2): assert pattern_re.startswith(start) and pattern_re.endswith(end) else: pattern_re = '' base = re.escape(os.path.join(self.base, '')) if prefix is not None: # ditch end of pattern character if _PYTHON_VERSION <= (3, 2): empty_pattern = self._glob_to_re('') prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] else: prefix_re = self._glob_to_re(prefix) assert prefix_re.startswith(start) and prefix_re.endswith(end) prefix_re = prefix_re[len(start): len(prefix_re) - len(end)] sep = os.sep if os.sep == '\\': sep = r'\\' if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + sep.join((prefix_re, '.*' + pattern_re)) else: pattern_re = pattern_re[len(start): len(pattern_re) - len(end)] pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep, pattern_re, end) else: # no prefix -- respect anchor flag if anchor: if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + pattern_re else: pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):]) return re.compile(pattern_re)
[ "Translate", "a", "shell", "-", "like", "wildcard", "pattern", "to", "a", "compiled", "regular", "expression", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L317-L370
[ "def", "_translate_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "if", "is_regex", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "re", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Manifest._glob_to_re
Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific).
pipenv/vendor/distlib/manifest.py
def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmatch.translate(pattern) # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, # and by extension they shouldn't match such "special characters" under # any OS. So change all non-escaped dots in the RE to match any # character except the special characters (currently: just os.sep). sep = os.sep if os.sep == '\\': # we're using a regex to manipulate a regex, so we need # to escape the backslash twice sep = r'\\\\' escaped = r'\1[^%s]' % sep pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) return pattern_re
def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmatch.translate(pattern) # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, # and by extension they shouldn't match such "special characters" under # any OS. So change all non-escaped dots in the RE to match any # character except the special characters (currently: just os.sep). sep = os.sep if os.sep == '\\': # we're using a regex to manipulate a regex, so we need # to escape the backslash twice sep = r'\\\\' escaped = r'\1[^%s]' % sep pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) return pattern_re
[ "Translate", "a", "shell", "-", "like", "glob", "pattern", "to", "a", "regular", "expression", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L372-L393
[ "def", "_glob_to_re", "(", "self", ",", "pattern", ")", ":", "pattern_re", "=", "fnmatch", ".", "translate", "(", "pattern", ")", "# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which", "# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,", "#...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde