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
HelpFormatter.write_dl
Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column.
pipenv/vendor/click/formatting.py
def write_dl(self, rows, col_max=30, col_spacing=2): """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError('Expected two columns for definition list') first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): self.write('%*s%s' % (self.current_indent, '', first)) if not second: self.write('\n') continue if term_len(first) <= first_col - col_spacing: self.write(' ' * (first_col - term_len(first))) else: self.write('\n') self.write(' ' * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) lines = iter(wrap_text(second, text_width).splitlines()) if lines: self.write(next(lines) + '\n') for line in lines: self.write('%*s%s\n' % ( first_col + self.current_indent, '', line)) else: self.write('\n')
def write_dl(self, rows, col_max=30, col_spacing=2): """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError('Expected two columns for definition list') first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): self.write('%*s%s' % (self.current_indent, '', first)) if not second: self.write('\n') continue if term_len(first) <= first_col - col_spacing: self.write(' ' * (first_col - term_len(first))) else: self.write('\n') self.write(' ' * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) lines = iter(wrap_text(second, text_width).splitlines()) if lines: self.write(next(lines) + '\n') for line in lines: self.write('%*s%s\n' % ( first_col + self.current_indent, '', line)) else: self.write('\n')
[ "Writes", "a", "definition", "list", "into", "the", "buffer", ".", "This", "is", "how", "options", "and", "commands", "are", "usually", "formatted", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/formatting.py#L173-L208
[ "def", "write_dl", "(", "self", ",", "rows", ",", "col_max", "=", "30", ",", "col_spacing", "=", "2", ")", ":", "rows", "=", "list", "(", "rows", ")", "widths", "=", "measure_table", "(", "rows", ")", "if", "len", "(", "widths", ")", "!=", "2", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HelpFormatter.section
Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading.
pipenv/vendor/click/formatting.py
def section(self, name): """Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading. """ self.write_paragraph() self.write_heading(name) self.indent() try: yield finally: self.dedent()
def section(self, name): """Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading. """ self.write_paragraph() self.write_heading(name) self.indent() try: yield finally: self.dedent()
[ "Helpful", "context", "manager", "that", "writes", "a", "paragraph", "a", "heading", "and", "the", "indents", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/formatting.py#L211-L223
[ "def", "section", "(", "self", ",", "name", ")", ":", "self", ".", "write_paragraph", "(", ")", "self", ".", "write_heading", "(", "name", ")", "self", ".", "indent", "(", ")", "try", ":", "yield", "finally", ":", "self", ".", "dedent", "(", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
invalid_config_error_message
Returns a better error message when invalid configuration option is provided.
pipenv/patched/notpip/_internal/cli/parser.py
def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for {1} option, " "please specify a boolean value like yes/no, " "true/false or 1/0 instead.").format(val, key) return ("{0} is not a valid value for {1} option, " "please specify a numerical value like 1/0 " "instead.").format(val, key)
def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for {1} option, " "please specify a boolean value like yes/no, " "true/false or 1/0 instead.").format(val, key) return ("{0} is not a valid value for {1} option, " "please specify a numerical value like 1/0 " "instead.").format(val, key)
[ "Returns", "a", "better", "error", "message", "when", "invalid", "configuration", "option", "is", "provided", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L251-L261
[ "def", "invalid_config_error_message", "(", "action", ",", "key", ",", "val", ")", ":", "if", "action", "in", "(", "'store_true'", ",", "'store_false'", ")", ":", "return", "(", "\"{0} is not a valid value for {1} option, \"", "\"please specify a boolean value like yes/no...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
PrettyHelpFormatter._format_option_strings
Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator
pipenv/patched/notpip/_internal/cli/parser.py
def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '): """ Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator """ opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, optsep) if option.takes_value(): metavar = option.metavar or option.dest.lower() opts.append(mvarfmt % metavar.lower()) return ''.join(opts)
def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '): """ Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator """ opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, optsep) if option.takes_value(): metavar = option.metavar or option.dest.lower() opts.append(mvarfmt % metavar.lower()) return ''.join(opts)
[ "Return", "a", "comma", "-", "separated", "list", "of", "option", "strings", "and", "metavars", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L32-L53
[ "def", "_format_option_strings", "(", "self", ",", "option", ",", "mvarfmt", "=", "' <%s>'", ",", "optsep", "=", "', '", ")", ":", "opts", "=", "[", "]", "if", "option", ".", "_short_opts", ":", "opts", ".", "append", "(", "option", ".", "_short_opts", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
PrettyHelpFormatter.format_usage
Ensure there is only one newline between usage and the first heading if there is no description.
pipenv/patched/notpip/_internal/cli/parser.py
def format_usage(self, usage): """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ") return msg
def format_usage(self, usage): """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ") return msg
[ "Ensure", "there", "is", "only", "one", "newline", "between", "usage", "and", "the", "first", "heading", "if", "there", "is", "no", "description", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L60-L66
[ "def", "format_usage", "(", "self", ",", "usage", ")", ":", "msg", "=", "'\\nUsage: %s\\n'", "%", "self", ".", "indent_lines", "(", "textwrap", ".", "dedent", "(", "usage", ")", ",", "\" \"", ")", "return", "msg" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CustomOptionParser.insert_option_group
Insert an OptionGroup at a given position.
pipenv/patched/notpip/_internal/cli/parser.py
def insert_option_group(self, idx, *args, **kwargs): """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group
def insert_option_group(self, idx, *args, **kwargs): """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group
[ "Insert", "an", "OptionGroup", "at", "a", "given", "position", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L113-L120
[ "def", "insert_option_group", "(", "self", ",", "idx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "group", "=", "self", ".", "add_option_group", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "option_groups", ".", "pop", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CustomOptionParser.option_list_all
Get a list of all options, including those in option groups.
pipenv/patched/notpip/_internal/cli/parser.py
def option_list_all(self): """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
def option_list_all(self): """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
[ "Get", "a", "list", "of", "all", "options", "including", "those", "in", "option", "groups", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L123-L129
[ "def", "option_list_all", "(", "self", ")", ":", "res", "=", "self", ".", "option_list", "[", ":", "]", "for", "i", "in", "self", ".", "option_groups", ":", "res", ".", "extend", "(", "i", ".", "option_list", ")", "return", "res" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ConfigOptionParser._update_defaults
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).
pipenv/patched/notpip/_internal/cli/parser.py
def _update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option('--' + key) # Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue if option.action in ('store_true', 'store_false', 'count'): try: val = strtobool(val) except ValueError: error_msg = invalid_config_error_message( option.action, key, val ) self.error(error_msg) elif option.action == 'append': val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == 'callback': late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val) defaults[option.dest] = val for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults
def _update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option('--' + key) # Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue if option.action in ('store_true', 'store_false', 'count'): try: val = strtobool(val) except ValueError: error_msg = invalid_config_error_message( option.action, key, val ) self.error(error_msg) elif option.action == 'append': val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == 'callback': late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val) defaults[option.dest] = val for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults
[ "Updates", "the", "given", "defaults", "with", "values", "from", "the", "config", "files", "and", "the", "environ", ".", "Does", "a", "little", "special", "handling", "for", "certain", "types", "of", "options", "(", "lists", ")", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L176-L223
[ "def", "_update_defaults", "(", "self", ",", "defaults", ")", ":", "# Accumulate complex default state.", "self", ".", "values", "=", "optparse", ".", "Values", "(", "self", ".", "defaults", ")", "late_eval", "=", "set", "(", ")", "# Then set the options with thos...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ConfigOptionParser.get_default_values
Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.
pipenv/patched/notpip/_internal/cli/parser.py
def get_default_values(self): """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) # Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err)) defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults)
def get_default_values(self): """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) # Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err)) defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults)
[ "Overriding", "to", "make", "updating", "the", "defaults", "after", "instantiation", "of", "the", "option", "parser", "possible", "_update_defaults", "()", "does", "the", "dirty", "work", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/parser.py#L225-L244
[ "def", "get_default_values", "(", "self", ")", ":", "if", "not", "self", ".", "process_default_values", ":", "# Old, pre-Optik 1.5 behaviour.", "return", "optparse", ".", "Values", "(", "self", ".", "defaults", ")", "# Load the configuration, or error out in case of an er...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.safe_import
Helper utility for reimporting previously imported modules while inside the env
pipenv/environment.py
def safe_import(self, name): """Helper utility for reimporting previously imported modules while inside the env""" module = None if name not in self._modules: self._modules[name] = importlib.import_module(name) module = self._modules[name] if not module: dist = next(iter( dist for dist in self.base_working_set if dist.project_name == name ), None) if dist: dist.activate() module = importlib.import_module(name) if name in sys.modules: try: six.moves.reload_module(module) six.moves.reload_module(sys.modules[name]) except TypeError: del sys.modules[name] sys.modules[name] = self._modules[name] return module
def safe_import(self, name): """Helper utility for reimporting previously imported modules while inside the env""" module = None if name not in self._modules: self._modules[name] = importlib.import_module(name) module = self._modules[name] if not module: dist = next(iter( dist for dist in self.base_working_set if dist.project_name == name ), None) if dist: dist.activate() module = importlib.import_module(name) if name in sys.modules: try: six.moves.reload_module(module) six.moves.reload_module(sys.modules[name]) except TypeError: del sys.modules[name] sys.modules[name] = self._modules[name] return module
[ "Helper", "utility", "for", "reimporting", "previously", "imported", "modules", "while", "inside", "the", "env" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L51-L71
[ "def", "safe_import", "(", "self", ",", "name", ")", ":", "module", "=", "None", "if", "name", "not", "in", "self", ".", "_modules", ":", "self", ".", "_modules", "[", "name", "]", "=", "importlib", ".", "import_module", "(", "name", ")", "module", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.resolve_dist
Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search for all packages :type working_set: :class:`pkg_resources.WorkingSet` :return: A set of distributions which the package depends on, including the package :rtype: set(:class:`pkg_resources.Distribution`)
pipenv/environment.py
def resolve_dist(cls, dist, working_set): """Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search for all packages :type working_set: :class:`pkg_resources.WorkingSet` :return: A set of distributions which the package depends on, including the package :rtype: set(:class:`pkg_resources.Distribution`) """ deps = set() deps.add(dist) try: reqs = dist.requires() except (AttributeError, OSError, IOError): # The METADATA file can't be found return deps for req in reqs: dist = working_set.find(req) deps |= cls.resolve_dist(dist, working_set) return deps
def resolve_dist(cls, dist, working_set): """Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search for all packages :type working_set: :class:`pkg_resources.WorkingSet` :return: A set of distributions which the package depends on, including the package :rtype: set(:class:`pkg_resources.Distribution`) """ deps = set() deps.add(dist) try: reqs = dist.requires() except (AttributeError, OSError, IOError): # The METADATA file can't be found return deps for req in reqs: dist = working_set.find(req) deps |= cls.resolve_dist(dist, working_set) return deps
[ "Given", "a", "local", "distribution", "and", "a", "working", "set", "returns", "all", "dependencies", "from", "the", "set", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L74-L94
[ "def", "resolve_dist", "(", "cls", ",", "dist", ",", "working_set", ")", ":", "deps", "=", "set", "(", ")", "deps", ".", "add", "(", "dist", ")", "try", ":", "reqs", "=", "dist", ".", "requires", "(", ")", "except", "(", "AttributeError", ",", "OSE...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.base_paths
Returns the context appropriate paths for the environment. :return: A dictionary of environment specific paths to be used for installation operations :rtype: dict .. note:: The implementation of this is borrowed from a combination of pip and virtualenv and is likely to change at some point in the future. >>> from pipenv.core import project >>> from pipenv.environment import Environment >>> env = Environment(prefix=project.virtualenv_location, is_venv=True, sources=project.sources) >>> import pprint >>> pprint.pprint(env.base_paths) {'PATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin::/bin:/usr/bin', 'PYTHONPATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'data': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'include': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'libdir': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platinclude': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'platlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platstdlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7', 'prefix': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'purelib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'scripts': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin', 'stdlib': '/home/hawk/.pyenv/versions/3.7.1/lib/python3.7'}
pipenv/environment.py
def base_paths(self): """ Returns the context appropriate paths for the environment. :return: A dictionary of environment specific paths to be used for installation operations :rtype: dict .. note:: The implementation of this is borrowed from a combination of pip and virtualenv and is likely to change at some point in the future. >>> from pipenv.core import project >>> from pipenv.environment import Environment >>> env = Environment(prefix=project.virtualenv_location, is_venv=True, sources=project.sources) >>> import pprint >>> pprint.pprint(env.base_paths) {'PATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin::/bin:/usr/bin', 'PYTHONPATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'data': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'include': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'libdir': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platinclude': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'platlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platstdlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7', 'prefix': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'purelib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'scripts': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin', 'stdlib': '/home/hawk/.pyenv/versions/3.7.1/lib/python3.7'} """ prefix = make_posix(self.prefix.as_posix()) install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix' paths = get_paths(install_scheme, vars={ 'base': prefix, 'platbase': prefix, }) paths["PATH"] = paths["scripts"] + os.pathsep + os.defpath if "prefix" not in paths: paths["prefix"] = prefix purelib = make_posix(get_python_lib(plat_specific=0, prefix=prefix)) platlib = make_posix(get_python_lib(plat_specific=1, prefix=prefix)) if purelib == platlib: lib_dirs = purelib else: lib_dirs = purelib + os.pathsep + platlib paths["libdir"] = purelib paths["purelib"] = purelib paths["platlib"] = platlib paths['PYTHONPATH'] = os.pathsep.join(["", ".", lib_dirs]) paths["libdirs"] = lib_dirs return paths
def base_paths(self): """ Returns the context appropriate paths for the environment. :return: A dictionary of environment specific paths to be used for installation operations :rtype: dict .. note:: The implementation of this is borrowed from a combination of pip and virtualenv and is likely to change at some point in the future. >>> from pipenv.core import project >>> from pipenv.environment import Environment >>> env = Environment(prefix=project.virtualenv_location, is_venv=True, sources=project.sources) >>> import pprint >>> pprint.pprint(env.base_paths) {'PATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin::/bin:/usr/bin', 'PYTHONPATH': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'data': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'include': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'libdir': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platinclude': '/home/hawk/.pyenv/versions/3.7.1/include/python3.7m', 'platlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'platstdlib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7', 'prefix': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW', 'purelib': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/lib/python3.7/site-packages', 'scripts': '/home/hawk/.virtualenvs/pipenv-MfOPs1lW/bin', 'stdlib': '/home/hawk/.pyenv/versions/3.7.1/lib/python3.7'} """ prefix = make_posix(self.prefix.as_posix()) install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix' paths = get_paths(install_scheme, vars={ 'base': prefix, 'platbase': prefix, }) paths["PATH"] = paths["scripts"] + os.pathsep + os.defpath if "prefix" not in paths: paths["prefix"] = prefix purelib = make_posix(get_python_lib(plat_specific=0, prefix=prefix)) platlib = make_posix(get_python_lib(plat_specific=1, prefix=prefix)) if purelib == platlib: lib_dirs = purelib else: lib_dirs = purelib + os.pathsep + platlib paths["libdir"] = purelib paths["purelib"] = purelib paths["platlib"] = platlib paths['PYTHONPATH'] = os.pathsep.join(["", ".", lib_dirs]) paths["libdirs"] = lib_dirs return paths
[ "Returns", "the", "context", "appropriate", "paths", "for", "the", "environment", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L124-L173
[ "def", "base_paths", "(", "self", ")", ":", "prefix", "=", "make_posix", "(", "self", ".", "prefix", ".", "as_posix", "(", ")", ")", "install_scheme", "=", "'nt'", "if", "(", "os", ".", "name", "==", "'nt'", ")", "else", "'posix_prefix'", "paths", "=",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.python
Path to the environment python
pipenv/environment.py
def python(self): """Path to the environment python""" py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix() if not py: return vistir.compat.Path(sys.executable).as_posix() return py
def python(self): """Path to the environment python""" py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix() if not py: return vistir.compat.Path(sys.executable).as_posix() return py
[ "Path", "to", "the", "environment", "python" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L182-L187
[ "def", "python", "(", "self", ")", ":", "py", "=", "vistir", ".", "compat", ".", "Path", "(", "self", ".", "base_paths", "[", "\"scripts\"", "]", ")", ".", "joinpath", "(", "\"python\"", ")", ".", "absolute", "(", ")", ".", "as_posix", "(", ")", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.sys_path
The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list
pipenv/environment.py
def sys_path(self): """ The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list """ from .vendor.vistir.compat import JSONDecodeError current_executable = vistir.compat.Path(sys.executable).as_posix() if not self.python or self.python == current_executable: return sys.path elif any([sys.prefix == self.prefix, not self.is_venv]): return sys.path cmd_args = [self.python, "-c", "import json, sys; print(json.dumps(sys.path))"] path, _ = vistir.misc.run(cmd_args, return_object=False, nospin=True, block=True, combine_stderr=False, write_to_stdout=False) try: path = json.loads(path.strip()) except JSONDecodeError: path = sys.path return path
def sys_path(self): """ The system path inside the environment :return: The :data:`sys.path` from the environment :rtype: list """ from .vendor.vistir.compat import JSONDecodeError current_executable = vistir.compat.Path(sys.executable).as_posix() if not self.python or self.python == current_executable: return sys.path elif any([sys.prefix == self.prefix, not self.is_venv]): return sys.path cmd_args = [self.python, "-c", "import json, sys; print(json.dumps(sys.path))"] path, _ = vistir.misc.run(cmd_args, return_object=False, nospin=True, block=True, combine_stderr=False, write_to_stdout=False) try: path = json.loads(path.strip()) except JSONDecodeError: path = sys.path return path
[ "The", "system", "path", "inside", "the", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L190-L210
[ "def", "sys_path", "(", "self", ")", ":", "from", ".", "vendor", ".", "vistir", ".", "compat", "import", "JSONDecodeError", "current_executable", "=", "vistir", ".", "compat", ".", "Path", "(", "sys", ".", "executable", ")", ".", "as_posix", "(", ")", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.sys_prefix
The prefix run inside the context of the environment :return: The python prefix inside the environment :rtype: :data:`sys.prefix`
pipenv/environment.py
def sys_prefix(self): """ The prefix run inside the context of the environment :return: The python prefix inside the environment :rtype: :data:`sys.prefix` """ command = [self.python, "-c" "import sys; print(sys.prefix)"] c = vistir.misc.run(command, return_object=True, block=True, nospin=True, write_to_stdout=False) sys_prefix = vistir.compat.Path(vistir.misc.to_text(c.out).strip()).as_posix() return sys_prefix
def sys_prefix(self): """ The prefix run inside the context of the environment :return: The python prefix inside the environment :rtype: :data:`sys.prefix` """ command = [self.python, "-c" "import sys; print(sys.prefix)"] c = vistir.misc.run(command, return_object=True, block=True, nospin=True, write_to_stdout=False) sys_prefix = vistir.compat.Path(vistir.misc.to_text(c.out).strip()).as_posix() return sys_prefix
[ "The", "prefix", "run", "inside", "the", "context", "of", "the", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L213-L224
[ "def", "sys_prefix", "(", "self", ")", ":", "command", "=", "[", "self", ".", "python", ",", "\"-c\"", "\"import sys; print(sys.prefix)\"", "]", "c", "=", "vistir", ".", "misc", ".", "run", "(", "command", ",", "return_object", "=", "True", ",", "block", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.pip_version
Get the pip version in the environment. Useful for knowing which args we can use when installing.
pipenv/environment.py
def pip_version(self): """ Get the pip version in the environment. Useful for knowing which args we can use when installing. """ from .vendor.packaging.version import parse as parse_version pip = next(iter( pkg for pkg in self.get_installed_packages() if pkg.key == "pip" ), None) if pip is not None: pip_version = parse_version(pip.version) return parse_version("18.0")
def pip_version(self): """ Get the pip version in the environment. Useful for knowing which args we can use when installing. """ from .vendor.packaging.version import parse as parse_version pip = next(iter( pkg for pkg in self.get_installed_packages() if pkg.key == "pip" ), None) if pip is not None: pip_version = parse_version(pip.version) return parse_version("18.0")
[ "Get", "the", "pip", "version", "in", "the", "environment", ".", "Useful", "for", "knowing", "which", "args", "we", "can", "use", "when", "installing", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L251-L262
[ "def", "pip_version", "(", "self", ")", ":", "from", ".", "vendor", ".", "packaging", ".", "version", "import", "parse", "as", "parse_version", "pip", "=", "next", "(", "iter", "(", "pkg", "for", "pkg", "in", "self", ".", "get_installed_packages", "(", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.get_distributions
Retrives the distributions installed on the library path of the environment :return: A set of distributions found on the library path :rtype: iterator
pipenv/environment.py
def get_distributions(self): """ Retrives the distributions installed on the library path of the environment :return: A set of distributions found on the library path :rtype: iterator """ pkg_resources = self.safe_import("pkg_resources") libdirs = self.base_paths["libdirs"].split(os.pathsep) dists = (pkg_resources.find_distributions(libdir) for libdir in libdirs) for dist in itertools.chain.from_iterable(dists): yield dist
def get_distributions(self): """ Retrives the distributions installed on the library path of the environment :return: A set of distributions found on the library path :rtype: iterator """ pkg_resources = self.safe_import("pkg_resources") libdirs = self.base_paths["libdirs"].split(os.pathsep) dists = (pkg_resources.find_distributions(libdir) for libdir in libdirs) for dist in itertools.chain.from_iterable(dists): yield dist
[ "Retrives", "the", "distributions", "installed", "on", "the", "library", "path", "of", "the", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L264-L276
[ "def", "get_distributions", "(", "self", ")", ":", "pkg_resources", "=", "self", ".", "safe_import", "(", "\"pkg_resources\"", ")", "libdirs", "=", "self", ".", "base_paths", "[", "\"libdirs\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", "dists", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.find_egg
Find an egg by name in the given environment
pipenv/environment.py
def find_egg(self, egg_dist): """Find an egg by name in the given environment""" site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE search_locations = [site_packages, user_site] for site_directory in search_locations: egg = os.path.join(site_directory, search_filename) if os.path.isfile(egg): return egg
def find_egg(self, egg_dist): """Find an egg by name in the given environment""" site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE search_locations = [site_packages, user_site] for site_directory in search_locations: egg = os.path.join(site_directory, search_filename) if os.path.isfile(egg): return egg
[ "Find", "an", "egg", "by", "name", "in", "the", "given", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L278-L290
[ "def", "find_egg", "(", "self", ",", "egg_dist", ")", ":", "site_packages", "=", "self", ".", "libdir", "[", "1", "]", "search_filename", "=", "\"{0}.egg-link\"", ".", "format", "(", "egg_dist", ".", "project_name", ")", "try", ":", "user_site", "=", "site...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.dist_is_in_project
Determine whether the supplied distribution is in the environment.
pipenv/environment.py
def dist_is_in_project(self, dist): """Determine whether the supplied distribution is in the environment.""" from .project import _normalized prefixes = [ _normalized(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if _normalized(prefix).startswith(_normalized(self.prefix.as_posix())) ] location = self.locate_dist(dist) if not location: return False location = _normalized(make_posix(location)) return any(location.startswith(prefix) for prefix in prefixes)
def dist_is_in_project(self, dist): """Determine whether the supplied distribution is in the environment.""" from .project import _normalized prefixes = [ _normalized(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if _normalized(prefix).startswith(_normalized(self.prefix.as_posix())) ] location = self.locate_dist(dist) if not location: return False location = _normalized(make_posix(location)) return any(location.startswith(prefix) for prefix in prefixes)
[ "Determine", "whether", "the", "supplied", "distribution", "is", "in", "the", "environment", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L300-L311
[ "def", "dist_is_in_project", "(", "self", ",", "dist", ")", ":", "from", ".", "project", "import", "_normalized", "prefixes", "=", "[", "_normalized", "(", "prefix", ")", "for", "prefix", "in", "self", ".", "base_paths", "[", "\"libdirs\"", "]", ".", "spli...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.is_installed
Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool
pipenv/environment.py
def is_installed(self, pkgname): """Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool """ return any(d for d in self.get_distributions() if d.project_name == pkgname)
def is_installed(self, pkgname): """Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool """ return any(d for d in self.get_distributions() if d.project_name == pkgname)
[ "Given", "a", "package", "name", "returns", "whether", "it", "is", "installed", "in", "the", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L481-L489
[ "def", "is_installed", "(", "self", ",", "pkgname", ")", ":", "return", "any", "(", "d", "for", "d", "in", "self", ".", "get_distributions", "(", ")", "if", "d", ".", "project_name", "==", "pkgname", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.run_py
Run a python command in the enviornment context. :param cmd: A command to run in the environment - runs with `python -c` :type cmd: str or list :param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir` :return: A finished command object :rtype: :class:`~subprocess.Popen`
pipenv/environment.py
def run_py(self, cmd, cwd=os.curdir): """Run a python command in the enviornment context. :param cmd: A command to run in the environment - runs with `python -c` :type cmd: str or list :param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir` :return: A finished command object :rtype: :class:`~subprocess.Popen` """ c = None if isinstance(cmd, six.string_types): script = vistir.cmdparse.Script.parse("{0} -c {1}".format(self.python, cmd)) else: script = vistir.cmdparse.Script.parse([self.python, "-c"] + list(cmd)) with self.activated(): c = vistir.misc.run(script._parts, return_object=True, nospin=True, cwd=cwd, write_to_stdout=False) return c
def run_py(self, cmd, cwd=os.curdir): """Run a python command in the enviornment context. :param cmd: A command to run in the environment - runs with `python -c` :type cmd: str or list :param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir` :return: A finished command object :rtype: :class:`~subprocess.Popen` """ c = None if isinstance(cmd, six.string_types): script = vistir.cmdparse.Script.parse("{0} -c {1}".format(self.python, cmd)) else: script = vistir.cmdparse.Script.parse([self.python, "-c"] + list(cmd)) with self.activated(): c = vistir.misc.run(script._parts, return_object=True, nospin=True, cwd=cwd, write_to_stdout=False) return c
[ "Run", "a", "python", "command", "in", "the", "enviornment", "context", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L507-L524
[ "def", "run_py", "(", "self", ",", "cmd", ",", "cwd", "=", "os", ".", "curdir", ")", ":", "c", "=", "None", "if", "isinstance", "(", "cmd", ",", "six", ".", "string_types", ")", ":", "script", "=", "vistir", ".", "cmdparse", ".", "Script", ".", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.run_activate_this
Runs the environment's inline activation script
pipenv/environment.py
def run_activate_this(self): """Runs the environment's inline activation script""" if self.is_venv: activate_this = os.path.join(self.scripts_dir, "activate_this.py") if not os.path.isfile(activate_this): raise OSError("No such file: {0!s}".format(activate_this)) with open(activate_this, "r") as f: code = compile(f.read(), activate_this, "exec") exec(code, dict(__file__=activate_this))
def run_activate_this(self): """Runs the environment's inline activation script""" if self.is_venv: activate_this = os.path.join(self.scripts_dir, "activate_this.py") if not os.path.isfile(activate_this): raise OSError("No such file: {0!s}".format(activate_this)) with open(activate_this, "r") as f: code = compile(f.read(), activate_this, "exec") exec(code, dict(__file__=activate_this))
[ "Runs", "the", "environment", "s", "inline", "activation", "script" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L526-L534
[ "def", "run_activate_this", "(", "self", ")", ":", "if", "self", ".", "is_venv", ":", "activate_this", "=", "os", ".", "path", ".", "join", "(", "self", ".", "scripts_dir", ",", "\"activate_this.py\"", ")", "if", "not", "os", ".", "path", ".", "isfile", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.activated
Helper context manager to activate the environment. This context manager will set the following variables for the duration of its activation: * sys.prefix * sys.path * os.environ["VIRTUAL_ENV"] * os.environ["PATH"] In addition, it will make any distributions passed into `extra_dists` available on `sys.path` while inside the context manager, as well as making `passa` itself available. The environment's `prefix` as well as `scripts_dir` properties are both prepended to `os.environ["PATH"]` to ensure that calls to `~Environment.run()` use the environment's path preferentially.
pipenv/environment.py
def activated(self, include_extras=True, extra_dists=None): """Helper context manager to activate the environment. This context manager will set the following variables for the duration of its activation: * sys.prefix * sys.path * os.environ["VIRTUAL_ENV"] * os.environ["PATH"] In addition, it will make any distributions passed into `extra_dists` available on `sys.path` while inside the context manager, as well as making `passa` itself available. The environment's `prefix` as well as `scripts_dir` properties are both prepended to `os.environ["PATH"]` to ensure that calls to `~Environment.run()` use the environment's path preferentially. """ if not extra_dists: extra_dists = [] original_path = sys.path original_prefix = sys.prefix parent_path = vistir.compat.Path(__file__).absolute().parent vendor_dir = parent_path.joinpath("vendor").as_posix() patched_dir = parent_path.joinpath("patched").as_posix() parent_path = parent_path.as_posix() self.add_dist("pip") prefix = self.prefix.as_posix() with vistir.contextmanagers.temp_environ(), vistir.contextmanagers.temp_path(): os.environ["PATH"] = os.pathsep.join([ vistir.compat.fs_str(self.scripts_dir), vistir.compat.fs_str(self.prefix.as_posix()), os.environ.get("PATH", "") ]) os.environ["PYTHONIOENCODING"] = vistir.compat.fs_str("utf-8") os.environ["PYTHONDONTWRITEBYTECODE"] = vistir.compat.fs_str("1") from .environments import PIPENV_USE_SYSTEM if self.is_venv: os.environ["PYTHONPATH"] = self.base_paths["PYTHONPATH"] os.environ["VIRTUAL_ENV"] = vistir.compat.fs_str(prefix) else: if not PIPENV_USE_SYSTEM and not os.environ.get("VIRTUAL_ENV"): os.environ["PYTHONPATH"] = self.base_paths["PYTHONPATH"] os.environ.pop("PYTHONHOME", None) sys.path = self.sys_path sys.prefix = self.sys_prefix site.addsitedir(self.base_paths["purelib"]) pip = self.safe_import("pip") pip_vendor = self.safe_import("pip._vendor") pep517_dir = os.path.join(os.path.dirname(pip_vendor.__file__), "pep517") site.addsitedir(pep517_dir) os.environ["PYTHONPATH"] = os.pathsep.join([ os.environ.get("PYTHONPATH", self.base_paths["PYTHONPATH"]), pep517_dir ]) if include_extras: site.addsitedir(parent_path) sys.path.extend([parent_path, patched_dir, vendor_dir]) extra_dists = list(self.extra_dists) + extra_dists for extra_dist in extra_dists: if extra_dist not in self.get_working_set(): extra_dist.activate(self.sys_path) try: yield finally: sys.path = original_path sys.prefix = original_prefix six.moves.reload_module(pkg_resources)
def activated(self, include_extras=True, extra_dists=None): """Helper context manager to activate the environment. This context manager will set the following variables for the duration of its activation: * sys.prefix * sys.path * os.environ["VIRTUAL_ENV"] * os.environ["PATH"] In addition, it will make any distributions passed into `extra_dists` available on `sys.path` while inside the context manager, as well as making `passa` itself available. The environment's `prefix` as well as `scripts_dir` properties are both prepended to `os.environ["PATH"]` to ensure that calls to `~Environment.run()` use the environment's path preferentially. """ if not extra_dists: extra_dists = [] original_path = sys.path original_prefix = sys.prefix parent_path = vistir.compat.Path(__file__).absolute().parent vendor_dir = parent_path.joinpath("vendor").as_posix() patched_dir = parent_path.joinpath("patched").as_posix() parent_path = parent_path.as_posix() self.add_dist("pip") prefix = self.prefix.as_posix() with vistir.contextmanagers.temp_environ(), vistir.contextmanagers.temp_path(): os.environ["PATH"] = os.pathsep.join([ vistir.compat.fs_str(self.scripts_dir), vistir.compat.fs_str(self.prefix.as_posix()), os.environ.get("PATH", "") ]) os.environ["PYTHONIOENCODING"] = vistir.compat.fs_str("utf-8") os.environ["PYTHONDONTWRITEBYTECODE"] = vistir.compat.fs_str("1") from .environments import PIPENV_USE_SYSTEM if self.is_venv: os.environ["PYTHONPATH"] = self.base_paths["PYTHONPATH"] os.environ["VIRTUAL_ENV"] = vistir.compat.fs_str(prefix) else: if not PIPENV_USE_SYSTEM and not os.environ.get("VIRTUAL_ENV"): os.environ["PYTHONPATH"] = self.base_paths["PYTHONPATH"] os.environ.pop("PYTHONHOME", None) sys.path = self.sys_path sys.prefix = self.sys_prefix site.addsitedir(self.base_paths["purelib"]) pip = self.safe_import("pip") pip_vendor = self.safe_import("pip._vendor") pep517_dir = os.path.join(os.path.dirname(pip_vendor.__file__), "pep517") site.addsitedir(pep517_dir) os.environ["PYTHONPATH"] = os.pathsep.join([ os.environ.get("PYTHONPATH", self.base_paths["PYTHONPATH"]), pep517_dir ]) if include_extras: site.addsitedir(parent_path) sys.path.extend([parent_path, patched_dir, vendor_dir]) extra_dists = list(self.extra_dists) + extra_dists for extra_dist in extra_dists: if extra_dist not in self.get_working_set(): extra_dist.activate(self.sys_path) try: yield finally: sys.path = original_path sys.prefix = original_prefix six.moves.reload_module(pkg_resources)
[ "Helper", "context", "manager", "to", "activate", "the", "environment", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L537-L605
[ "def", "activated", "(", "self", ",", "include_extras", "=", "True", ",", "extra_dists", "=", "None", ")", ":", "if", "not", "extra_dists", ":", "extra_dists", "=", "[", "]", "original_path", "=", "sys", ".", "path", "original_prefix", "=", "sys", ".", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Environment.uninstall
A context manager which allows uninstallation of packages from the environment :param str pkgname: The name of a package to uninstall >>> env = Environment("/path/to/env/root") >>> with env.uninstall("pytz", auto_confirm=True, verbose=False) as uninstaller: cleaned = uninstaller.paths >>> if cleaned: print("uninstalled packages: %s" % cleaned)
pipenv/environment.py
def uninstall(self, pkgname, *args, **kwargs): """A context manager which allows uninstallation of packages from the environment :param str pkgname: The name of a package to uninstall >>> env = Environment("/path/to/env/root") >>> with env.uninstall("pytz", auto_confirm=True, verbose=False) as uninstaller: cleaned = uninstaller.paths >>> if cleaned: print("uninstalled packages: %s" % cleaned) """ auto_confirm = kwargs.pop("auto_confirm", True) verbose = kwargs.pop("verbose", False) with self.activated(): monkey_patch = next(iter( dist for dist in self.base_working_set if dist.project_name == "recursive-monkey-patch" ), None) if monkey_patch: monkey_patch.activate() pip_shims = self.safe_import("pip_shims") pathset_base = pip_shims.UninstallPathSet pathset_base._permitted = PatchedUninstaller._permitted dist = next( iter(filter(lambda d: d.project_name == pkgname, self.get_working_set())), None ) pathset = pathset_base.from_dist(dist) if pathset is not None: pathset.remove(auto_confirm=auto_confirm, verbose=verbose) try: yield pathset except Exception as e: if pathset is not None: pathset.rollback() else: if pathset is not None: pathset.commit() if pathset is None: return
def uninstall(self, pkgname, *args, **kwargs): """A context manager which allows uninstallation of packages from the environment :param str pkgname: The name of a package to uninstall >>> env = Environment("/path/to/env/root") >>> with env.uninstall("pytz", auto_confirm=True, verbose=False) as uninstaller: cleaned = uninstaller.paths >>> if cleaned: print("uninstalled packages: %s" % cleaned) """ auto_confirm = kwargs.pop("auto_confirm", True) verbose = kwargs.pop("verbose", False) with self.activated(): monkey_patch = next(iter( dist for dist in self.base_working_set if dist.project_name == "recursive-monkey-patch" ), None) if monkey_patch: monkey_patch.activate() pip_shims = self.safe_import("pip_shims") pathset_base = pip_shims.UninstallPathSet pathset_base._permitted = PatchedUninstaller._permitted dist = next( iter(filter(lambda d: d.project_name == pkgname, self.get_working_set())), None ) pathset = pathset_base.from_dist(dist) if pathset is not None: pathset.remove(auto_confirm=auto_confirm, verbose=verbose) try: yield pathset except Exception as e: if pathset is not None: pathset.rollback() else: if pathset is not None: pathset.commit() if pathset is None: return
[ "A", "context", "manager", "which", "allows", "uninstallation", "of", "packages", "from", "the", "environment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L673-L713
[ "def", "uninstall", "(", "self", ",", "pkgname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "auto_confirm", "=", "kwargs", ".", "pop", "(", "\"auto_confirm\"", ",", "True", ")", "verbose", "=", "kwargs", ".", "pop", "(", "\"verbose\"", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
stn
Convert a string to a null-terminated bytes object.
pipenv/vendor/distlib/_backport/tarfile.py
def stn(s, length, encoding, errors): """Convert a string to a null-terminated bytes object. """ s = s.encode(encoding, errors) return s[:length] + (length - len(s)) * NUL
def stn(s, length, encoding, errors): """Convert a string to a null-terminated bytes object. """ s = s.encode(encoding, errors) return s[:length] + (length - len(s)) * NUL
[ "Convert", "a", "string", "to", "a", "null", "-", "terminated", "bytes", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L185-L189
[ "def", "stn", "(", "s", ",", "length", ",", "encoding", ",", "errors", ")", ":", "s", "=", "s", ".", "encode", "(", "encoding", ",", "errors", ")", "return", "s", "[", ":", "length", "]", "+", "(", "length", "-", "len", "(", "s", ")", ")", "*...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
nts
Convert a null-terminated bytes object to a string.
pipenv/vendor/distlib/_backport/tarfile.py
def nts(s, encoding, errors): """Convert a null-terminated bytes object to a string. """ p = s.find(b"\0") if p != -1: s = s[:p] return s.decode(encoding, errors)
def nts(s, encoding, errors): """Convert a null-terminated bytes object to a string. """ p = s.find(b"\0") if p != -1: s = s[:p] return s.decode(encoding, errors)
[ "Convert", "a", "null", "-", "terminated", "bytes", "object", "to", "a", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L191-L197
[ "def", "nts", "(", "s", ",", "encoding", ",", "errors", ")", ":", "p", "=", "s", ".", "find", "(", "b\"\\0\"", ")", "if", "p", "!=", "-", "1", ":", "s", "=", "s", "[", ":", "p", "]", "return", "s", ".", "decode", "(", "encoding", ",", "erro...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
nti
Convert a number field to a python number.
pipenv/vendor/distlib/_backport/tarfile.py
def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0o200): try: n = int(nts(s, "ascii", "strict") or "0", 8) except ValueError: raise InvalidHeaderError("invalid header") else: n = 0 for i in range(len(s) - 1): n <<= 8 n += ord(s[i + 1]) return n
def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0o200): try: n = int(nts(s, "ascii", "strict") or "0", 8) except ValueError: raise InvalidHeaderError("invalid header") else: n = 0 for i in range(len(s) - 1): n <<= 8 n += ord(s[i + 1]) return n
[ "Convert", "a", "number", "field", "to", "a", "python", "number", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L199-L214
[ "def", "nti", "(", "s", ")", ":", "# There are two possible encodings for a number field, see", "# itn() below.", "if", "s", "[", "0", "]", "!=", "chr", "(", "0o200", ")", ":", "try", ":", "n", "=", "int", "(", "nts", "(", "s", ",", "\"ascii\"", ",", "\"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
itn
Convert a python number to a number field.
pipenv/vendor/distlib/_backport/tarfile.py
def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0o200 byte indicates this particular # encoding, the following digits-1 bytes are a big-endian # representation. This allows values up to (256**(digits-1))-1. if 0 <= n < 8 ** (digits - 1): s = ("%0*o" % (digits - 1, n)).encode("ascii") + NUL else: if format != GNU_FORMAT or n >= 256 ** (digits - 1): raise ValueError("overflow in number field") if n < 0: # XXX We mimic GNU tar's behaviour with negative numbers, # this could raise OverflowError. n = struct.unpack("L", struct.pack("l", n))[0] s = bytearray() for i in range(digits - 1): s.insert(0, n & 0o377) n >>= 8 s.insert(0, 0o200) return s
def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0o200 byte indicates this particular # encoding, the following digits-1 bytes are a big-endian # representation. This allows values up to (256**(digits-1))-1. if 0 <= n < 8 ** (digits - 1): s = ("%0*o" % (digits - 1, n)).encode("ascii") + NUL else: if format != GNU_FORMAT or n >= 256 ** (digits - 1): raise ValueError("overflow in number field") if n < 0: # XXX We mimic GNU tar's behaviour with negative numbers, # this could raise OverflowError. n = struct.unpack("L", struct.pack("l", n))[0] s = bytearray() for i in range(digits - 1): s.insert(0, n & 0o377) n >>= 8 s.insert(0, 0o200) return s
[ "Convert", "a", "python", "number", "to", "a", "number", "field", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L216-L241
[ "def", "itn", "(", "n", ",", "digits", "=", "8", ",", "format", "=", "DEFAULT_FORMAT", ")", ":", "# POSIX 1003.1-1988 requires numbers to be encoded as a string of", "# octal digits followed by a null-byte, this allows values up to", "# (8**(digits-1))-1. GNU tar allows storing numbe...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
calc_chksums
Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed.
pipenv/vendor/distlib/_backport/tarfile.py
def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512])) return unsigned_chksum, signed_chksum
def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512])) return unsigned_chksum, signed_chksum
[ "Calculate", "the", "checksum", "for", "a", "member", "s", "header", "by", "summing", "up", "all", "characters", "except", "for", "the", "chksum", "field", "which", "is", "treated", "as", "if", "it", "was", "filled", "with", "spaces", ".", "According", "to...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L243-L254
[ "def", "calc_chksums", "(", "buf", ")", ":", "unsigned_chksum", "=", "256", "+", "sum", "(", "struct", ".", "unpack", "(", "\"148B\"", ",", "buf", "[", ":", "148", "]", ")", "+", "struct", ".", "unpack", "(", "\"356B\"", ",", "buf", "[", "156", ":"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
copyfileobj
Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content.
pipenv/vendor/distlib/_backport/tarfile.py
def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: while True: buf = src.read(16*1024) if not buf: break dst.write(buf) return BUFSIZE = 16 * 1024 blocks, remainder = divmod(length, BUFSIZE) for b in range(blocks): buf = src.read(BUFSIZE) if len(buf) < BUFSIZE: raise IOError("end of file reached") dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise IOError("end of file reached") dst.write(buf) return
def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: while True: buf = src.read(16*1024) if not buf: break dst.write(buf) return BUFSIZE = 16 * 1024 blocks, remainder = divmod(length, BUFSIZE) for b in range(blocks): buf = src.read(BUFSIZE) if len(buf) < BUFSIZE: raise IOError("end of file reached") dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise IOError("end of file reached") dst.write(buf) return
[ "Copy", "length", "bytes", "from", "fileobj", "src", "to", "fileobj", "dst", ".", "If", "length", "is", "None", "copy", "the", "entire", "content", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L256-L283
[ "def", "copyfileobj", "(", "src", ",", "dst", ",", "length", "=", "None", ")", ":", "if", "length", "==", "0", ":", "return", "if", "length", "is", "None", ":", "while", "True", ":", "buf", "=", "src", ".", "read", "(", "16", "*", "1024", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
filemode
Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list()
pipenv/vendor/distlib/_backport/tarfile.py
def filemode(mode): """Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() """ perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm)
def filemode(mode): """Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() """ perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm)
[ "Convert", "a", "file", "s", "mode", "to", "a", "string", "of", "the", "form", "-", "rwxrwxrwx", ".", "Used", "by", "TarFile", ".", "list", "()" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L312-L325
[ "def", "filemode", "(", "mode", ")", ":", "perm", "=", "[", "]", "for", "table", "in", "filemode_table", ":", "for", "bit", ",", "char", "in", "table", ":", "if", "mode", "&", "bit", "==", "bit", ":", "perm", ".", "append", "(", "char", ")", "bre...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
is_tarfile
Return True if name points to a tar archive that we are able to handle, else return False.
pipenv/vendor/distlib/_backport/tarfile.py
def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. """ try: t = open(name) t.close() return True except TarError: return False
def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. """ try: t = open(name) t.close() return True except TarError: return False
[ "Return", "True", "if", "name", "points", "to", "a", "tar", "archive", "that", "we", "are", "able", "to", "handle", "else", "return", "False", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2595-L2604
[ "def", "is_tarfile", "(", "name", ")", ":", "try", ":", "t", "=", "open", "(", "name", ")", "t", ".", "close", "(", ")", "return", "True", "except", "TarError", ":", "return", "False" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream._init_write_gz
Initialize for writing with gzip compression.
pipenv/vendor/distlib/_backport/tarfile.py
def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) timestamp = struct.pack("<L", int(time.time())) self.__write(b"\037\213\010\010" + timestamp + b"\002\377") if self.name.endswith(".gz"): self.name = self.name[:-3] # RFC1952 says we must use ISO-8859-1 for the FNAME field. self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) timestamp = struct.pack("<L", int(time.time())) self.__write(b"\037\213\010\010" + timestamp + b"\002\377") if self.name.endswith(".gz"): self.name = self.name[:-3] # RFC1952 says we must use ISO-8859-1 for the FNAME field. self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
[ "Initialize", "for", "writing", "with", "gzip", "compression", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L455-L467
[ "def", "_init_write_gz", "(", "self", ")", ":", "self", ".", "cmp", "=", "self", ".", "zlib", ".", "compressobj", "(", "9", ",", "self", ".", "zlib", ".", "DEFLATED", ",", "-", "self", ".", "zlib", ".", "MAX_WBITS", ",", "self", ".", "zlib", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.write
Write string s to the stream.
pipenv/vendor/distlib/_backport/tarfile.py
def write(self, s): """Write string s to the stream. """ if self.comptype == "gz": self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != "tar": s = self.cmp.compress(s) self.__write(s)
def write(self, s): """Write string s to the stream. """ if self.comptype == "gz": self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != "tar": s = self.cmp.compress(s) self.__write(s)
[ "Write", "string", "s", "to", "the", "stream", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L469-L477
[ "def", "write", "(", "self", ",", "s", ")", ":", "if", "self", ".", "comptype", "==", "\"gz\"", ":", "self", ".", "crc", "=", "self", ".", "zlib", ".", "crc32", "(", "s", ",", "self", ".", "crc", ")", "self", ".", "pos", "+=", "len", "(", "s"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.__write
Write string s to the stream if a whole new block is ready to be written.
pipenv/vendor/distlib/_backport/tarfile.py
def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.buf[:self.bufsize]) self.buf = self.buf[self.bufsize:]
def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.buf[:self.bufsize]) self.buf = self.buf[self.bufsize:]
[ "Write", "string", "s", "to", "the", "stream", "if", "a", "whole", "new", "block", "is", "ready", "to", "be", "written", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L479-L486
[ "def", "__write", "(", "self", ",", "s", ")", ":", "self", ".", "buf", "+=", "s", "while", "len", "(", "self", ".", "buf", ")", ">", "self", ".", "bufsize", ":", "self", ".", "fileobj", ".", "write", "(", "self", ".", "buf", "[", ":", "self", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.close
Close the _Stream object. No operation should be done on it afterwards.
pipenv/vendor/distlib/_backport/tarfile.py
def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return if self.mode == "w" and self.comptype != "tar": self.buf += self.cmp.flush() if self.mode == "w" and self.buf: self.fileobj.write(self.buf) self.buf = b"" if self.comptype == "gz": # The native zlib crc is an unsigned 32-bit integer, but # the Python wrapper implicitly casts that to a signed C # long. So, on a 32-bit box self.crc may "look negative", # while the same crc on a 64-bit box may "look positive". # To avoid irksome warnings from the `struct` module, force # it to look positive on all boxes. self.fileobj.write(struct.pack("<L", self.crc & 0xffffffff)) self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF)) if not self._extfileobj: self.fileobj.close() self.closed = True
def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return if self.mode == "w" and self.comptype != "tar": self.buf += self.cmp.flush() if self.mode == "w" and self.buf: self.fileobj.write(self.buf) self.buf = b"" if self.comptype == "gz": # The native zlib crc is an unsigned 32-bit integer, but # the Python wrapper implicitly casts that to a signed C # long. So, on a 32-bit box self.crc may "look negative", # while the same crc on a 64-bit box may "look positive". # To avoid irksome warnings from the `struct` module, force # it to look positive on all boxes. self.fileobj.write(struct.pack("<L", self.crc & 0xffffffff)) self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF)) if not self._extfileobj: self.fileobj.close() self.closed = True
[ "Close", "the", "_Stream", "object", ".", "No", "operation", "should", "be", "done", "on", "it", "afterwards", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L488-L514
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "return", "if", "self", ".", "mode", "==", "\"w\"", "and", "self", ".", "comptype", "!=", "\"tar\"", ":", "self", ".", "buf", "+=", "self", ".", "cmp", ".", "flush", "(", ")...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream._init_read_gz
Initialize for reading a gzip compressed fileobj.
pipenv/vendor/distlib/_backport/tarfile.py
def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = b"" # taken from gzip.GzipFile with some alterations if self.__read(2) != b"\037\213": raise ReadError("not a gzip file") if self.__read(1) != b"\010": raise CompressionError("unsupported compression method") flag = ord(self.__read(1)) self.__read(6) if flag & 4: xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) self.read(xlen) if flag & 8: while True: s = self.__read(1) if not s or s == NUL: break if flag & 16: while True: s = self.__read(1) if not s or s == NUL: break if flag & 2: self.__read(2)
def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = b"" # taken from gzip.GzipFile with some alterations if self.__read(2) != b"\037\213": raise ReadError("not a gzip file") if self.__read(1) != b"\010": raise CompressionError("unsupported compression method") flag = ord(self.__read(1)) self.__read(6) if flag & 4: xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) self.read(xlen) if flag & 8: while True: s = self.__read(1) if not s or s == NUL: break if flag & 16: while True: s = self.__read(1) if not s or s == NUL: break if flag & 2: self.__read(2)
[ "Initialize", "for", "reading", "a", "gzip", "compressed", "fileobj", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L516-L545
[ "def", "_init_read_gz", "(", "self", ")", ":", "self", ".", "cmp", "=", "self", ".", "zlib", ".", "decompressobj", "(", "-", "self", ".", "zlib", ".", "MAX_WBITS", ")", "self", ".", "dbuf", "=", "b\"\"", "# taken from gzip.GzipFile with some alterations", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.seek
Set the stream's file pointer to pos. Negative seeking is forbidden.
pipenv/vendor/distlib/_backport/tarfile.py
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in range(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError("seeking backwards is not allowed") return self.pos
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in range(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError("seeking backwards is not allowed") return self.pos
[ "Set", "the", "stream", "s", "file", "pointer", "to", "pos", ".", "Negative", "seeking", "is", "forbidden", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L552-L563
[ "def", "seek", "(", "self", ",", "pos", "=", "0", ")", ":", "if", "pos", "-", "self", ".", "pos", ">=", "0", ":", "blocks", ",", "remainder", "=", "divmod", "(", "pos", "-", "self", ".", "pos", ",", "self", ".", "bufsize", ")", "for", "i", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.read
Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF.
pipenv/vendor/distlib/_backport/tarfile.py
def read(self, size=None): """Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF. """ if size is None: t = [] while True: buf = self._read(self.bufsize) if not buf: break t.append(buf) buf = "".join(t) else: buf = self._read(size) self.pos += len(buf) return buf
def read(self, size=None): """Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF. """ if size is None: t = [] while True: buf = self._read(self.bufsize) if not buf: break t.append(buf) buf = "".join(t) else: buf = self._read(size) self.pos += len(buf) return buf
[ "Return", "the", "next", "size", "number", "of", "bytes", "from", "the", "stream", ".", "If", "size", "is", "not", "defined", "return", "all", "bytes", "of", "the", "stream", "up", "to", "EOF", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L565-L581
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "t", "=", "[", "]", "while", "True", ":", "buf", "=", "self", ".", "_read", "(", "self", ".", "bufsize", ")", "if", "not", "buf", ":", "break", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream._read
Return size bytes from the stream.
pipenv/vendor/distlib/_backport/tarfile.py
def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) while c < size: buf = self.__read(self.bufsize) if not buf: break try: buf = self.cmp.decompress(buf) except IOError: raise ReadError("invalid compressed data") self.dbuf += buf c += len(buf) buf = self.dbuf[:size] self.dbuf = self.dbuf[size:] return buf
def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) while c < size: buf = self.__read(self.bufsize) if not buf: break try: buf = self.cmp.decompress(buf) except IOError: raise ReadError("invalid compressed data") self.dbuf += buf c += len(buf) buf = self.dbuf[:size] self.dbuf = self.dbuf[size:] return buf
[ "Return", "size", "bytes", "from", "the", "stream", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L583-L602
[ "def", "_read", "(", "self", ",", "size", ")", ":", "if", "self", ".", "comptype", "==", "\"tar\"", ":", "return", "self", ".", "__read", "(", "size", ")", "c", "=", "len", "(", "self", ".", "dbuf", ")", "while", "c", "<", "size", ":", "buf", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_Stream.__read
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
pipenv/vendor/distlib/_backport/tarfile.py
def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break self.buf += buf c += len(buf) buf = self.buf[:size] self.buf = self.buf[size:] return buf
def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break self.buf += buf c += len(buf) buf = self.buf[:size] self.buf = self.buf[size:] return buf
[ "Return", "size", "bytes", "from", "stream", ".", "If", "internal", "buffer", "is", "empty", "read", "another", "block", "from", "the", "stream", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L604-L617
[ "def", "__read", "(", "self", ",", "size", ")", ":", "c", "=", "len", "(", "self", ".", "buf", ")", "while", "c", "<", "size", ":", "buf", "=", "self", ".", "fileobj", ".", "read", "(", "self", ".", "bufsize", ")", "if", "not", "buf", ":", "b...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_FileInFile.read
Read data from the file.
pipenv/vendor/distlib/_backport/tarfile.py
def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: data, start, stop, offset = self.map[self.map_index] if start <= self.position < stop: break else: self.map_index += 1 if self.map_index == len(self.map): self.map_index = 0 length = min(size, stop - self.position) if data: self.fileobj.seek(offset + (self.position - start)) buf += self.fileobj.read(length) else: buf += NUL * length size -= length self.position += length return buf
def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: data, start, stop, offset = self.map[self.map_index] if start <= self.position < stop: break else: self.map_index += 1 if self.map_index == len(self.map): self.map_index = 0 length = min(size, stop - self.position) if data: self.fileobj.seek(offset + (self.position - start)) buf += self.fileobj.read(length) else: buf += NUL * length size -= length self.position += length return buf
[ "Read", "data", "from", "the", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L752-L778
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "size", "-", "self", ".", "position", "else", ":", "size", "=", "min", "(", "size", ",", "self", ".", "size", "-", "self"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ExFileObject.read
Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached.
pipenv/vendor/distlib/_backport/tarfile.py
def read(self, size=None): """Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. """ if self.closed: raise ValueError("I/O operation on closed file") buf = b"" if self.buffer: if size is None: buf = self.buffer self.buffer = b"" else: buf = self.buffer[:size] self.buffer = self.buffer[size:] if size is None: buf += self.fileobj.read() else: buf += self.fileobj.read(size - len(buf)) self.position += len(buf) return buf
def read(self, size=None): """Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. """ if self.closed: raise ValueError("I/O operation on closed file") buf = b"" if self.buffer: if size is None: buf = self.buffer self.buffer = b"" else: buf = self.buffer[:size] self.buffer = self.buffer[size:] if size is None: buf += self.fileobj.read() else: buf += self.fileobj.read(size - len(buf)) self.position += len(buf) return buf
[ "Read", "at", "most", "size", "bytes", "from", "the", "file", ".", "If", "size", "is", "not", "present", "or", "None", "read", "all", "data", "until", "EOF", "is", "reached", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L810-L832
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "buf", "=", "b\"\"", "if", "self", ".", "buffer", ":", "if", "size", "is", "None", ":...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ExFileObject.readline
Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line.
pipenv/vendor/distlib/_backport/tarfile.py
def readline(self, size=-1): """Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line. """ if self.closed: raise ValueError("I/O operation on closed file") pos = self.buffer.find(b"\n") + 1 if pos == 0: # no newline found. while True: buf = self.fileobj.read(self.blocksize) self.buffer += buf if not buf or b"\n" in buf: pos = self.buffer.find(b"\n") + 1 if pos == 0: # no newline found. pos = len(self.buffer) break if size != -1: pos = min(size, pos) buf = self.buffer[:pos] self.buffer = self.buffer[pos:] self.position += len(buf) return buf
def readline(self, size=-1): """Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line. """ if self.closed: raise ValueError("I/O operation on closed file") pos = self.buffer.find(b"\n") + 1 if pos == 0: # no newline found. while True: buf = self.fileobj.read(self.blocksize) self.buffer += buf if not buf or b"\n" in buf: pos = self.buffer.find(b"\n") + 1 if pos == 0: # no newline found. pos = len(self.buffer) break if size != -1: pos = min(size, pos) buf = self.buffer[:pos] self.buffer = self.buffer[pos:] self.position += len(buf) return buf
[ "Read", "one", "entire", "line", "from", "the", "file", ".", "If", "size", "is", "present", "and", "non", "-", "negative", "return", "a", "string", "with", "at", "most", "that", "size", "which", "may", "be", "an", "incomplete", "line", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L837-L864
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "pos", "=", "self", ".", "buffer", ".", "find", "(", "b\"\\n\"", ")", "+", "1",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ExFileObject.seek
Seek to a position in the file.
pipenv/vendor/distlib/_backport/tarfile.py
def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ if self.closed: raise ValueError("I/O operation on closed file") if whence == os.SEEK_SET: self.position = min(max(pos, 0), self.size) elif whence == os.SEEK_CUR: if pos < 0: self.position = max(self.position + pos, 0) else: self.position = min(self.position + pos, self.size) elif whence == os.SEEK_END: self.position = max(min(self.size + pos, self.size), 0) else: raise ValueError("Invalid argument") self.buffer = b"" self.fileobj.seek(self.position)
def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ if self.closed: raise ValueError("I/O operation on closed file") if whence == os.SEEK_SET: self.position = min(max(pos, 0), self.size) elif whence == os.SEEK_CUR: if pos < 0: self.position = max(self.position + pos, 0) else: self.position = min(self.position + pos, self.size) elif whence == os.SEEK_END: self.position = max(min(self.size + pos, self.size), 0) else: raise ValueError("Invalid argument") self.buffer = b"" self.fileobj.seek(self.position)
[ "Seek", "to", "a", "position", "in", "the", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L884-L903
[ "def", "seek", "(", "self", ",", "pos", ",", "whence", "=", "os", ".", "SEEK_SET", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "if", "whence", "==", "os", ".", "SEEK_SET", ":", "self", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.get_info
Return the TarInfo's attributes as a dictionary.
pipenv/vendor/distlib/_backport/tarfile.py
def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self.mtime, "chksum": self.chksum, "type": self.type, "linkname": self.linkname, "uname": self.uname, "gname": self.gname, "devmajor": self.devmajor, "devminor": self.devminor } if info["type"] == DIRTYPE and not info["name"].endswith("/"): info["name"] += "/" return info
def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self.mtime, "chksum": self.chksum, "type": self.type, "linkname": self.linkname, "uname": self.uname, "gname": self.gname, "devmajor": self.devmajor, "devminor": self.devminor } if info["type"] == DIRTYPE and not info["name"].endswith("/"): info["name"] += "/" return info
[ "Return", "the", "TarInfo", "s", "attributes", "as", "a", "dictionary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L978-L1000
[ "def", "get_info", "(", "self", ")", ":", "info", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"mode\"", ":", "self", ".", "mode", "&", "0o7777", ",", "\"uid\"", ":", "self", ".", "uid", ",", "\"gid\"", ":", "self", ".", "gid", ",", "\"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.tobuf
Return a tar header as a string of 512 byte blocks.
pipenv/vendor/distlib/_backport/tarfile.py
def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() if format == USTAR_FORMAT: return self.create_ustar_header(info, encoding, errors) elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: return self.create_pax_header(info, encoding) else: raise ValueError("invalid format")
def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() if format == USTAR_FORMAT: return self.create_ustar_header(info, encoding, errors) elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: return self.create_pax_header(info, encoding) else: raise ValueError("invalid format")
[ "Return", "a", "tar", "header", "as", "a", "string", "of", "512", "byte", "blocks", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1002-L1014
[ "def", "tobuf", "(", "self", ",", "format", "=", "DEFAULT_FORMAT", ",", "encoding", "=", "ENCODING", ",", "errors", "=", "\"surrogateescape\"", ")", ":", "info", "=", "self", ".", "get_info", "(", ")", "if", "format", "==", "USTAR_FORMAT", ":", "return", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.create_ustar_header
Return the object as a ustar header block.
pipenv/vendor/distlib/_backport/tarfile.py
def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"]) return self._create_header(info, USTAR_FORMAT, encoding, errors)
def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"]) return self._create_header(info, USTAR_FORMAT, encoding, errors)
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1016-L1027
[ "def", "create_ustar_header", "(", "self", ",", "info", ",", "encoding", ",", "errors", ")", ":", "info", "[", "\"magic\"", "]", "=", "POSIX_MAGIC", "if", "len", "(", "info", "[", "\"linkname\"", "]", ")", ">", "LENGTH_LINK", ":", "raise", "ValueError", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.create_gnu_header
Return the object as a GNU header block sequence.
pipenv/vendor/distlib/_backport/tarfile.py
def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) if len(info["name"]) > LENGTH_NAME: buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) if len(info["name"]) > LENGTH_NAME: buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
[ "Return", "the", "object", "as", "a", "GNU", "header", "block", "sequence", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1029-L1041
[ "def", "create_gnu_header", "(", "self", ",", "info", ",", "encoding", ",", "errors", ")", ":", "info", "[", "\"magic\"", "]", "=", "GNU_MAGIC", "buf", "=", "b\"\"", "if", "len", "(", "info", "[", "\"linkname\"", "]", ")", ">", "LENGTH_LINK", ":", "buf...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.create_pax_header
Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information.
pipenv/vendor/distlib/_backport/tarfile.py
def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. """ info["magic"] = POSIX_MAGIC pax_headers = self.pax_headers.copy() # Test string fields for values that exceed the field length or cannot # be represented in ASCII encoding. for name, hname, length in ( ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), ("uname", "uname", 32), ("gname", "gname", 32)): if hname in pax_headers: # The pax header has priority. continue # Try to encode the string as ASCII. try: info[name].encode("ascii", "strict") except UnicodeEncodeError: pax_headers[hname] = info[name] continue if len(info[name]) > length: pax_headers[hname] = info[name] # Test number fields for values that exceed the field limit or values # that like to be stored as float. for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): if name in pax_headers: # The pax header has priority. Avoid overflow. info[name] = 0 continue val = info[name] if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): pax_headers[name] = str(val) info[name] = 0 # Create a pax extended header if necessary. if pax_headers: buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. """ info["magic"] = POSIX_MAGIC pax_headers = self.pax_headers.copy() # Test string fields for values that exceed the field length or cannot # be represented in ASCII encoding. for name, hname, length in ( ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), ("uname", "uname", 32), ("gname", "gname", 32)): if hname in pax_headers: # The pax header has priority. continue # Try to encode the string as ASCII. try: info[name].encode("ascii", "strict") except UnicodeEncodeError: pax_headers[hname] = info[name] continue if len(info[name]) > length: pax_headers[hname] = info[name] # Test number fields for values that exceed the field limit or values # that like to be stored as float. for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): if name in pax_headers: # The pax header has priority. Avoid overflow. info[name] = 0 continue val = info[name] if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): pax_headers[name] = str(val) info[name] = 0 # Create a pax extended header if necessary. if pax_headers: buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", ".", "If", "it", "cannot", "be", "represented", "this", "way", "prepend", "a", "pax", "extended", "header", "sequence", "with", "supplement", "information", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1043-L1090
[ "def", "create_pax_header", "(", "self", ",", "info", ",", "encoding", ")", ":", "info", "[", "\"magic\"", "]", "=", "POSIX_MAGIC", "pax_headers", "=", "self", ".", "pax_headers", ".", "copy", "(", ")", "# Test string fields for values that exceed the field length o...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._posix_split_name
Split a name longer than 100 chars into a prefix and a name part.
pipenv/vendor/distlib/_backport/tarfile.py
def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix and a name part. """ prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = name[len(prefix):] prefix = prefix[:-1] if not prefix or len(name) > LENGTH_NAME: raise ValueError("name is too long") return prefix, name
def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix and a name part. """ prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = name[len(prefix):] prefix = prefix[:-1] if not prefix or len(name) > LENGTH_NAME: raise ValueError("name is too long") return prefix, name
[ "Split", "a", "name", "longer", "than", "100", "chars", "into", "a", "prefix", "and", "a", "name", "part", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1098-L1111
[ "def", "_posix_split_name", "(", "self", ",", "name", ")", ":", "prefix", "=", "name", "[", ":", "LENGTH_PREFIX", "+", "1", "]", "while", "prefix", "and", "prefix", "[", "-", "1", "]", "!=", "\"/\"", ":", "prefix", "=", "prefix", "[", ":", "-", "1"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._create_header
Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants.
pipenv/vendor/distlib/_backport/tarfile.py
def _create_header(info, format, encoding, errors): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. """ parts = [ stn(info.get("name", ""), 100, encoding, errors), itn(info.get("mode", 0) & 0o7777, 8, format), itn(info.get("uid", 0), 8, format), itn(info.get("gid", 0), 8, format), itn(info.get("size", 0), 12, format), itn(info.get("mtime", 0), 12, format), b" ", # checksum field info.get("type", REGTYPE), stn(info.get("linkname", ""), 100, encoding, errors), info.get("magic", POSIX_MAGIC), stn(info.get("uname", ""), 32, encoding, errors), stn(info.get("gname", ""), 32, encoding, errors), itn(info.get("devmajor", 0), 8, format), itn(info.get("devminor", 0), 8, format), stn(info.get("prefix", ""), 155, encoding, errors) ] buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts)) chksum = calc_chksums(buf[-BLOCKSIZE:])[0] buf = buf[:-364] + ("%06o\0" % chksum).encode("ascii") + buf[-357:] return buf
def _create_header(info, format, encoding, errors): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. """ parts = [ stn(info.get("name", ""), 100, encoding, errors), itn(info.get("mode", 0) & 0o7777, 8, format), itn(info.get("uid", 0), 8, format), itn(info.get("gid", 0), 8, format), itn(info.get("size", 0), 12, format), itn(info.get("mtime", 0), 12, format), b" ", # checksum field info.get("type", REGTYPE), stn(info.get("linkname", ""), 100, encoding, errors), info.get("magic", POSIX_MAGIC), stn(info.get("uname", ""), 32, encoding, errors), stn(info.get("gname", ""), 32, encoding, errors), itn(info.get("devmajor", 0), 8, format), itn(info.get("devminor", 0), 8, format), stn(info.get("prefix", ""), 155, encoding, errors) ] buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts)) chksum = calc_chksums(buf[-BLOCKSIZE:])[0] buf = buf[:-364] + ("%06o\0" % chksum).encode("ascii") + buf[-357:] return buf
[ "Return", "a", "header", "block", ".", "info", "is", "a", "dictionary", "with", "file", "information", "format", "must", "be", "one", "of", "the", "*", "_FORMAT", "constants", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1114-L1139
[ "def", "_create_header", "(", "info", ",", "format", ",", "encoding", ",", "errors", ")", ":", "parts", "=", "[", "stn", "(", "info", ".", "get", "(", "\"name\"", ",", "\"\"", ")", ",", "100", ",", "encoding", ",", "errors", ")", ",", "itn", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._create_payload
Return the string payload filled with zero bytes up to the next 512 byte border.
pipenv/vendor/distlib/_backport/tarfile.py
def _create_payload(payload): """Return the string payload filled with zero bytes up to the next 512 byte border. """ blocks, remainder = divmod(len(payload), BLOCKSIZE) if remainder > 0: payload += (BLOCKSIZE - remainder) * NUL return payload
def _create_payload(payload): """Return the string payload filled with zero bytes up to the next 512 byte border. """ blocks, remainder = divmod(len(payload), BLOCKSIZE) if remainder > 0: payload += (BLOCKSIZE - remainder) * NUL return payload
[ "Return", "the", "string", "payload", "filled", "with", "zero", "bytes", "up", "to", "the", "next", "512", "byte", "border", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1142-L1149
[ "def", "_create_payload", "(", "payload", ")", ":", "blocks", ",", "remainder", "=", "divmod", "(", "len", "(", "payload", ")", ",", "BLOCKSIZE", ")", "if", "remainder", ">", "0", ":", "payload", "+=", "(", "BLOCKSIZE", "-", "remainder", ")", "*", "NUL...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._create_gnu_long_header
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name.
pipenv/vendor/distlib/_backport/tarfile.py
def _create_gnu_long_header(cls, name, type, encoding, errors): """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. """ name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" info["type"] = type info["size"] = len(name) info["magic"] = GNU_MAGIC # create extended header + name blocks. return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ cls._create_payload(name)
def _create_gnu_long_header(cls, name, type, encoding, errors): """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. """ name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" info["type"] = type info["size"] = len(name) info["magic"] = GNU_MAGIC # create extended header + name blocks. return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ cls._create_payload(name)
[ "Return", "a", "GNUTYPE_LONGNAME", "or", "GNUTYPE_LONGLINK", "sequence", "for", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1152-L1166
[ "def", "_create_gnu_long_header", "(", "cls", ",", "name", ",", "type", ",", "encoding", ",", "errors", ")", ":", "name", "=", "name", ".", "encode", "(", "encoding", ",", "errors", ")", "+", "NUL", "info", "=", "{", "}", "info", "[", "\"name\"", "]"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._create_pax_generic_header
Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings.
pipenv/vendor/distlib/_backport/tarfile.py
def _create_pax_generic_header(cls, pax_headers, type, encoding): """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ # Check if one of the fields contains surrogate characters and thereby # forces hdrcharset=BINARY, see _proc_pax() for more information. binary = False for keyword, value in pax_headers.items(): try: value.encode("utf8", "strict") except UnicodeEncodeError: binary = True break records = b"" if binary: # Put the hdrcharset field at the beginning of the header. records += b"21 hdrcharset=BINARY\n" for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") if binary: # Try to restore the original byte representation of `value'. # Needless to say, that the encoding must match the string. value = value.encode(encoding, "surrogateescape") else: value = value.encode("utf8") l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: n = l + len(str(p)) if n == p: break p = n records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" # We use a hardcoded "././@PaxHeader" name like star does # instead of the one that POSIX recommends. info = {} info["name"] = "././@PaxHeader" info["type"] = type info["size"] = len(records) info["magic"] = POSIX_MAGIC # Create pax header + record blocks. return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ cls._create_payload(records)
def _create_pax_generic_header(cls, pax_headers, type, encoding): """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ # Check if one of the fields contains surrogate characters and thereby # forces hdrcharset=BINARY, see _proc_pax() for more information. binary = False for keyword, value in pax_headers.items(): try: value.encode("utf8", "strict") except UnicodeEncodeError: binary = True break records = b"" if binary: # Put the hdrcharset field at the beginning of the header. records += b"21 hdrcharset=BINARY\n" for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") if binary: # Try to restore the original byte representation of `value'. # Needless to say, that the encoding must match the string. value = value.encode(encoding, "surrogateescape") else: value = value.encode("utf8") l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: n = l + len(str(p)) if n == p: break p = n records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" # We use a hardcoded "././@PaxHeader" name like star does # instead of the one that POSIX recommends. info = {} info["name"] = "././@PaxHeader" info["type"] = type info["size"] = len(records) info["magic"] = POSIX_MAGIC # Create pax header + record blocks. return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ cls._create_payload(records)
[ "Return", "a", "POSIX", ".", "1", "-", "2008", "extended", "or", "global", "header", "sequence", "that", "contains", "a", "list", "of", "keyword", "value", "pairs", ".", "The", "values", "must", "be", "strings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1169-L1217
[ "def", "_create_pax_generic_header", "(", "cls", ",", "pax_headers", ",", "type", ",", "encoding", ")", ":", "# Check if one of the fields contains surrogate characters and thereby", "# forces hdrcharset=BINARY, see _proc_pax() for more information.", "binary", "=", "False", "for",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.frombuf
Construct a TarInfo object from a 512 byte bytes object.
pipenv/vendor/distlib/_backport/tarfile.py
def frombuf(cls, buf, encoding, errors): """Construct a TarInfo object from a 512 byte bytes object. """ if len(buf) == 0: raise EmptyHeaderError("empty header") if len(buf) != BLOCKSIZE: raise TruncatedHeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: raise EOFHeaderError("end of file header") chksum = nti(buf[148:156]) if chksum not in calc_chksums(buf): raise InvalidHeaderError("bad checksum") obj = cls() obj.name = nts(buf[0:100], encoding, errors) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) obj.gid = nti(buf[116:124]) obj.size = nti(buf[124:136]) obj.mtime = nti(buf[136:148]) obj.chksum = chksum obj.type = buf[156:157] obj.linkname = nts(buf[157:257], encoding, errors) obj.uname = nts(buf[265:297], encoding, errors) obj.gname = nts(buf[297:329], encoding, errors) obj.devmajor = nti(buf[329:337]) obj.devminor = nti(buf[337:345]) prefix = nts(buf[345:500], encoding, errors) # Old V7 tar format represents a directory as a regular # file with a trailing slash. if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE # The old GNU sparse format occupies some of the unused # space in the buffer for up to 4 sparse structures. # Save the them for later processing in _proc_sparse(). if obj.type == GNUTYPE_SPARSE: pos = 386 structs = [] for i in range(4): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[482]) origsize = nti(buf[483:495]) obj._sparse_structs = (structs, isextended, origsize) # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") # Reconstruct a ustar longname. if prefix and obj.type not in GNU_TYPES: obj.name = prefix + "/" + obj.name return obj
def frombuf(cls, buf, encoding, errors): """Construct a TarInfo object from a 512 byte bytes object. """ if len(buf) == 0: raise EmptyHeaderError("empty header") if len(buf) != BLOCKSIZE: raise TruncatedHeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: raise EOFHeaderError("end of file header") chksum = nti(buf[148:156]) if chksum not in calc_chksums(buf): raise InvalidHeaderError("bad checksum") obj = cls() obj.name = nts(buf[0:100], encoding, errors) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) obj.gid = nti(buf[116:124]) obj.size = nti(buf[124:136]) obj.mtime = nti(buf[136:148]) obj.chksum = chksum obj.type = buf[156:157] obj.linkname = nts(buf[157:257], encoding, errors) obj.uname = nts(buf[265:297], encoding, errors) obj.gname = nts(buf[297:329], encoding, errors) obj.devmajor = nti(buf[329:337]) obj.devminor = nti(buf[337:345]) prefix = nts(buf[345:500], encoding, errors) # Old V7 tar format represents a directory as a regular # file with a trailing slash. if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE # The old GNU sparse format occupies some of the unused # space in the buffer for up to 4 sparse structures. # Save the them for later processing in _proc_sparse(). if obj.type == GNUTYPE_SPARSE: pos = 386 structs = [] for i in range(4): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[482]) origsize = nti(buf[483:495]) obj._sparse_structs = (structs, isextended, origsize) # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") # Reconstruct a ustar longname. if prefix and obj.type not in GNU_TYPES: obj.name = prefix + "/" + obj.name return obj
[ "Construct", "a", "TarInfo", "object", "from", "a", "512", "byte", "bytes", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1220-L1280
[ "def", "frombuf", "(", "cls", ",", "buf", ",", "encoding", ",", "errors", ")", ":", "if", "len", "(", "buf", ")", "==", "0", ":", "raise", "EmptyHeaderError", "(", "\"empty header\"", ")", "if", "len", "(", "buf", ")", "!=", "BLOCKSIZE", ":", "raise"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo.fromtarfile
Return the next TarInfo object from TarFile object tarfile.
pipenv/vendor/distlib/_backport/tarfile.py
def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE return obj._proc_member(tarfile)
def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE return obj._proc_member(tarfile)
[ "Return", "the", "next", "TarInfo", "object", "from", "TarFile", "object", "tarfile", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1283-L1290
[ "def", "fromtarfile", "(", "cls", ",", "tarfile", ")", ":", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "BLOCKSIZE", ")", "obj", "=", "cls", ".", "frombuf", "(", "buf", ",", "tarfile", ".", "encoding", ",", "tarfile", ".", "errors", ")",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_member
Choose the right processing method depending on the type and call it.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(tarfile) elif self.type == GNUTYPE_SPARSE: return self._proc_sparse(tarfile) elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): return self._proc_pax(tarfile) else: return self._proc_builtin(tarfile)
def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(tarfile) elif self.type == GNUTYPE_SPARSE: return self._proc_sparse(tarfile) elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): return self._proc_pax(tarfile) else: return self._proc_builtin(tarfile)
[ "Choose", "the", "right", "processing", "method", "depending", "on", "the", "type", "and", "call", "it", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1303-L1314
[ "def", "_proc_member", "(", "self", ",", "tarfile", ")", ":", "if", "self", ".", "type", "in", "(", "GNUTYPE_LONGNAME", ",", "GNUTYPE_LONGLINK", ")", ":", "return", "self", ".", "_proc_gnulong", "(", "tarfile", ")", "elif", "self", ".", "type", "==", "GN...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_builtin
Process a builtin type or an unknown type which will be treated as a regular file.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
[ "Process", "a", "builtin", "type", "or", "an", "unknown", "type", "which", "will", "be", "treated", "as", "a", "regular", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1316-L1331
[ "def", "_proc_builtin", "(", "self", ",", "tarfile", ")", ":", "self", ".", "offset_data", "=", "tarfile", ".", "fileobj", ".", "tell", "(", ")", "offset", "=", "self", ".", "offset_data", "if", "self", ".", "isreg", "(", ")", "or", "self", ".", "typ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_gnulong
Process the blocks that hold a GNU longname or longlink member.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Patch the TarInfo object from the next header with # the longname information. next.offset = self.offset if self.type == GNUTYPE_LONGNAME: next.name = nts(buf, tarfile.encoding, tarfile.errors) elif self.type == GNUTYPE_LONGLINK: next.linkname = nts(buf, tarfile.encoding, tarfile.errors) return next
def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Patch the TarInfo object from the next header with # the longname information. next.offset = self.offset if self.type == GNUTYPE_LONGNAME: next.name = nts(buf, tarfile.encoding, tarfile.errors) elif self.type == GNUTYPE_LONGLINK: next.linkname = nts(buf, tarfile.encoding, tarfile.errors) return next
[ "Process", "the", "blocks", "that", "hold", "a", "GNU", "longname", "or", "longlink", "member", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1333-L1353
[ "def", "_proc_gnulong", "(", "self", ",", "tarfile", ")", ":", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "self", ".", "_block", "(", "self", ".", "size", ")", ")", "# Fetch the next header and process it.", "try", ":", "next", "=", "self", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_sparse
Process a GNU sparse header plus extra headers.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 for i in range(21): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset and numbytes: structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) self.sparse = structs self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) self.size = origsize return self
def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 for i in range(21): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset and numbytes: structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) self.sparse = structs self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) self.size = origsize return self
[ "Process", "a", "GNU", "sparse", "header", "plus", "extra", "headers", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1355-L1381
[ "def", "_proc_sparse", "(", "self", ",", "tarfile", ")", ":", "# We already collected some sparse structures in frombuf().", "structs", ",", "isextended", ",", "origsize", "=", "self", ".", "_sparse_structs", "del", "self", ".", "_sparse_structs", "# Collect sparse struct...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_pax
Process an extended or global header as described in POSIX.1-2008.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental information for either # the following file (extended) or all following files # (global). if self.type == XGLTYPE: pax_headers = tarfile.pax_headers else: pax_headers = tarfile.pax_headers.copy() # Check if the pax header contains a hdrcharset field. This tells us # the encoding of the path, linkpath, uname and gname fields. Normally, # these fields are UTF-8 encoded but since POSIX.1-2008 tar # implementations are allowed to store them as raw binary strings if # the translation to UTF-8 fails. match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) if match is not None: pax_headers["hdrcharset"] = match.group(1).decode("utf8") # For the time being, we don't care about anything other than "BINARY". # The only other value that is currently allowed by the standard is # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. hdrcharset = pax_headers.get("hdrcharset") if hdrcharset == "BINARY": encoding = tarfile.encoding else: encoding = "utf8" # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and # the newline. keyword and value are both UTF-8 encoded strings. regex = re.compile(br"(\d+) ([^=]+)=") pos = 0 while True: match = regex.match(buf, pos) if not match: break length, keyword = match.groups() length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] # Normally, we could just use "utf8" as the encoding and "strict" # as the error handler, but we better not take the risk. For # example, GNU tar <= 1.23 is known to store filenames it cannot # translate to UTF-8 as raw strings (unfortunately without a # hdrcharset=BINARY header). # We first try the strict standard encoding, and if that fails we # fall back on the user's encoding and error handler. keyword = self._decode_pax_field(keyword, "utf8", "utf8", tarfile.errors) if keyword in PAX_NAME_FIELDS: value = self._decode_pax_field(value, encoding, tarfile.encoding, tarfile.errors) else: value = self._decode_pax_field(value, "utf8", "utf8", tarfile.errors) pax_headers[keyword] = value pos += length # Fetch the next header. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Process GNU sparse information. if "GNU.sparse.map" in pax_headers: # GNU extended sparse format version 0.1. self._proc_gnusparse_01(next, pax_headers) elif "GNU.sparse.size" in pax_headers: # GNU extended sparse format version 0.0. self._proc_gnusparse_00(next, pax_headers, buf) elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0": # GNU extended sparse format version 1.0. self._proc_gnusparse_10(next, pax_headers, tarfile) if self.type in (XHDTYPE, SOLARIS_XHDTYPE): # Patch the TarInfo object with the extended header info. next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) next.offset = self.offset if "size" in pax_headers: # If the extended header replaces the size field, # we need to recalculate the offset where the next # header starts. offset = next.offset_data if next.isreg() or next.type not in SUPPORTED_TYPES: offset += next._block(next.size) tarfile.offset = offset return next
def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental information for either # the following file (extended) or all following files # (global). if self.type == XGLTYPE: pax_headers = tarfile.pax_headers else: pax_headers = tarfile.pax_headers.copy() # Check if the pax header contains a hdrcharset field. This tells us # the encoding of the path, linkpath, uname and gname fields. Normally, # these fields are UTF-8 encoded but since POSIX.1-2008 tar # implementations are allowed to store them as raw binary strings if # the translation to UTF-8 fails. match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) if match is not None: pax_headers["hdrcharset"] = match.group(1).decode("utf8") # For the time being, we don't care about anything other than "BINARY". # The only other value that is currently allowed by the standard is # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. hdrcharset = pax_headers.get("hdrcharset") if hdrcharset == "BINARY": encoding = tarfile.encoding else: encoding = "utf8" # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and # the newline. keyword and value are both UTF-8 encoded strings. regex = re.compile(br"(\d+) ([^=]+)=") pos = 0 while True: match = regex.match(buf, pos) if not match: break length, keyword = match.groups() length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] # Normally, we could just use "utf8" as the encoding and "strict" # as the error handler, but we better not take the risk. For # example, GNU tar <= 1.23 is known to store filenames it cannot # translate to UTF-8 as raw strings (unfortunately without a # hdrcharset=BINARY header). # We first try the strict standard encoding, and if that fails we # fall back on the user's encoding and error handler. keyword = self._decode_pax_field(keyword, "utf8", "utf8", tarfile.errors) if keyword in PAX_NAME_FIELDS: value = self._decode_pax_field(value, encoding, tarfile.encoding, tarfile.errors) else: value = self._decode_pax_field(value, "utf8", "utf8", tarfile.errors) pax_headers[keyword] = value pos += length # Fetch the next header. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Process GNU sparse information. if "GNU.sparse.map" in pax_headers: # GNU extended sparse format version 0.1. self._proc_gnusparse_01(next, pax_headers) elif "GNU.sparse.size" in pax_headers: # GNU extended sparse format version 0.0. self._proc_gnusparse_00(next, pax_headers, buf) elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0": # GNU extended sparse format version 1.0. self._proc_gnusparse_10(next, pax_headers, tarfile) if self.type in (XHDTYPE, SOLARIS_XHDTYPE): # Patch the TarInfo object with the extended header info. next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) next.offset = self.offset if "size" in pax_headers: # If the extended header replaces the size field, # we need to recalculate the offset where the next # header starts. offset = next.offset_data if next.isreg() or next.type not in SUPPORTED_TYPES: offset += next._block(next.size) tarfile.offset = offset return next
[ "Process", "an", "extended", "or", "global", "header", "as", "described", "in", "POSIX", ".", "1", "-", "2008", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1383-L1483
[ "def", "_proc_pax", "(", "self", ",", "tarfile", ")", ":", "# Read the header information.", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "self", ".", "_block", "(", "self", ".", "size", ")", ")", "# A pax header stores supplemental information for eit...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_gnusparse_00
Process a GNU tar extended sparse header, version 0.0.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match.group(1))) numbytes = [] for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf): numbytes.append(int(match.group(1))) next.sparse = list(zip(offsets, numbytes))
def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match.group(1))) numbytes = [] for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf): numbytes.append(int(match.group(1))) next.sparse = list(zip(offsets, numbytes))
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "0", ".", "0", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1485-L1494
[ "def", "_proc_gnusparse_00", "(", "self", ",", "next", ",", "pax_headers", ",", "buf", ")", ":", "offsets", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "br\"\\d+ GNU.sparse.offset=(\\d+)\\n\"", ",", "buf", ")", ":", "offsets", ".", "ap...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_gnusparse_01
Process a GNU tar extended sparse header, version 0.1.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2]))
def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2]))
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "0", ".", "1", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1496-L1500
[ "def", "_proc_gnusparse_01", "(", "self", ",", "next", ",", "pax_headers", ")", ":", "sparse", "=", "[", "int", "(", "x", ")", "for", "x", "in", "pax_headers", "[", "\"GNU.sparse.map\"", "]", ".", "split", "(", "\",\"", ")", "]", "next", ".", "sparse",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._proc_gnusparse_10
Process a GNU tar extended sparse header, version 1.0.
pipenv/vendor/distlib/_backport/tarfile.py
def _proc_gnusparse_10(self, next, pax_headers, tarfile): """Process a GNU tar extended sparse header, version 1.0. """ fields = None sparse = [] buf = tarfile.fileobj.read(BLOCKSIZE) fields, buf = buf.split(b"\n", 1) fields = int(fields) while len(sparse) < fields * 2: if b"\n" not in buf: buf += tarfile.fileobj.read(BLOCKSIZE) number, buf = buf.split(b"\n", 1) sparse.append(int(number)) next.offset_data = tarfile.fileobj.tell() next.sparse = list(zip(sparse[::2], sparse[1::2]))
def _proc_gnusparse_10(self, next, pax_headers, tarfile): """Process a GNU tar extended sparse header, version 1.0. """ fields = None sparse = [] buf = tarfile.fileobj.read(BLOCKSIZE) fields, buf = buf.split(b"\n", 1) fields = int(fields) while len(sparse) < fields * 2: if b"\n" not in buf: buf += tarfile.fileobj.read(BLOCKSIZE) number, buf = buf.split(b"\n", 1) sparse.append(int(number)) next.offset_data = tarfile.fileobj.tell() next.sparse = list(zip(sparse[::2], sparse[1::2]))
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "1", ".", "0", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1502-L1516
[ "def", "_proc_gnusparse_10", "(", "self", ",", "next", ",", "pax_headers", ",", "tarfile", ")", ":", "fields", "=", "None", "sparse", "=", "[", "]", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "BLOCKSIZE", ")", "fields", ",", "buf", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._apply_pax_info
Replace fields with supplemental information from a previous pax extended or global header.
pipenv/vendor/distlib/_backport/tarfile.py
def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": setattr(self, "size", int(value)) elif keyword in PAX_FIELDS: if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) self.pax_headers = pax_headers.copy()
def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": setattr(self, "size", int(value)) elif keyword in PAX_FIELDS: if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) self.pax_headers = pax_headers.copy()
[ "Replace", "fields", "with", "supplemental", "information", "from", "a", "previous", "pax", "extended", "or", "global", "header", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1518-L1539
[ "def", "_apply_pax_info", "(", "self", ",", "pax_headers", ",", "encoding", ",", "errors", ")", ":", "for", "keyword", ",", "value", "in", "pax_headers", ".", "items", "(", ")", ":", "if", "keyword", "==", "\"GNU.sparse.name\"", ":", "setattr", "(", "self"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._decode_pax_field
Decode a single field from a pax record.
pipenv/vendor/distlib/_backport/tarfile.py
def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ try: return value.decode(encoding, "strict") except UnicodeDecodeError: return value.decode(fallback_encoding, fallback_errors)
def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ try: return value.decode(encoding, "strict") except UnicodeDecodeError: return value.decode(fallback_encoding, fallback_errors)
[ "Decode", "a", "single", "field", "from", "a", "pax", "record", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1541-L1547
[ "def", "_decode_pax_field", "(", "self", ",", "value", ",", "encoding", ",", "fallback_encoding", ",", "fallback_errors", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "encoding", ",", "\"strict\"", ")", "except", "UnicodeDecodeError", ":", "ret...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarInfo._block
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024.
pipenv/vendor/distlib/_backport/tarfile.py
def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE
def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE
[ "Round", "up", "a", "byte", "count", "by", "BLOCKSIZE", "and", "return", "it", "e", ".", "g", ".", "_block", "(", "834", ")", "=", ">", "1024", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1549-L1556
[ "def", "_block", "(", "self", ",", "count", ")", ":", "blocks", ",", "remainder", "=", "divmod", "(", "count", ",", "BLOCKSIZE", ")", "if", "remainder", ":", "blocks", "+=", "1", "return", "blocks", "*", "BLOCKSIZE" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.open
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing
pipenv/vendor/distlib/_backport/tarfile.py
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError) as e: if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in "rw": raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in "aw": return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode")
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError) as e: if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in "rw": raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in "aw": return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode")
[ "Open", "a", "tar", "archive", "for", "reading", "writing", "or", "appending", ".", "Return", "an", "appropriate", "TarFile", "class", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1714-L1787
[ "def", "open", "(", "cls", ",", "name", "=", "None", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "bufsize", "=", "RECORDSIZE", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", "and", "not", "fileobj", ":", "raise", "ValueErr...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.taropen
Open uncompressed tar archive name for reading or writing.
pipenv/vendor/distlib/_backport/tarfile.py
def taropen(cls, name, mode="r", fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") return cls(name, mode, fileobj, **kwargs)
def taropen(cls, name, mode="r", fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") return cls(name, mode, fileobj, **kwargs)
[ "Open", "uncompressed", "tar", "archive", "name", "for", "reading", "or", "writing", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1790-L1795
[ "def", "taropen", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"raw\"", ":", "raise", "ValueError", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.gzopen
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
pipenv/vendor/distlib/_backport/tarfile.py
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") extfileobj = fileobj is not None try: fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: if not extfileobj and fileobj is not None: fileobj.close() if fileobj is None: raise raise ReadError("not a gzip file") except: if not extfileobj and fileobj is not None: fileobj.close() raise t._extfileobj = extfileobj return t
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") extfileobj = fileobj is not None try: fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: if not extfileobj and fileobj is not None: fileobj.close() if fileobj is None: raise raise ReadError("not a gzip file") except: if not extfileobj and fileobj is not None: fileobj.close() raise t._extfileobj = extfileobj return t
[ "Open", "gzip", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1798-L1826
[ "def", "gzopen", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "compresslevel", "=", "9", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"rw\"", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.bz2open
Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed.
pipenv/vendor/distlib/_backport/tarfile.py
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'.") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (IOError, EOFError): fileobj.close() raise ReadError("not a bzip2 file") t._extfileobj = False return t
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'.") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (IOError, EOFError): fileobj.close() raise ReadError("not a bzip2 file") t._extfileobj = False return t
[ "Open", "bzip2", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1829-L1852
[ "def", "bz2open", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "compresslevel", "=", "9", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"rw\"", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.close
Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive.
pipenv/vendor/distlib/_backport/tarfile.py
def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return if self.mode in "aw": self.fileobj.write(NUL * (BLOCKSIZE * 2)) self.offset += (BLOCKSIZE * 2) # fill up the end with zero-blocks # (like option -b20 for tar does) blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) if not self._extfileobj: self.fileobj.close() self.closed = True
def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return if self.mode in "aw": self.fileobj.write(NUL * (BLOCKSIZE * 2)) self.offset += (BLOCKSIZE * 2) # fill up the end with zero-blocks # (like option -b20 for tar does) blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) if not self._extfileobj: self.fileobj.close() self.closed = True
[ "Close", "the", "TarFile", ".", "In", "write", "-", "mode", "two", "finishing", "zero", "blocks", "are", "appended", "to", "the", "archive", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1864-L1882
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "return", "if", "self", ".", "mode", "in", "\"aw\"", ":", "self", ".", "fileobj", ".", "write", "(", "NUL", "*", "(", "BLOCKSIZE", "*", "2", ")", ")", "self", ".", "offset",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.getmember
Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version.
pipenv/vendor/distlib/_backport/tarfile.py
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError("filename %r not found" % name) return tarinfo
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError("filename %r not found" % name) return tarinfo
[ "Return", "a", "TarInfo", "object", "for", "member", "name", ".", "If", "name", "can", "not", "be", "found", "in", "the", "archive", "KeyError", "is", "raised", ".", "If", "a", "member", "occurs", "more", "than", "once", "in", "the", "archive", "its", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1884-L1893
[ "def", "getmember", "(", "self", ",", "name", ")", ":", "tarinfo", "=", "self", ".", "_getmember", "(", "name", ")", "if", "tarinfo", "is", "None", ":", "raise", "KeyError", "(", "\"filename %r not found\"", "%", "name", ")", "return", "tarinfo" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.getmembers
Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive.
pipenv/vendor/distlib/_backport/tarfile.py
def getmembers(self): """Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. """ self._check() if not self._loaded: # if we want to obtain a list of self._load() # all members, we first have to # scan the whole archive. return self.members
def getmembers(self): """Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. """ self._check() if not self._loaded: # if we want to obtain a list of self._load() # all members, we first have to # scan the whole archive. return self.members
[ "Return", "the", "members", "of", "the", "archive", "as", "a", "list", "of", "TarInfo", "objects", ".", "The", "list", "has", "the", "same", "order", "as", "the", "members", "in", "the", "archive", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1895-L1903
[ "def", "getmembers", "(", "self", ")", ":", "self", ".", "_check", "(", ")", "if", "not", "self", ".", "_loaded", ":", "# if we want to obtain a list of", "self", ".", "_load", "(", ")", "# all members, we first have to", "# scan the whole archive.", "return", "se...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.gettarinfo
Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the archive.
pipenv/vendor/distlib/_backport/tarfile.py
def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the archive. """ self._check("aw") # When fileobj is given, replace name by # fileobj's real name. if fileobj is not None: name = fileobj.name # Building the name of the member in the archive. # Backward slashes are converted to forward slashes, # Absolute paths are turned to relative paths. if arcname is None: arcname = name drv, arcname = os.path.splitdrive(arcname) arcname = arcname.replace(os.sep, "/") arcname = arcname.lstrip("/") # Now, fill the TarInfo object with # information specific for the file. tarinfo = self.tarinfo() tarinfo.tarfile = self # Use os.stat or os.lstat, depending on platform # and if symlinks shall be resolved. if fileobj is None: if hasattr(os, "lstat") and not self.dereference: statres = os.lstat(name) else: statres = os.stat(name) else: statres = os.fstat(fileobj.fileno()) linkname = "" stmd = statres.st_mode if stat.S_ISREG(stmd): inode = (statres.st_ino, statres.st_dev) if not self.dereference and statres.st_nlink > 1 and \ inode in self.inodes and arcname != self.inodes[inode]: # Is it a hardlink to an already # archived file? type = LNKTYPE linkname = self.inodes[inode] else: # The inode is added only if its valid. # For win32 it is always 0. type = REGTYPE if inode[0]: self.inodes[inode] = arcname elif stat.S_ISDIR(stmd): type = DIRTYPE elif stat.S_ISFIFO(stmd): type = FIFOTYPE elif stat.S_ISLNK(stmd): type = SYMTYPE linkname = os.readlink(name) elif stat.S_ISCHR(stmd): type = CHRTYPE elif stat.S_ISBLK(stmd): type = BLKTYPE else: return None # Fill the TarInfo object with all # information we can get. tarinfo.name = arcname tarinfo.mode = stmd tarinfo.uid = statres.st_uid tarinfo.gid = statres.st_gid if type == REGTYPE: tarinfo.size = statres.st_size else: tarinfo.size = 0 tarinfo.mtime = statres.st_mtime tarinfo.type = type tarinfo.linkname = linkname if pwd: try: tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] except KeyError: pass if grp: try: tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] except KeyError: pass if type in (CHRTYPE, BLKTYPE): if hasattr(os, "major") and hasattr(os, "minor"): tarinfo.devmajor = os.major(statres.st_rdev) tarinfo.devminor = os.minor(statres.st_rdev) return tarinfo
def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the archive. """ self._check("aw") # When fileobj is given, replace name by # fileobj's real name. if fileobj is not None: name = fileobj.name # Building the name of the member in the archive. # Backward slashes are converted to forward slashes, # Absolute paths are turned to relative paths. if arcname is None: arcname = name drv, arcname = os.path.splitdrive(arcname) arcname = arcname.replace(os.sep, "/") arcname = arcname.lstrip("/") # Now, fill the TarInfo object with # information specific for the file. tarinfo = self.tarinfo() tarinfo.tarfile = self # Use os.stat or os.lstat, depending on platform # and if symlinks shall be resolved. if fileobj is None: if hasattr(os, "lstat") and not self.dereference: statres = os.lstat(name) else: statres = os.stat(name) else: statres = os.fstat(fileobj.fileno()) linkname = "" stmd = statres.st_mode if stat.S_ISREG(stmd): inode = (statres.st_ino, statres.st_dev) if not self.dereference and statres.st_nlink > 1 and \ inode in self.inodes and arcname != self.inodes[inode]: # Is it a hardlink to an already # archived file? type = LNKTYPE linkname = self.inodes[inode] else: # The inode is added only if its valid. # For win32 it is always 0. type = REGTYPE if inode[0]: self.inodes[inode] = arcname elif stat.S_ISDIR(stmd): type = DIRTYPE elif stat.S_ISFIFO(stmd): type = FIFOTYPE elif stat.S_ISLNK(stmd): type = SYMTYPE linkname = os.readlink(name) elif stat.S_ISCHR(stmd): type = CHRTYPE elif stat.S_ISBLK(stmd): type = BLKTYPE else: return None # Fill the TarInfo object with all # information we can get. tarinfo.name = arcname tarinfo.mode = stmd tarinfo.uid = statres.st_uid tarinfo.gid = statres.st_gid if type == REGTYPE: tarinfo.size = statres.st_size else: tarinfo.size = 0 tarinfo.mtime = statres.st_mtime tarinfo.type = type tarinfo.linkname = linkname if pwd: try: tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] except KeyError: pass if grp: try: tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] except KeyError: pass if type in (CHRTYPE, BLKTYPE): if hasattr(os, "major") and hasattr(os, "minor"): tarinfo.devmajor = os.major(statres.st_rdev) tarinfo.devminor = os.minor(statres.st_rdev) return tarinfo
[ "Create", "a", "TarInfo", "object", "for", "either", "the", "file", "name", "or", "the", "file", "object", "fileobj", "(", "using", "os", ".", "fstat", "on", "its", "file", "descriptor", ")", ".", "You", "can", "modify", "some", "of", "the", "TarInfo", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1911-L2007
[ "def", "gettarinfo", "(", "self", ",", "name", "=", "None", ",", "arcname", "=", "None", ",", "fileobj", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "# When fileobj is given, replace name by", "# fileobj's real name.", "if", "fileobj", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.list
Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced.
pipenv/vendor/distlib/_backport/tarfile.py
def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: print(filemode(tarinfo.mode), end=' ') print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): print("%10s" % ("%d,%d" \ % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: print("%10d" % tarinfo.size, end=' ') print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6], end=' ') print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') if verbose: if tarinfo.issym(): print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): print("link to", tarinfo.linkname, end=' ') print()
def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: print(filemode(tarinfo.mode), end=' ') print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): print("%10s" % ("%d,%d" \ % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: print("%10d" % tarinfo.size, end=' ') print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6], end=' ') print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') if verbose: if tarinfo.issym(): print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): print("link to", tarinfo.linkname, end=' ') print()
[ "Print", "a", "table", "of", "contents", "to", "sys", ".", "stdout", ".", "If", "verbose", "is", "False", "only", "the", "names", "of", "the", "members", "are", "printed", ".", "If", "it", "is", "True", "an", "ls", "-", "l", "-", "like", "output", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2009-L2036
[ "def", "list", "(", "self", ",", "verbose", "=", "True", ")", ":", "self", ".", "_check", "(", ")", "for", "tarinfo", "in", "self", ":", "if", "verbose", ":", "print", "(", "filemode", "(", "tarinfo", ".", "mode", ")", ",", "end", "=", "' '", ")"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.addfile
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
pipenv/vendor/distlib/_backport/tarfile.py
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
[ "Add", "the", "TarInfo", "object", "tarinfo", "to", "the", "archive", ".", "If", "fileobj", "is", "given", "tarinfo", ".", "size", "bytes", "are", "read", "from", "it", "and", "added", "to", "the", "archive", ".", "You", "can", "create", "TarInfo", "obje...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2100-L2124
[ "def", "addfile", "(", "self", ",", "tarinfo", ",", "fileobj", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "tarinfo", "=", "copy", ".", "copy", "(", "tarinfo", ")", "buf", "=", "tarinfo", ".", "tobuf", "(", "self", ".", "forma...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.extractall
Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers().
pipenv/vendor/distlib/_backport/tarfile.py
def extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0o700 # Do not set_attrs directories, as we will do that further down self.extract(tarinfo, path, set_attrs=not tarinfo.isdir()) # Reverse sort directories. directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
def extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0o700 # Do not set_attrs directories, as we will do that further down self.extract(tarinfo, path, set_attrs=not tarinfo.isdir()) # Reverse sort directories. directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
[ "Extract", "all", "members", "from", "the", "archive", "to", "the", "current", "working", "directory", "and", "set", "owner", "modification", "time", "and", "permissions", "on", "directories", "afterwards", ".", "path", "specifies", "a", "different", "directory", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2126-L2162
[ "def", "extractall", "(", "self", ",", "path", "=", "\".\"", ",", "members", "=", "None", ")", ":", "directories", "=", "[", "]", "if", "members", "is", "None", ":", "members", "=", "self", "for", "tarinfo", "in", "members", ":", "if", "tarinfo", "."...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.extract
Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mtime, mode) are set unless `set_attrs' is False.
pipenv/vendor/distlib/_backport/tarfile.py
def extract(self, member, path="", set_attrs=True): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mtime, mode) are set unless `set_attrs' is False. """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member # Prepare the link target for makelink(). if tarinfo.islnk(): tarinfo._link_target = os.path.join(path, tarinfo.linkname) try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name), set_attrs=set_attrs) except EnvironmentError as e: if self.errorlevel > 0: raise else: if e.filename is None: self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
def extract(self, member, path="", set_attrs=True): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mtime, mode) are set unless `set_attrs' is False. """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member # Prepare the link target for makelink(). if tarinfo.islnk(): tarinfo._link_target = os.path.join(path, tarinfo.linkname) try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name), set_attrs=set_attrs) except EnvironmentError as e: if self.errorlevel > 0: raise else: if e.filename is None: self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
[ "Extract", "a", "member", "from", "the", "archive", "to", "the", "current", "working", "directory", "using", "its", "full", "name", ".", "Its", "file", "information", "is", "extracted", "as", "accurately", "as", "possible", ".", "member", "may", "be", "a", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2164-L2197
[ "def", "extract", "(", "self", ",", "member", ",", "path", "=", "\"\"", ",", "set_attrs", "=", "True", ")", ":", "self", ".", "_check", "(", "\"r\"", ")", "if", "isinstance", "(", "member", ",", "str", ")", ":", "tarinfo", "=", "self", ".", "getmem...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.extractfile
Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell()
pipenv/vendor/distlib/_backport/tarfile.py
def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member if tarinfo.isreg(): return self.fileobject(self, tarinfo) elif tarinfo.type not in SUPPORTED_TYPES: # If a member's type is unknown, it is treated as a # regular file. return self.fileobject(self, tarinfo) elif tarinfo.islnk() or tarinfo.issym(): if isinstance(self.fileobj, _Stream): # A small but ugly workaround for the case that someone tries # to extract a (sym)link as a file-object from a non-seekable # stream of tar blocks. raise StreamError("cannot extract (sym)link as file object") else: # A (sym)link's file object is its target's file object. return self.extractfile(self._find_link_target(tarinfo)) else: # If there's no data associated with the member (directory, chrdev, # blkdev, etc.), return None instead of a file object. return None
def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member if tarinfo.isreg(): return self.fileobject(self, tarinfo) elif tarinfo.type not in SUPPORTED_TYPES: # If a member's type is unknown, it is treated as a # regular file. return self.fileobject(self, tarinfo) elif tarinfo.islnk() or tarinfo.issym(): if isinstance(self.fileobj, _Stream): # A small but ugly workaround for the case that someone tries # to extract a (sym)link as a file-object from a non-seekable # stream of tar blocks. raise StreamError("cannot extract (sym)link as file object") else: # A (sym)link's file object is its target's file object. return self.extractfile(self._find_link_target(tarinfo)) else: # If there's no data associated with the member (directory, chrdev, # blkdev, etc.), return None instead of a file object. return None
[ "Extract", "a", "member", "from", "the", "archive", "as", "a", "file", "object", ".", "member", "may", "be", "a", "filename", "or", "a", "TarInfo", "object", ".", "If", "member", "is", "a", "regular", "file", "a", "file", "-", "like", "object", "is", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2199-L2235
[ "def", "extractfile", "(", "self", ",", "member", ")", ":", "self", ".", "_check", "(", "\"r\"", ")", "if", "isinstance", "(", "member", ",", "str", ")", ":", "tarinfo", "=", "self", ".", "getmember", "(", "member", ")", "else", ":", "tarinfo", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._extract_member
Extract the TarInfo object tarinfo to a physical file called targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def _extract_member(self, tarinfo, targetpath, set_attrs=True): """Extract the TarInfo object tarinfo to a physical file called targetpath. """ # Fetch the TarInfo object for the given name # and build the destination pathname, replacing # forward slashes to platform specific separators. targetpath = targetpath.rstrip("/") targetpath = targetpath.replace("/", os.sep) # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): # Create directories that are not part of the archive with # default permissions. os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) else: self._dbg(1, tarinfo.name) if tarinfo.isreg(): self.makefile(tarinfo, targetpath) elif tarinfo.isdir(): self.makedir(tarinfo, targetpath) elif tarinfo.isfifo(): self.makefifo(tarinfo, targetpath) elif tarinfo.ischr() or tarinfo.isblk(): self.makedev(tarinfo, targetpath) elif tarinfo.islnk() or tarinfo.issym(): self.makelink(tarinfo, targetpath) elif tarinfo.type not in SUPPORTED_TYPES: self.makeunknown(tarinfo, targetpath) else: self.makefile(tarinfo, targetpath) if set_attrs: self.chown(tarinfo, targetpath) if not tarinfo.issym(): self.chmod(tarinfo, targetpath) self.utime(tarinfo, targetpath)
def _extract_member(self, tarinfo, targetpath, set_attrs=True): """Extract the TarInfo object tarinfo to a physical file called targetpath. """ # Fetch the TarInfo object for the given name # and build the destination pathname, replacing # forward slashes to platform specific separators. targetpath = targetpath.rstrip("/") targetpath = targetpath.replace("/", os.sep) # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): # Create directories that are not part of the archive with # default permissions. os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) else: self._dbg(1, tarinfo.name) if tarinfo.isreg(): self.makefile(tarinfo, targetpath) elif tarinfo.isdir(): self.makedir(tarinfo, targetpath) elif tarinfo.isfifo(): self.makefifo(tarinfo, targetpath) elif tarinfo.ischr() or tarinfo.isblk(): self.makedev(tarinfo, targetpath) elif tarinfo.islnk() or tarinfo.issym(): self.makelink(tarinfo, targetpath) elif tarinfo.type not in SUPPORTED_TYPES: self.makeunknown(tarinfo, targetpath) else: self.makefile(tarinfo, targetpath) if set_attrs: self.chown(tarinfo, targetpath) if not tarinfo.issym(): self.chmod(tarinfo, targetpath) self.utime(tarinfo, targetpath)
[ "Extract", "the", "TarInfo", "object", "tarinfo", "to", "a", "physical", "file", "called", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2237-L2278
[ "def", "_extract_member", "(", "self", ",", "tarinfo", ",", "targetpath", ",", "set_attrs", "=", "True", ")", ":", "# Fetch the TarInfo object for the given name", "# and build the destination pathname, replacing", "# forward slashes to platform specific separators.", "targetpath",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makedir
Make a directory called targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except EnvironmentError as e: if e.errno != errno.EEXIST: raise
def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except EnvironmentError as e: if e.errno != errno.EEXIST: raise
[ "Make", "a", "directory", "called", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2285-L2294
[ "def", "makedir", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "try", ":", "# Use a safe mode for the directory, the real mode is set", "# later in _extract_member().", "os", ".", "mkdir", "(", "targetpath", ",", "0o700", ")", "except", "EnvironmentError", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makefile
Make a file called targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) target = bltn_open(targetpath, "wb") if tarinfo.sparse is not None: for offset, size in tarinfo.sparse: target.seek(offset) copyfileobj(source, target, size) else: copyfileobj(source, target, tarinfo.size) target.seek(tarinfo.size) target.truncate() target.close()
def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) target = bltn_open(targetpath, "wb") if tarinfo.sparse is not None: for offset, size in tarinfo.sparse: target.seek(offset) copyfileobj(source, target, size) else: copyfileobj(source, target, tarinfo.size) target.seek(tarinfo.size) target.truncate() target.close()
[ "Make", "a", "file", "called", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2296-L2310
[ "def", "makefile", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "source", "=", "self", ".", "fileobj", "source", ".", "seek", "(", "tarinfo", ".", "offset_data", ")", "target", "=", "bltn_open", "(", "targetpath", ",", "\"wb\"", ")", "if", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makeunknown
Make a file from a TarInfo object with an unknown type at targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def makeunknown(self, tarinfo, targetpath): """Make a file from a TarInfo object with an unknown type at targetpath. """ self.makefile(tarinfo, targetpath) self._dbg(1, "tarfile: Unknown file type %r, " \ "extracted as regular file." % tarinfo.type)
def makeunknown(self, tarinfo, targetpath): """Make a file from a TarInfo object with an unknown type at targetpath. """ self.makefile(tarinfo, targetpath) self._dbg(1, "tarfile: Unknown file type %r, " \ "extracted as regular file." % tarinfo.type)
[ "Make", "a", "file", "from", "a", "TarInfo", "object", "with", "an", "unknown", "type", "at", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2312-L2318
[ "def", "makeunknown", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "self", ".", "makefile", "(", "tarinfo", ",", "targetpath", ")", "self", ".", "_dbg", "(", "1", ",", "\"tarfile: Unknown file type %r, \"", "\"extracted as regular file.\"", "%", "ta...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makefifo
Make a fifo called targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def makefifo(self, tarinfo, targetpath): """Make a fifo called targetpath. """ if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError("fifo not supported by system")
def makefifo(self, tarinfo, targetpath): """Make a fifo called targetpath. """ if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError("fifo not supported by system")
[ "Make", "a", "fifo", "called", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2320-L2326
[ "def", "makefifo", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "hasattr", "(", "os", ",", "\"mkfifo\"", ")", ":", "os", ".", "mkfifo", "(", "targetpath", ")", "else", ":", "raise", "ExtractError", "(", "\"fifo not supported by system\"", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makedev
Make a character or block device called targetpath.
pipenv/vendor/distlib/_backport/tarfile.py
def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError("special devices not supported by system") mode = tarinfo.mode if tarinfo.isblk(): mode |= stat.S_IFBLK else: mode |= stat.S_IFCHR os.mknod(targetpath, mode, os.makedev(tarinfo.devmajor, tarinfo.devminor))
def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError("special devices not supported by system") mode = tarinfo.mode if tarinfo.isblk(): mode |= stat.S_IFBLK else: mode |= stat.S_IFCHR os.mknod(targetpath, mode, os.makedev(tarinfo.devmajor, tarinfo.devminor))
[ "Make", "a", "character", "or", "block", "device", "called", "targetpath", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2328-L2341
[ "def", "makedev", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "\"mknod\"", ")", "or", "not", "hasattr", "(", "os", ",", "\"makedev\"", ")", ":", "raise", "ExtractError", "(", "\"special devices not supp...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.makelink
Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link.
pipenv/vendor/distlib/_backport/tarfile.py
def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. """ try: # For systems that support symbolic and hard links. if tarinfo.issym(): os.symlink(tarinfo.linkname, targetpath) else: # See extract(). if os.path.exists(tarinfo._link_target): os.link(tarinfo._link_target, targetpath) else: self._extract_member(self._find_link_target(tarinfo), targetpath) except symlink_exception: if tarinfo.issym(): linkpath = os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname) else: linkpath = tarinfo.linkname else: try: self._extract_member(self._find_link_target(tarinfo), targetpath) except KeyError: raise ExtractError("unable to resolve link inside archive")
def makelink(self, tarinfo, targetpath): """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. """ try: # For systems that support symbolic and hard links. if tarinfo.issym(): os.symlink(tarinfo.linkname, targetpath) else: # See extract(). if os.path.exists(tarinfo._link_target): os.link(tarinfo._link_target, targetpath) else: self._extract_member(self._find_link_target(tarinfo), targetpath) except symlink_exception: if tarinfo.issym(): linkpath = os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname) else: linkpath = tarinfo.linkname else: try: self._extract_member(self._find_link_target(tarinfo), targetpath) except KeyError: raise ExtractError("unable to resolve link inside archive")
[ "Make", "a", "(", "symbolic", ")", "link", "called", "targetpath", ".", "If", "it", "cannot", "be", "created", "(", "platform", "limitation", ")", "we", "try", "to", "make", "a", "copy", "of", "the", "referenced", "file", "instead", "of", "a", "link", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2343-L2370
[ "def", "makelink", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "try", ":", "# For systems that support symbolic and hard links.", "if", "tarinfo", ".", "issym", "(", ")", ":", "os", ".", "symlink", "(", "tarinfo", ".", "linkname", ",", "targetpat...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.chown
Set owner of targetpath according to tarinfo.
pipenv/vendor/distlib/_backport/tarfile.py
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError as e: raise ExtractError("could not change owner")
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError as e: raise ExtractError("could not change owner")
[ "Set", "owner", "of", "targetpath", "according", "to", "tarinfo", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2372-L2392
[ "def", "chown", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "pwd", "and", "hasattr", "(", "os", ",", "\"geteuid\"", ")", "and", "os", ".", "geteuid", "(", ")", "==", "0", ":", "# We have to be root to do so.", "try", ":", "g", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.chmod
Set file permissions of targetpath according to tarinfo.
pipenv/vendor/distlib/_backport/tarfile.py
def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except EnvironmentError as e: raise ExtractError("could not change mode")
def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except EnvironmentError as e: raise ExtractError("could not change mode")
[ "Set", "file", "permissions", "of", "targetpath", "according", "to", "tarinfo", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2394-L2401
[ "def", "chmod", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "hasattr", "(", "os", ",", "'chmod'", ")", ":", "try", ":", "os", ".", "chmod", "(", "targetpath", ",", "tarinfo", ".", "mode", ")", "except", "EnvironmentError", "as", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.utime
Set modification time of targetpath according to tarinfo.
pipenv/vendor/distlib/_backport/tarfile.py
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except EnvironmentError as e: raise ExtractError("could not change modification time")
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except EnvironmentError as e: raise ExtractError("could not change modification time")
[ "Set", "modification", "time", "of", "targetpath", "according", "to", "tarinfo", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2403-L2411
[ "def", "utime", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "'utime'", ")", ":", "return", "try", ":", "os", ".", "utime", "(", "targetpath", ",", "(", "tarinfo", ".", "mtime", ",", "tarinfo", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile.next
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.
pipenv/vendor/distlib/_backport/tarfile.py
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m # Read the next block. self.fileobj.seek(self.offset) tarinfo = None while True: try: tarinfo = self.tarinfo.fromtarfile(self) except EOFHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue except InvalidHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue elif self.offset == 0: raise ReadError(str(e)) except EmptyHeaderError: if self.offset == 0: raise ReadError("empty file") except TruncatedHeaderError as e: if self.offset == 0: raise ReadError(str(e)) except SubsequentHeaderError as e: raise ReadError(str(e)) break if tarinfo is not None: self.members.append(tarinfo) else: self._loaded = True return tarinfo
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m # Read the next block. self.fileobj.seek(self.offset) tarinfo = None while True: try: tarinfo = self.tarinfo.fromtarfile(self) except EOFHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue except InvalidHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue elif self.offset == 0: raise ReadError(str(e)) except EmptyHeaderError: if self.offset == 0: raise ReadError("empty file") except TruncatedHeaderError as e: if self.offset == 0: raise ReadError(str(e)) except SubsequentHeaderError as e: raise ReadError(str(e)) break if tarinfo is not None: self.members.append(tarinfo) else: self._loaded = True return tarinfo
[ "Return", "the", "next", "member", "of", "the", "archive", "as", "a", "TarInfo", "object", "when", "TarFile", "is", "opened", "for", "reading", ".", "Return", "None", "if", "there", "is", "no", "more", "available", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2414-L2458
[ "def", "next", "(", "self", ")", ":", "self", ".", "_check", "(", "\"ra\"", ")", "if", "self", ".", "firstmember", "is", "not", "None", ":", "m", "=", "self", ".", "firstmember", "self", ".", "firstmember", "=", "None", "return", "m", "# Read the next ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._getmember
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point.
pipenv/vendor/distlib/_backport/tarfile.py
def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member
def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member
[ "Find", "an", "archive", "member", "by", "name", "from", "bottom", "to", "top", ".", "If", "tarinfo", "is", "given", "it", "is", "used", "as", "the", "starting", "point", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2463-L2484
[ "def", "_getmember", "(", "self", ",", "name", ",", "tarinfo", "=", "None", ",", "normalize", "=", "False", ")", ":", "# Ensure that all members have been loaded.", "members", "=", "self", ".", "getmembers", "(", ")", "# Limit the member search list up to tarinfo.", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._load
Read through the entire archive file and look for readable members.
pipenv/vendor/distlib/_backport/tarfile.py
def _load(self): """Read through the entire archive file and look for readable members. """ while True: tarinfo = self.next() if tarinfo is None: break self._loaded = True
def _load(self): """Read through the entire archive file and look for readable members. """ while True: tarinfo = self.next() if tarinfo is None: break self._loaded = True
[ "Read", "through", "the", "entire", "archive", "file", "and", "look", "for", "readable", "members", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2486-L2494
[ "def", "_load", "(", "self", ")", ":", "while", "True", ":", "tarinfo", "=", "self", ".", "next", "(", ")", "if", "tarinfo", "is", "None", ":", "break", "self", ".", "_loaded", "=", "True" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._check
Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode.
pipenv/vendor/distlib/_backport/tarfile.py
def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise IOError("%s is closed" % self.__class__.__name__) if mode is not None and self.mode not in mode: raise IOError("bad operation for mode %r" % self.mode)
def _check(self, mode=None): """Check if TarFile is still open, and if the operation's mode corresponds to TarFile's mode. """ if self.closed: raise IOError("%s is closed" % self.__class__.__name__) if mode is not None and self.mode not in mode: raise IOError("bad operation for mode %r" % self.mode)
[ "Check", "if", "TarFile", "is", "still", "open", "and", "if", "the", "operation", "s", "mode", "corresponds", "to", "TarFile", "s", "mode", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2496-L2503
[ "def", "_check", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "self", ".", "closed", ":", "raise", "IOError", "(", "\"%s is closed\"", "%", "self", ".", "__class__", ".", "__name__", ")", "if", "mode", "is", "not", "None", "and", "self", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._find_link_target
Find the target member of a symlink or hardlink member in the archive.
pipenv/vendor/distlib/_backport/tarfile.py
def _find_link_target(self, tarinfo): """Find the target member of a symlink or hardlink member in the archive. """ if tarinfo.issym(): # Always search the entire archive. linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname limit = None else: # Search the archive before the link, because a hard link is # just a reference to an already archived file. linkname = tarinfo.linkname limit = tarinfo member = self._getmember(linkname, tarinfo=limit, normalize=True) if member is None: raise KeyError("linkname %r not found" % linkname) return member
def _find_link_target(self, tarinfo): """Find the target member of a symlink or hardlink member in the archive. """ if tarinfo.issym(): # Always search the entire archive. linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname limit = None else: # Search the archive before the link, because a hard link is # just a reference to an already archived file. linkname = tarinfo.linkname limit = tarinfo member = self._getmember(linkname, tarinfo=limit, normalize=True) if member is None: raise KeyError("linkname %r not found" % linkname) return member
[ "Find", "the", "target", "member", "of", "a", "symlink", "or", "hardlink", "member", "in", "the", "archive", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2505-L2522
[ "def", "_find_link_target", "(", "self", ",", "tarinfo", ")", ":", "if", "tarinfo", ".", "issym", "(", ")", ":", "# Always search the entire archive.", "linkname", "=", "os", ".", "path", ".", "dirname", "(", "tarinfo", ".", "name", ")", "+", "\"/\"", "+",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
TarFile._dbg
Write debugging output to sys.stderr.
pipenv/vendor/distlib/_backport/tarfile.py
def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: print(msg, file=sys.stderr)
def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: print(msg, file=sys.stderr)
[ "Write", "debugging", "output", "to", "sys", ".", "stderr", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2532-L2536
[ "def", "_dbg", "(", "self", ",", "level", ",", "msg", ")", ":", "if", "level", "<=", "self", ".", "debug", ":", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project.path_to
Returns the absolute path to a given relative path.
pipenv/project.py
def path_to(self, p): """Returns the absolute path to a given relative path.""" if os.path.isabs(p): return p return os.sep.join([self._original_dir, p])
def path_to(self, p): """Returns the absolute path to a given relative path.""" if os.path.isabs(p): return p return os.sep.join([self._original_dir, p])
[ "Returns", "the", "absolute", "path", "to", "a", "given", "relative", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L159-L164
[ "def", "path_to", "(", "self", ",", "p", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "p", ")", ":", "return", "p", "return", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "_original_dir", ",", "p", "]", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project._build_package_list
Returns a list of packages for pip-tools to consume.
pipenv/project.py
def _build_package_list(self, package_section): """Returns a list of packages for pip-tools to consume.""" from pipenv.vendor.requirementslib.utils import is_vcs ps = {} # TODO: Separate the logic for showing packages from the filters for supplying pip-tools for k, v in self.parsed_pipfile.get(package_section, {}).items(): # Skip editable VCS deps. if hasattr(v, "keys"): # When a vcs url is gven without editable it only appears as a key # Eliminate any vcs, path, or url entries which are not editable # Since pip-tools can't do deep resolution on them, even setuptools-installable ones if ( is_vcs(v) or is_vcs(k) or (is_installable_file(k) or is_installable_file(v)) or any( ( prefix in v and (os.path.isfile(v[prefix]) or is_valid_url(v[prefix])) ) for prefix in ["path", "file"] ) ): # If they are editable, do resolve them if "editable" not in v: # allow wheels to be passed through if not ( hasattr(v, "keys") and v.get("path", v.get("file", "")).endswith(".whl") ): continue ps.update({k: v}) else: ps.update({k: v}) else: ps.update({k: v}) else: # Since these entries have no attributes we know they are not editable # So we can safely exclude things that need to be editable in order to be resolved # First exclude anything that is a vcs entry either in the key or value if not ( any(is_vcs(i) for i in [k, v]) or # Then exclude any installable files that are not directories # Because pip-tools can resolve setup.py for example any(is_installable_file(i) for i in [k, v]) or # Then exclude any URLs because they need to be editable also # Things that are excluded can only be 'shallow resolved' any(is_valid_url(i) for i in [k, v]) ): ps.update({k: v}) return ps
def _build_package_list(self, package_section): """Returns a list of packages for pip-tools to consume.""" from pipenv.vendor.requirementslib.utils import is_vcs ps = {} # TODO: Separate the logic for showing packages from the filters for supplying pip-tools for k, v in self.parsed_pipfile.get(package_section, {}).items(): # Skip editable VCS deps. if hasattr(v, "keys"): # When a vcs url is gven without editable it only appears as a key # Eliminate any vcs, path, or url entries which are not editable # Since pip-tools can't do deep resolution on them, even setuptools-installable ones if ( is_vcs(v) or is_vcs(k) or (is_installable_file(k) or is_installable_file(v)) or any( ( prefix in v and (os.path.isfile(v[prefix]) or is_valid_url(v[prefix])) ) for prefix in ["path", "file"] ) ): # If they are editable, do resolve them if "editable" not in v: # allow wheels to be passed through if not ( hasattr(v, "keys") and v.get("path", v.get("file", "")).endswith(".whl") ): continue ps.update({k: v}) else: ps.update({k: v}) else: ps.update({k: v}) else: # Since these entries have no attributes we know they are not editable # So we can safely exclude things that need to be editable in order to be resolved # First exclude anything that is a vcs entry either in the key or value if not ( any(is_vcs(i) for i in [k, v]) or # Then exclude any installable files that are not directories # Because pip-tools can resolve setup.py for example any(is_installable_file(i) for i in [k, v]) or # Then exclude any URLs because they need to be editable also # Things that are excluded can only be 'shallow resolved' any(is_valid_url(i) for i in [k, v]) ): ps.update({k: v}) return ps
[ "Returns", "a", "list", "of", "packages", "for", "pip", "-", "tools", "to", "consume", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L166-L219
[ "def", "_build_package_list", "(", "self", ",", "package_section", ")", ":", "from", "pipenv", ".", "vendor", ".", "requirementslib", ".", "utils", "import", "is_vcs", "ps", "=", "{", "}", "# TODO: Separate the logic for showing packages from the filters for supplying pip...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Project._get_virtualenv_hash
Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash)
pipenv/project.py
def _get_virtualenv_hash(self, name): """Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash) """ def get_name(name, location): name = self._sanitize(name) hash = hashlib.sha256(location.encode()).digest()[:6] encoded_hash = base64.urlsafe_b64encode(hash).decode() return name, encoded_hash[:8] clean_name, encoded_hash = get_name(name, self.pipfile_location) venv_name = "{0}-{1}".format(clean_name, encoded_hash) # This should work most of the time for # Case-sensitive filesystems, # In-project venv # "Proper" path casing (on non-case-sensitive filesystems). if ( not fnmatch.fnmatch("A", "a") or self.is_venv_in_project() or get_workon_home().joinpath(venv_name).exists() ): return clean_name, encoded_hash # Check for different capitalization of the same project. for path in get_workon_home().iterdir(): if not is_virtual_environment(path): continue try: env_name, hash_ = path.name.rsplit("-", 1) except ValueError: continue if len(hash_) != 8 or env_name.lower() != name.lower(): continue return get_name(env_name, self.pipfile_location.replace(name, env_name)) # Use the default if no matching env exists. return clean_name, encoded_hash
def _get_virtualenv_hash(self, name): """Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash) """ def get_name(name, location): name = self._sanitize(name) hash = hashlib.sha256(location.encode()).digest()[:6] encoded_hash = base64.urlsafe_b64encode(hash).decode() return name, encoded_hash[:8] clean_name, encoded_hash = get_name(name, self.pipfile_location) venv_name = "{0}-{1}".format(clean_name, encoded_hash) # This should work most of the time for # Case-sensitive filesystems, # In-project venv # "Proper" path casing (on non-case-sensitive filesystems). if ( not fnmatch.fnmatch("A", "a") or self.is_venv_in_project() or get_workon_home().joinpath(venv_name).exists() ): return clean_name, encoded_hash # Check for different capitalization of the same project. for path in get_workon_home().iterdir(): if not is_virtual_environment(path): continue try: env_name, hash_ = path.name.rsplit("-", 1) except ValueError: continue if len(hash_) != 8 or env_name.lower() != name.lower(): continue return get_name(env_name, self.pipfile_location.replace(name, env_name)) # Use the default if no matching env exists. return clean_name, encoded_hash
[ "Get", "the", "name", "of", "the", "virtualenv", "adjusted", "for", "windows", "if", "needed" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L368-L407
[ "def", "_get_virtualenv_hash", "(", "self", ",", "name", ")", ":", "def", "get_name", "(", "name", ",", "location", ")", ":", "name", "=", "self", ".", "_sanitize", "(", "name", ")", "hash", "=", "hashlib", ".", "sha256", "(", "location", ".", "encode"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde