id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,500
pypa/pipenv
pipenv/environment.py
Environment.python
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
python
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", ")", ":", "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
[ "Path", "to", "the", "environment", "python" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L182-L187
25,501
pypa/pipenv
pipenv/environment.py
Environment.sys_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
python
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", ")", ":", "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 :return: The :data:`sys.path` from the environment :rtype: list
[ "The", "system", "path", "inside", "the", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L190-L210
25,502
pypa/pipenv
pipenv/environment.py
Environment.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
python
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", ")", ":", "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 :return: The python prefix inside the environment :rtype: :data:`sys.prefix`
[ "The", "prefix", "run", "inside", "the", "context", "of", "the", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L213-L224
25,503
pypa/pipenv
pipenv/environment.py
Environment.pip_version
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")
python
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", ")", ":", "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.
[ "Get", "the", "pip", "version", "in", "the", "environment", ".", "Useful", "for", "knowing", "which", "args", "we", "can", "use", "when", "installing", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L251-L262
25,504
pypa/pipenv
pipenv/environment.py
Environment.get_distributions
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
python
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", ")", ":", "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 :return: A set of distributions found on the library path :rtype: iterator
[ "Retrives", "the", "distributions", "installed", "on", "the", "library", "path", "of", "the", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L264-L276
25,505
pypa/pipenv
pipenv/environment.py
Environment.find_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
python
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", ")", ":", "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
[ "Find", "an", "egg", "by", "name", "in", "the", "given", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L278-L290
25,506
pypa/pipenv
pipenv/environment.py
Environment.dist_is_in_project
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)
python
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", ")", ":", "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.
[ "Determine", "whether", "the", "supplied", "distribution", "is", "in", "the", "environment", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L300-L311
25,507
pypa/pipenv
pipenv/environment.py
Environment.is_installed
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)
python
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", ")", ":", "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 :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool
[ "Given", "a", "package", "name", "returns", "whether", "it", "is", "installed", "in", "the", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L481-L489
25,508
pypa/pipenv
pipenv/environment.py
Environment.run_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
python
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", ")", ":", "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. :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`
[ "Run", "a", "python", "command", "in", "the", "enviornment", "context", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L507-L524
25,509
pypa/pipenv
pipenv/environment.py
Environment.run_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))
python
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", ")", ":", "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
[ "Runs", "the", "environment", "s", "inline", "activation", "script" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L526-L534
25,510
pypa/pipenv
pipenv/environment.py
Environment.activated
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)
python
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", ")", ":", "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. 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.
[ "Helper", "context", "manager", "to", "activate", "the", "environment", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L537-L605
25,511
pypa/pipenv
pipenv/environment.py
Environment.uninstall
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
python
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", ")", ":", "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 :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)
[ "A", "context", "manager", "which", "allows", "uninstallation", "of", "packages", "from", "the", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L673-L713
25,512
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
stn
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
python
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", ")", ":", "s", "=", "s", ".", "encode", "(", "encoding", ",", "errors", ")", "return", "s", "[", ":", "length", "]", "+", "(", "length", "-", "len", "(", "s", ")", ")", "*", "NUL" ]
Convert a string to a null-terminated bytes object.
[ "Convert", "a", "string", "to", "a", "null", "-", "terminated", "bytes", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L185-L189
25,513
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
nts
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)
python
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", ")", ":", "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.
[ "Convert", "a", "null", "-", "terminated", "bytes", "object", "to", "a", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L191-L197
25,514
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
itn
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
python
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", ")", ":", "# 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.
[ "Convert", "a", "python", "number", "to", "a", "number", "field", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L216-L241
25,515
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
is_tarfile
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
python
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", ")", ":", "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.
[ "Return", "True", "if", "name", "points", "to", "a", "tar", "archive", "that", "we", "are", "able", "to", "handle", "else", "return", "False", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2595-L2604
25,516
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream._init_write_gz
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)
python
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", ")", ":", "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.
[ "Initialize", "for", "writing", "with", "gzip", "compression", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L455-L467
25,517
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.write
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)
python
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", ")", ":", "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.
[ "Write", "string", "s", "to", "the", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L469-L477
25,518
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.__write
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:]
python
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", ")", ":", "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.
[ "Write", "string", "s", "to", "the", "stream", "if", "a", "whole", "new", "block", "is", "ready", "to", "be", "written", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L479-L486
25,519
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.close
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
python
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", ")", ":", "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.
[ "Close", "the", "_Stream", "object", ".", "No", "operation", "should", "be", "done", "on", "it", "afterwards", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L488-L514
25,520
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream._init_read_gz
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)
python
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", ")", ":", "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.
[ "Initialize", "for", "reading", "a", "gzip", "compressed", "fileobj", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L516-L545
25,521
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.seek
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
python
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", ")", ":", "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.
[ "Set", "the", "stream", "s", "file", "pointer", "to", "pos", ".", "Negative", "seeking", "is", "forbidden", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L552-L563
25,522
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.read
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
python
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", ")", ":", "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.
[ "Return", "the", "next", "size", "number", "of", "bytes", "from", "the", "stream", ".", "If", "size", "is", "not", "defined", "return", "all", "bytes", "of", "the", "stream", "up", "to", "EOF", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L565-L581
25,523
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream._read
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
python
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", ")", ":", "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.
[ "Return", "size", "bytes", "from", "the", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L583-L602
25,524
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
_Stream.__read
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
python
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", ")", ":", "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.
[ "Return", "size", "bytes", "from", "stream", ".", "If", "internal", "buffer", "is", "empty", "read", "another", "block", "from", "the", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L604-L617
25,525
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
ExFileObject.read
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
python
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", ")", ":", "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.
[ "Read", "at", "most", "size", "bytes", "from", "the", "file", ".", "If", "size", "is", "not", "present", "or", "None", "read", "all", "data", "until", "EOF", "is", "reached", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L810-L832
25,526
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
ExFileObject.readline
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
python
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", ")", ":", "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.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L837-L864
25,527
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
ExFileObject.seek
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)
python
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", ")", ":", "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.
[ "Seek", "to", "a", "position", "in", "the", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L884-L903
25,528
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.get_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
python
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", ")", ":", "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.
[ "Return", "the", "TarInfo", "s", "attributes", "as", "a", "dictionary", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L978-L1000
25,529
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.tobuf
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")
python
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\"", ")", ":", "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.
[ "Return", "a", "tar", "header", "as", "a", "string", "of", "512", "byte", "blocks", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1002-L1014
25,530
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.create_ustar_header
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)
python
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", ")", ":", "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.
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1016-L1027
25,531
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.create_gnu_header
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)
python
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", ")", ":", "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.
[ "Return", "the", "object", "as", "a", "GNU", "header", "block", "sequence", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1029-L1041
25,532
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.create_pax_header
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")
python
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", ")", ":", "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.
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", ".", "If", "it", "cannot", "be", "represented", "this", "way", "prepend", "a", "pax", "extended", "header", "sequence", "with", "supplement", "information", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1043-L1090
25,533
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._posix_split_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
python
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", ")", ":", "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.
[ "Split", "a", "name", "longer", "than", "100", "chars", "into", "a", "prefix", "and", "a", "name", "part", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1098-L1111
25,534
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._create_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
python
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", ")", ":", "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.
[ "Return", "the", "string", "payload", "filled", "with", "zero", "bytes", "up", "to", "the", "next", "512", "byte", "border", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1142-L1149
25,535
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._create_gnu_long_header
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)
python
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", ")", ":", "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.
[ "Return", "a", "GNUTYPE_LONGNAME", "or", "GNUTYPE_LONGLINK", "sequence", "for", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1152-L1166
25,536
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._create_pax_generic_header
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)
python
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", ")", ":", "# 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.
[ "Return", "a", "POSIX", ".", "1", "-", "2008", "extended", "or", "global", "header", "sequence", "that", "contains", "a", "list", "of", "keyword", "value", "pairs", ".", "The", "values", "must", "be", "strings", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1169-L1217
25,537
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.frombuf
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
python
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", ")", ":", "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.
[ "Construct", "a", "TarInfo", "object", "from", "a", "512", "byte", "bytes", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1220-L1280
25,538
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo.fromtarfile
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)
python
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", ")", ":", "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.
[ "Return", "the", "next", "TarInfo", "object", "from", "TarFile", "object", "tarfile", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1283-L1290
25,539
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_member
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)
python
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", ")", ":", "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.
[ "Choose", "the", "right", "processing", "method", "depending", "on", "the", "type", "and", "call", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1303-L1314
25,540
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_builtin
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
python
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", ")", ":", "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.
[ "Process", "a", "builtin", "type", "or", "an", "unknown", "type", "which", "will", "be", "treated", "as", "a", "regular", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1316-L1331
25,541
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_gnulong
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
python
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", ")", ":", "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.
[ "Process", "the", "blocks", "that", "hold", "a", "GNU", "longname", "or", "longlink", "member", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1333-L1353
25,542
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_sparse
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
python
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", ")", ":", "# 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.
[ "Process", "a", "GNU", "sparse", "header", "plus", "extra", "headers", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1355-L1381
25,543
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_pax
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
python
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", ")", ":", "# 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.
[ "Process", "an", "extended", "or", "global", "header", "as", "described", "in", "POSIX", ".", "1", "-", "2008", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1383-L1483
25,544
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_gnusparse_00
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))
python
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", ")", ":", "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.
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "0", ".", "0", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1485-L1494
25,545
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_gnusparse_01
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]))
python
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", ")", ":", "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.
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "0", ".", "1", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1496-L1500
25,546
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_gnusparse_10
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]))
python
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", ")", ":", "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.
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "1", ".", "0", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1502-L1516
25,547
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._apply_pax_info
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()
python
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", ")", ":", "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.
[ "Replace", "fields", "with", "supplemental", "information", "from", "a", "previous", "pax", "extended", "or", "global", "header", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1518-L1539
25,548
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._decode_pax_field
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)
python
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", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "encoding", ",", "\"strict\"", ")", "except", "UnicodeDecodeError", ":", "return", "value", ".", "decode", "(", "fallback_encoding", ",", "fallback_errors", ")" ]
Decode a single field from a pax record.
[ "Decode", "a", "single", "field", "from", "a", "pax", "record", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1541-L1547
25,549
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.open
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")
python
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", ")", ":", "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. 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
[ "Open", "a", "tar", "archive", "for", "reading", "writing", "or", "appending", ".", "Return", "an", "appropriate", "TarFile", "class", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1714-L1787
25,550
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.taropen
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)
python
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", ")", ":", "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.
[ "Open", "uncompressed", "tar", "archive", "name", "for", "reading", "or", "writing", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1790-L1795
25,551
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.gzopen
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
python
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", ")", ":", "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.
[ "Open", "gzip", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1798-L1826
25,552
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.bz2open
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
python
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", ")", ":", "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.
[ "Open", "bzip2", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1829-L1852
25,553
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.close
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
python
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", ")", ":", "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.
[ "Close", "the", "TarFile", ".", "In", "write", "-", "mode", "two", "finishing", "zero", "blocks", "are", "appended", "to", "the", "archive", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1864-L1882
25,554
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.getmember
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
python
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", ")", ":", "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 last occurrence is assumed to be the most up-to-date version.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1884-L1893
25,555
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.getmembers
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
python
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", ")", ":", "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.
[ "Return", "the", "members", "of", "the", "archive", "as", "a", "list", "of", "TarInfo", "objects", ".", "The", "list", "has", "the", "same", "order", "as", "the", "members", "in", "the", "archive", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1895-L1903
25,556
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.list
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()
python
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", ")", ":", "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 is produced.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2009-L2036
25,557
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._extract_member
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)
python
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", ")", ":", "# 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.
[ "Extract", "the", "TarInfo", "object", "tarinfo", "to", "a", "physical", "file", "called", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2237-L2278
25,558
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.makedir
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
python
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", ")", ":", "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.
[ "Make", "a", "directory", "called", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2285-L2294
25,559
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.makefile
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()
python
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", ")", ":", "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.
[ "Make", "a", "file", "called", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2296-L2310
25,560
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.makeunknown
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)
python
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", ")", ":", "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.
[ "Make", "a", "file", "from", "a", "TarInfo", "object", "with", "an", "unknown", "type", "at", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2312-L2318
25,561
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.makefifo
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")
python
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", ")", ":", "if", "hasattr", "(", "os", ",", "\"mkfifo\"", ")", ":", "os", ".", "mkfifo", "(", "targetpath", ")", "else", ":", "raise", "ExtractError", "(", "\"fifo not supported by system\"", ")" ]
Make a fifo called targetpath.
[ "Make", "a", "fifo", "called", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2320-L2326
25,562
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.makedev
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))
python
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", ")", ":", "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.
[ "Make", "a", "character", "or", "block", "device", "called", "targetpath", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2328-L2341
25,563
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.chown
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")
python
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", ")", ":", "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.
[ "Set", "owner", "of", "targetpath", "according", "to", "tarinfo", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2372-L2392
25,564
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.chmod
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")
python
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", ")", ":", "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.
[ "Set", "file", "permissions", "of", "targetpath", "according", "to", "tarinfo", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2394-L2401
25,565
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.utime
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")
python
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", ")", ":", "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.
[ "Set", "modification", "time", "of", "targetpath", "according", "to", "tarinfo", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2403-L2411
25,566
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile.next
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
python
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", ")", ":", "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.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2414-L2458
25,567
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._getmember
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
python
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", ")", ":", "# 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.
[ "Find", "an", "archive", "member", "by", "name", "from", "bottom", "to", "top", ".", "If", "tarinfo", "is", "given", "it", "is", "used", "as", "the", "starting", "point", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2463-L2484
25,568
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._load
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
python
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", ")", ":", "while", "True", ":", "tarinfo", "=", "self", ".", "next", "(", ")", "if", "tarinfo", "is", "None", ":", "break", "self", ".", "_loaded", "=", "True" ]
Read through the entire archive file and look for readable members.
[ "Read", "through", "the", "entire", "archive", "file", "and", "look", "for", "readable", "members", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2486-L2494
25,569
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._check
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)
python
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", ")", ":", "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.
[ "Check", "if", "TarFile", "is", "still", "open", "and", "if", "the", "operation", "s", "mode", "corresponds", "to", "TarFile", "s", "mode", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2496-L2503
25,570
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._find_link_target
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
python
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", ")", ":", "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.
[ "Find", "the", "target", "member", "of", "a", "symlink", "or", "hardlink", "member", "in", "the", "archive", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2505-L2522
25,571
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarFile._dbg
def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ if level <= self.debug: print(msg, file=sys.stderr)
python
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", ")", ":", "if", "level", "<=", "self", ".", "debug", ":", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")" ]
Write debugging output to sys.stderr.
[ "Write", "debugging", "output", "to", "sys", ".", "stderr", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2532-L2536
25,572
pypa/pipenv
pipenv/project.py
Project.path_to
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])
python
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", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "p", ")", ":", "return", "p", "return", "os", ".", "sep", ".", "join", "(", "[", "self", ".", "_original_dir", ",", "p", "]", ")" ]
Returns the absolute path to a given relative path.
[ "Returns", "the", "absolute", "path", "to", "a", "given", "relative", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L159-L164
25,573
pypa/pipenv
pipenv/project.py
Project._build_package_list
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
python
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", ")", ":", "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.
[ "Returns", "a", "list", "of", "packages", "for", "pip", "-", "tools", "to", "consume", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L166-L219
25,574
pypa/pipenv
pipenv/project.py
Project._get_virtualenv_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
python
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", ")", ":", "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 Returns (name, encoded_hash)
[ "Get", "the", "name", "of", "the", "virtualenv", "adjusted", "for", "windows", "if", "needed" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L368-L407
25,575
pypa/pipenv
pipenv/project.py
Project.register_proper_name
def register_proper_name(self, name): """Registers a proper name to the database.""" with self.proper_names_db_path.open("a") as f: f.write(u"{0}\n".format(name))
python
def register_proper_name(self, name): """Registers a proper name to the database.""" with self.proper_names_db_path.open("a") as f: f.write(u"{0}\n".format(name))
[ "def", "register_proper_name", "(", "self", ",", "name", ")", ":", "with", "self", ".", "proper_names_db_path", ".", "open", "(", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "u\"{0}\\n\"", ".", "format", "(", "name", ")", ")" ]
Registers a proper name to the database.
[ "Registers", "a", "proper", "name", "to", "the", "database", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L462-L465
25,576
pypa/pipenv
pipenv/project.py
Project.parsed_pipfile
def parsed_pipfile(self): """Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)""" contents = self.read_pipfile() # use full contents to get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key not in _pipfile_cache: parsed = self._parse_pipfile(contents) _pipfile_cache[cache_key] = parsed return _pipfile_cache[cache_key]
python
def parsed_pipfile(self): """Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)""" contents = self.read_pipfile() # use full contents to get around str/bytes 2/3 issues cache_key = (self.pipfile_location, contents) if cache_key not in _pipfile_cache: parsed = self._parse_pipfile(contents) _pipfile_cache[cache_key] = parsed return _pipfile_cache[cache_key]
[ "def", "parsed_pipfile", "(", "self", ")", ":", "contents", "=", "self", ".", "read_pipfile", "(", ")", "# use full contents to get around str/bytes 2/3 issues", "cache_key", "=", "(", "self", ".", "pipfile_location", ",", "contents", ")", "if", "cache_key", "not", "in", "_pipfile_cache", ":", "parsed", "=", "self", ".", "_parse_pipfile", "(", "contents", ")", "_pipfile_cache", "[", "cache_key", "]", "=", "parsed", "return", "_pipfile_cache", "[", "cache_key", "]" ]
Parse Pipfile into a TOMLFile and cache it (call clear_pipfile_cache() afterwards if mutating)
[ "Parse", "Pipfile", "into", "a", "TOMLFile", "and", "cache", "it" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L491-L501
25,577
pypa/pipenv
pipenv/project.py
Project._lockfile
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
python
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
[ "def", "_lockfile", "(", "self", ")", ":", "pfile", "=", "pipfile", ".", "load", "(", "self", ".", "pipfile_location", ",", "inject_env", "=", "False", ")", "lockfile", "=", "json", ".", "loads", "(", "pfile", ".", "lock", "(", ")", ")", "for", "section", "in", "(", "\"default\"", ",", "\"develop\"", ")", ":", "lock_section", "=", "lockfile", ".", "get", "(", "section", ",", "{", "}", ")", "for", "key", "in", "list", "(", "lock_section", ".", "keys", "(", ")", ")", ":", "norm_key", "=", "pep423_name", "(", "key", ")", "lockfile", "[", "section", "]", "[", "norm_key", "]", "=", "lock_section", ".", "pop", "(", "key", ")", "return", "lockfile" ]
Pipfile.lock divided by PyPI and external dependencies.
[ "Pipfile", ".", "lock", "divided", "by", "PyPI", "and", "external", "dependencies", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L581-L590
25,578
pypa/pipenv
pipenv/project.py
Project.create_pipfile
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(make_option_group(index_group, config_parser)) install = config_parser.option_groups[0] indexes = ( " ".join(install.get_option("--extra-index-url").default) .lstrip("\n") .split("\n") ) sources = [DEFAULT_SOURCE,] for i, index in enumerate(indexes): if not index: continue source_name = "pip_index_{}".format(i) verify_ssl = index.startswith("https") sources.append( {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name} ) data = { u"source": sources, # Default packages. u"packages": {}, u"dev-packages": {}, } # Default requires. required_python = python if not python: if self.virtualenv_location: required_python = self.which("python", self.virtualenv_location) else: required_python = self.which("python") version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION if version and len(version) >= 3: data[u"requires"] = {"python_version": version[: len("2.7")]} self.write_toml(data)
python
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(make_option_group(index_group, config_parser)) install = config_parser.option_groups[0] indexes = ( " ".join(install.get_option("--extra-index-url").default) .lstrip("\n") .split("\n") ) sources = [DEFAULT_SOURCE,] for i, index in enumerate(indexes): if not index: continue source_name = "pip_index_{}".format(i) verify_ssl = index.startswith("https") sources.append( {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name} ) data = { u"source": sources, # Default packages. u"packages": {}, u"dev-packages": {}, } # Default requires. required_python = python if not python: if self.virtualenv_location: required_python = self.which("python", self.virtualenv_location) else: required_python = self.which("python") version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION if version and len(version) >= 3: data[u"requires"] = {"python_version": version[: len("2.7")]} self.write_toml(data)
[ "def", "create_pipfile", "(", "self", ",", "python", "=", "None", ")", ":", "from", ".", "vendor", ".", "pip_shims", ".", "shims", "import", "(", "ConfigOptionParser", ",", "make_option_group", ",", "index_group", ")", "config_parser", "=", "ConfigOptionParser", "(", "name", "=", "self", ".", "name", ")", "config_parser", ".", "add_option_group", "(", "make_option_group", "(", "index_group", ",", "config_parser", ")", ")", "install", "=", "config_parser", ".", "option_groups", "[", "0", "]", "indexes", "=", "(", "\" \"", ".", "join", "(", "install", ".", "get_option", "(", "\"--extra-index-url\"", ")", ".", "default", ")", ".", "lstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", ")", "sources", "=", "[", "DEFAULT_SOURCE", ",", "]", "for", "i", ",", "index", "in", "enumerate", "(", "indexes", ")", ":", "if", "not", "index", ":", "continue", "source_name", "=", "\"pip_index_{}\"", ".", "format", "(", "i", ")", "verify_ssl", "=", "index", ".", "startswith", "(", "\"https\"", ")", "sources", ".", "append", "(", "{", "u\"url\"", ":", "index", ",", "u\"verify_ssl\"", ":", "verify_ssl", ",", "u\"name\"", ":", "source_name", "}", ")", "data", "=", "{", "u\"source\"", ":", "sources", ",", "# Default packages.", "u\"packages\"", ":", "{", "}", ",", "u\"dev-packages\"", ":", "{", "}", ",", "}", "# Default requires.", "required_python", "=", "python", "if", "not", "python", ":", "if", "self", ".", "virtualenv_location", ":", "required_python", "=", "self", ".", "which", "(", "\"python\"", ",", "self", ".", "virtualenv_location", ")", "else", ":", "required_python", "=", "self", ".", "which", "(", "\"python\"", ")", "version", "=", "python_version", "(", "required_python", ")", "or", "PIPENV_DEFAULT_PYTHON_VERSION", "if", "version", "and", "len", "(", "version", ")", ">=", "3", ":", "data", "[", "u\"requires\"", "]", "=", "{", "\"python_version\"", ":", "version", "[", ":", "len", "(", "\"2.7\"", ")", "]", "}", "self", ".", "write_toml", "(", "data", ")" ]
Creates the Pipfile, filled with juicy defaults.
[ "Creates", "the", "Pipfile", "filled", "with", "juicy", "defaults", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L674-L715
25,579
pypa/pipenv
pipenv/project.py
Project.write_toml
def write_toml(self, data, path=None): """Writes the given data structure out as TOML.""" if path is None: path = self.pipfile_location data = convert_toml_outline_tables(data) try: formatted_data = tomlkit.dumps(data).rstrip() except Exception: document = tomlkit.document() for section in ("packages", "dev-packages"): document[section] = tomlkit.container.Table() # Convert things to inline tables — fancy :) for package in data.get(section, {}): if hasattr(data[section][package], "keys"): table = tomlkit.inline_table() table.update(data[section][package]) document[section][package] = table else: document[section][package] = tomlkit.string(data[section][package]) formatted_data = tomlkit.dumps(document).rstrip() if ( vistir.compat.Path(path).absolute() == vistir.compat.Path(self.pipfile_location).absolute() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
python
def write_toml(self, data, path=None): """Writes the given data structure out as TOML.""" if path is None: path = self.pipfile_location data = convert_toml_outline_tables(data) try: formatted_data = tomlkit.dumps(data).rstrip() except Exception: document = tomlkit.document() for section in ("packages", "dev-packages"): document[section] = tomlkit.container.Table() # Convert things to inline tables — fancy :) for package in data.get(section, {}): if hasattr(data[section][package], "keys"): table = tomlkit.inline_table() table.update(data[section][package]) document[section][package] = table else: document[section][package] = tomlkit.string(data[section][package]) formatted_data = tomlkit.dumps(document).rstrip() if ( vistir.compat.Path(path).absolute() == vistir.compat.Path(self.pipfile_location).absolute() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
[ "def", "write_toml", "(", "self", ",", "data", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "self", ".", "pipfile_location", "data", "=", "convert_toml_outline_tables", "(", "data", ")", "try", ":", "formatted_data", "=", "tomlkit", ".", "dumps", "(", "data", ")", ".", "rstrip", "(", ")", "except", "Exception", ":", "document", "=", "tomlkit", ".", "document", "(", ")", "for", "section", "in", "(", "\"packages\"", ",", "\"dev-packages\"", ")", ":", "document", "[", "section", "]", "=", "tomlkit", ".", "container", ".", "Table", "(", ")", "# Convert things to inline tables — fancy :)", "for", "package", "in", "data", ".", "get", "(", "section", ",", "{", "}", ")", ":", "if", "hasattr", "(", "data", "[", "section", "]", "[", "package", "]", ",", "\"keys\"", ")", ":", "table", "=", "tomlkit", ".", "inline_table", "(", ")", "table", ".", "update", "(", "data", "[", "section", "]", "[", "package", "]", ")", "document", "[", "section", "]", "[", "package", "]", "=", "table", "else", ":", "document", "[", "section", "]", "[", "package", "]", "=", "tomlkit", ".", "string", "(", "data", "[", "section", "]", "[", "package", "]", ")", "formatted_data", "=", "tomlkit", ".", "dumps", "(", "document", ")", ".", "rstrip", "(", ")", "if", "(", "vistir", ".", "compat", ".", "Path", "(", "path", ")", ".", "absolute", "(", ")", "==", "vistir", ".", "compat", ".", "Path", "(", "self", ".", "pipfile_location", ")", ".", "absolute", "(", ")", ")", ":", "newlines", "=", "self", ".", "_pipfile_newlines", "else", ":", "newlines", "=", "DEFAULT_NEWLINES", "formatted_data", "=", "cleanup_toml", "(", "formatted_data", ")", "with", "io", ".", "open", "(", "path", ",", "\"w\"", ",", "newline", "=", "newlines", ")", "as", "f", ":", "f", ".", "write", "(", "formatted_data", ")", "# pipfile is mutated!", "self", ".", "clear_pipfile_cache", "(", ")" ]
Writes the given data structure out as TOML.
[ "Writes", "the", "given", "data", "structure", "out", "as", "TOML", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L783-L815
25,580
pypa/pipenv
pipenv/project.py
Project.write_lockfile
def write_lockfile(self, content): """Write out the lockfile. """ s = self._lockfile_encoder.encode(content) open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"} with vistir.contextmanagers.atomic_open_for_write( self.lockfile_location, **open_kwargs ) as f: f.write(s) # Write newline at end of document. GH-319. # Only need '\n' here; the file object handles the rest. if not s.endswith(u"\n"): f.write(u"\n")
python
def write_lockfile(self, content): """Write out the lockfile. """ s = self._lockfile_encoder.encode(content) open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"} with vistir.contextmanagers.atomic_open_for_write( self.lockfile_location, **open_kwargs ) as f: f.write(s) # Write newline at end of document. GH-319. # Only need '\n' here; the file object handles the rest. if not s.endswith(u"\n"): f.write(u"\n")
[ "def", "write_lockfile", "(", "self", ",", "content", ")", ":", "s", "=", "self", ".", "_lockfile_encoder", ".", "encode", "(", "content", ")", "open_kwargs", "=", "{", "\"newline\"", ":", "self", ".", "_lockfile_newlines", ",", "\"encoding\"", ":", "\"utf-8\"", "}", "with", "vistir", ".", "contextmanagers", ".", "atomic_open_for_write", "(", "self", ".", "lockfile_location", ",", "*", "*", "open_kwargs", ")", "as", "f", ":", "f", ".", "write", "(", "s", ")", "# Write newline at end of document. GH-319.", "# Only need '\\n' here; the file object handles the rest.", "if", "not", "s", ".", "endswith", "(", "u\"\\n\"", ")", ":", "f", ".", "write", "(", "u\"\\n\"", ")" ]
Write out the lockfile.
[ "Write", "out", "the", "lockfile", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L817-L829
25,581
pypa/pipenv
pipenv/project.py
Project.find_source
def find_source(self, source): """ Given a source, find it. source can be a url or an index name. """ if not is_valid_url(source): try: source = self.get_source(name=source) except SourceNotFound: source = self.get_source(url=source) else: source = self.get_source(url=source) return source
python
def find_source(self, source): """ Given a source, find it. source can be a url or an index name. """ if not is_valid_url(source): try: source = self.get_source(name=source) except SourceNotFound: source = self.get_source(url=source) else: source = self.get_source(url=source) return source
[ "def", "find_source", "(", "self", ",", "source", ")", ":", "if", "not", "is_valid_url", "(", "source", ")", ":", "try", ":", "source", "=", "self", ".", "get_source", "(", "name", "=", "source", ")", "except", "SourceNotFound", ":", "source", "=", "self", ".", "get_source", "(", "url", "=", "source", ")", "else", ":", "source", "=", "self", ".", "get_source", "(", "url", "=", "source", ")", "return", "source" ]
Given a source, find it. source can be a url or an index name.
[ "Given", "a", "source", "find", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L854-L867
25,582
pypa/pipenv
pipenv/project.py
Project.get_package_name_in_pipfile
def get_package_name_in_pipfile(self, package_name, dev=False): """Get the equivalent package name in pipfile""" key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): if pep423_name(name) == package_name: return name return None
python
def get_package_name_in_pipfile(self, package_name, dev=False): """Get the equivalent package name in pipfile""" key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): if pep423_name(name) == package_name: return name return None
[ "def", "get_package_name_in_pipfile", "(", "self", ",", "package_name", ",", "dev", "=", "False", ")", ":", "key", "=", "\"dev-packages\"", "if", "dev", "else", "\"packages\"", "section", "=", "self", ".", "parsed_pipfile", ".", "get", "(", "key", ",", "{", "}", ")", "package_name", "=", "pep423_name", "(", "package_name", ")", "for", "name", "in", "section", ".", "keys", "(", ")", ":", "if", "pep423_name", "(", "name", ")", "==", "package_name", ":", "return", "name", "return", "None" ]
Get the equivalent package name in pipfile
[ "Get", "the", "equivalent", "package", "name", "in", "pipfile" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L898-L906
25,583
pypa/pipenv
pipenv/project.py
Project.add_index_to_pipfile
def add_index_to_pipfile(self, index, verify_ssl=True): """Adds a given index to the Pipfile.""" # Read and append Pipfile. p = self.parsed_pipfile try: self.get_source(url=index) except SourceNotFound: source = {"url": index, "verify_ssl": verify_ssl} else: return source["name"] = self.src_name_from_url(index) # Add the package to the group. if "source" not in p: p["source"] = [source] else: p["source"].append(source) # Write Pipfile. self.write_toml(p)
python
def add_index_to_pipfile(self, index, verify_ssl=True): """Adds a given index to the Pipfile.""" # Read and append Pipfile. p = self.parsed_pipfile try: self.get_source(url=index) except SourceNotFound: source = {"url": index, "verify_ssl": verify_ssl} else: return source["name"] = self.src_name_from_url(index) # Add the package to the group. if "source" not in p: p["source"] = [source] else: p["source"].append(source) # Write Pipfile. self.write_toml(p)
[ "def", "add_index_to_pipfile", "(", "self", ",", "index", ",", "verify_ssl", "=", "True", ")", ":", "# Read and append Pipfile.", "p", "=", "self", ".", "parsed_pipfile", "try", ":", "self", ".", "get_source", "(", "url", "=", "index", ")", "except", "SourceNotFound", ":", "source", "=", "{", "\"url\"", ":", "index", ",", "\"verify_ssl\"", ":", "verify_ssl", "}", "else", ":", "return", "source", "[", "\"name\"", "]", "=", "self", ".", "src_name_from_url", "(", "index", ")", "# Add the package to the group.", "if", "\"source\"", "not", "in", "p", ":", "p", "[", "\"source\"", "]", "=", "[", "source", "]", "else", ":", "p", "[", "\"source\"", "]", ".", "append", "(", "source", ")", "# Write Pipfile.", "self", ".", "write_toml", "(", "p", ")" ]
Adds a given index to the Pipfile.
[ "Adds", "a", "given", "index", "to", "the", "Pipfile", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L969-L986
25,584
pypa/pipenv
pipenv/project.py
Project.ensure_proper_casing
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
python
def ensure_proper_casing(self): """Ensures proper casing of Pipfile packages""" pfile = self.parsed_pipfile casing_changed = self.proper_case_section(pfile.get("packages", {})) casing_changed |= self.proper_case_section(pfile.get("dev-packages", {})) return casing_changed
[ "def", "ensure_proper_casing", "(", "self", ")", ":", "pfile", "=", "self", ".", "parsed_pipfile", "casing_changed", "=", "self", ".", "proper_case_section", "(", "pfile", ".", "get", "(", "\"packages\"", ",", "{", "}", ")", ")", "casing_changed", "|=", "self", ".", "proper_case_section", "(", "pfile", ".", "get", "(", "\"dev-packages\"", ",", "{", "}", ")", ")", "return", "casing_changed" ]
Ensures proper casing of Pipfile packages
[ "Ensures", "proper", "casing", "of", "Pipfile", "packages" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1028-L1033
25,585
pypa/pipenv
pipenv/project.py
Project.proper_case_section
def proper_case_section(self, section): """Verify proper casing is retrieved, when available, for each dependency in the section. """ # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Replace each package with proper casing. for dep in unknown_names: try: # Get new casing for package name. new_casing = proper_case(dep) except IOError: # Unable to normalize package name. continue if new_casing != dep: changed_values = True self.register_proper_name(new_casing) # Replace old value with new value. old_value = section[dep] section[new_casing] = old_value del section[dep] # Return whether or not values have been changed. return changed_values
python
def proper_case_section(self, section): """Verify proper casing is retrieved, when available, for each dependency in the section. """ # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Replace each package with proper casing. for dep in unknown_names: try: # Get new casing for package name. new_casing = proper_case(dep) except IOError: # Unable to normalize package name. continue if new_casing != dep: changed_values = True self.register_proper_name(new_casing) # Replace old value with new value. old_value = section[dep] section[new_casing] = old_value del section[dep] # Return whether or not values have been changed. return changed_values
[ "def", "proper_case_section", "(", "self", ",", "section", ")", ":", "# Casing for section.", "changed_values", "=", "False", "unknown_names", "=", "[", "k", "for", "k", "in", "section", ".", "keys", "(", ")", "if", "k", "not", "in", "set", "(", "self", ".", "proper_names", ")", "]", "# Replace each package with proper casing.", "for", "dep", "in", "unknown_names", ":", "try", ":", "# Get new casing for package name.", "new_casing", "=", "proper_case", "(", "dep", ")", "except", "IOError", ":", "# Unable to normalize package name.", "continue", "if", "new_casing", "!=", "dep", ":", "changed_values", "=", "True", "self", ".", "register_proper_name", "(", "new_casing", ")", "# Replace old value with new value.", "old_value", "=", "section", "[", "dep", "]", "section", "[", "new_casing", "]", "=", "old_value", "del", "section", "[", "dep", "]", "# Return whether or not values have been changed.", "return", "changed_values" ]
Verify proper casing is retrieved, when available, for each dependency in the section.
[ "Verify", "proper", "casing", "is", "retrieved", "when", "available", "for", "each", "dependency", "in", "the", "section", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L1035-L1059
25,586
pypa/pipenv
pipenv/vendor/orderedmultidict/orderedmultidict.py
omdict.reverse
def reverse(self): """ Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>. """ for key in six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
python
def reverse(self): """ Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>. """ for key in six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
[ "def", "reverse", "(", "self", ")", ":", "for", "key", "in", "six", ".", "iterkeys", "(", "self", ".", "_map", ")", ":", "self", ".", "_map", "[", "key", "]", ".", "reverse", "(", ")", "self", ".", "_items", ".", "reverse", "(", ")", "return", "self" ]
Reverse the order of all items in the dictionary. Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.reverse() omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)] Returns: <self>.
[ "Reverse", "the", "order", "of", "all", "items", "in", "the", "dictionary", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/orderedmultidict/orderedmultidict.py#L746-L760
25,587
pypa/pipenv
pipenv/vendor/click/parser.py
_unpack_args
def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args)
python
def _unpack_args(args, nargs_spec): """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`. """ args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return None while nargs_spec: nargs = _fetch(nargs_spec) if nargs == 1: rv.append(_fetch(args)) elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError('Cannot have two nargs < 0') spos = len(rv) rv.append(None) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1:] = reversed(rv[spos + 1:]) return tuple(rv), list(args)
[ "def", "_unpack_args", "(", "args", ",", "nargs_spec", ")", ":", "args", "=", "deque", "(", "args", ")", "nargs_spec", "=", "deque", "(", "nargs_spec", ")", "rv", "=", "[", "]", "spos", "=", "None", "def", "_fetch", "(", "c", ")", ":", "try", ":", "if", "spos", "is", "None", ":", "return", "c", ".", "popleft", "(", ")", "else", ":", "return", "c", ".", "pop", "(", ")", "except", "IndexError", ":", "return", "None", "while", "nargs_spec", ":", "nargs", "=", "_fetch", "(", "nargs_spec", ")", "if", "nargs", "==", "1", ":", "rv", ".", "append", "(", "_fetch", "(", "args", ")", ")", "elif", "nargs", ">", "1", ":", "x", "=", "[", "_fetch", "(", "args", ")", "for", "_", "in", "range", "(", "nargs", ")", "]", "# If we're reversed, we're pulling in the arguments in reverse,", "# so we need to turn them around.", "if", "spos", "is", "not", "None", ":", "x", ".", "reverse", "(", ")", "rv", ".", "append", "(", "tuple", "(", "x", ")", ")", "elif", "nargs", "<", "0", ":", "if", "spos", "is", "not", "None", ":", "raise", "TypeError", "(", "'Cannot have two nargs < 0'", ")", "spos", "=", "len", "(", "rv", ")", "rv", ".", "append", "(", "None", ")", "# spos is the position of the wildcard (star). If it's not `None`,", "# we fill it with the remainder.", "if", "spos", "is", "not", "None", ":", "rv", "[", "spos", "]", "=", "tuple", "(", "args", ")", "args", "=", "[", "]", "rv", "[", "spos", "+", "1", ":", "]", "=", "reversed", "(", "rv", "[", "spos", "+", "1", ":", "]", ")", "return", "tuple", "(", "rv", ")", ",", "list", "(", "args", ")" ]
Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with `None`.
[ "Given", "an", "iterable", "of", "arguments", "and", "an", "iterable", "of", "nargs", "specifications", "it", "returns", "a", "tuple", "with", "all", "the", "unpacked", "arguments", "at", "the", "first", "index", "and", "all", "remaining", "arguments", "as", "the", "second", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L25-L73
25,588
pypa/pipenv
pipenv/vendor/click/parser.py
split_arg_string
def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv
python
def split_arg_string(string): """Given an argument string this attempts to split it into small parts.""" rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[:1] == arg[-1:] and arg[:1] in '"\'': arg = arg[1:-1].encode('ascii', 'backslashreplace') \ .decode('unicode-escape') try: arg = type(string)(arg) except UnicodeError: pass rv.append(arg) return rv
[ "def", "split_arg_string", "(", "string", ")", ":", "rv", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "r\"('([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\"", "r'|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"'", "r'|\\S+)\\s*'", ",", "string", ",", "re", ".", "S", ")", ":", "arg", "=", "match", ".", "group", "(", ")", ".", "strip", "(", ")", "if", "arg", "[", ":", "1", "]", "==", "arg", "[", "-", "1", ":", "]", "and", "arg", "[", ":", "1", "]", "in", "'\"\\''", ":", "arg", "=", "arg", "[", "1", ":", "-", "1", "]", ".", "encode", "(", "'ascii'", ",", "'backslashreplace'", ")", ".", "decode", "(", "'unicode-escape'", ")", "try", ":", "arg", "=", "type", "(", "string", ")", "(", "arg", ")", "except", "UnicodeError", ":", "pass", "rv", ".", "append", "(", "arg", ")", "return", "rv" ]
Given an argument string this attempts to split it into small parts.
[ "Given", "an", "argument", "string", "this", "attempts", "to", "split", "it", "into", "small", "parts", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L98-L113
25,589
pypa/pipenv
pipenv/vendor/click/parser.py
OptionParser.add_argument
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
python
def add_argument(self, dest, nargs=1, obj=None): """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
[ "def", "add_argument", "(", "self", ",", "dest", ",", "nargs", "=", "1", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "obj", "=", "dest", "self", ".", "_args", ".", "append", "(", "Argument", "(", "dest", "=", "dest", ",", "nargs", "=", "nargs", ",", "obj", "=", "obj", ")", ")" ]
Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser.
[ "Adds", "a", "positional", "argument", "named", "dest", "to", "the", "parser", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/parser.py#L249-L257
25,590
pypa/pipenv
pipenv/vendor/distlib/database.py
make_graph
def make_graph(dists, scheme='default'): """Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance """ scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_distribution(dist) for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) provided.setdefault(name, []).append((version, dist)) # now make the edges for dist in dists: requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires) for req in requires: try: matcher = scheme.matcher(req) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive matched = False if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: graph.add_edge(dist, provider, req) matched = True break if not matched: graph.add_missing(dist, req) return graph
python
def make_graph(dists, scheme='default'): """Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance """ scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_distribution(dist) for p in dist.provides: name, version = parse_name_and_version(p) logger.debug('Add to provided: %s, %s, %s', name, version, dist) provided.setdefault(name, []).append((version, dist)) # now make the edges for dist in dists: requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires) for req in requires: try: matcher = scheme.matcher(req) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive matched = False if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: graph.add_edge(dist, provider, req) matched = True break if not matched: graph.add_missing(dist, req) return graph
[ "def", "make_graph", "(", "dists", ",", "scheme", "=", "'default'", ")", ":", "scheme", "=", "get_scheme", "(", "scheme", ")", "graph", "=", "DependencyGraph", "(", ")", "provided", "=", "{", "}", "# maps names to lists of (version, dist) tuples", "# first, build the graph and find out what's provided", "for", "dist", "in", "dists", ":", "graph", ".", "add_distribution", "(", "dist", ")", "for", "p", "in", "dist", ".", "provides", ":", "name", ",", "version", "=", "parse_name_and_version", "(", "p", ")", "logger", ".", "debug", "(", "'Add to provided: %s, %s, %s'", ",", "name", ",", "version", ",", "dist", ")", "provided", ".", "setdefault", "(", "name", ",", "[", "]", ")", ".", "append", "(", "(", "version", ",", "dist", ")", ")", "# now make the edges", "for", "dist", "in", "dists", ":", "requires", "=", "(", "dist", ".", "run_requires", "|", "dist", ".", "meta_requires", "|", "dist", ".", "build_requires", "|", "dist", ".", "dev_requires", ")", "for", "req", "in", "requires", ":", "try", ":", "matcher", "=", "scheme", ".", "matcher", "(", "req", ")", "except", "UnsupportedVersionError", ":", "# XXX compat-mode if cannot read the version", "logger", ".", "warning", "(", "'could not read version %r - using name only'", ",", "req", ")", "name", "=", "req", ".", "split", "(", ")", "[", "0", "]", "matcher", "=", "scheme", ".", "matcher", "(", "name", ")", "name", "=", "matcher", ".", "key", "# case-insensitive", "matched", "=", "False", "if", "name", "in", "provided", ":", "for", "version", ",", "provider", "in", "provided", "[", "name", "]", ":", "try", ":", "match", "=", "matcher", ".", "match", "(", "version", ")", "except", "UnsupportedVersionError", ":", "match", "=", "False", "if", "match", ":", "graph", ".", "add_edge", "(", "dist", ",", "provider", ",", "req", ")", "matched", "=", "True", "break", "if", "not", "matched", ":", "graph", ".", "add_missing", "(", "dist", ",", "req", ")", "return", "graph" ]
Makes a dependency graph from the given distributions. :parameter dists: a list of distributions :type dists: list of :class:`distutils2.database.InstalledDistribution` and :class:`distutils2.database.EggInfoDistribution` instances :rtype: a :class:`DependencyGraph` instance
[ "Makes", "a", "dependency", "graph", "from", "the", "given", "distributions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1225-L1276
25,591
pypa/pipenv
pipenv/vendor/distlib/database.py
make_dist
def make_dist(name, version, **kwargs): """ A convenience method for making a dist given just a name and version. """ summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' return Distribution(md)
python
def make_dist(name, version, **kwargs): """ A convenience method for making a dist given just a name and version. """ summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' return Distribution(md)
[ "def", "make_dist", "(", "name", ",", "version", ",", "*", "*", "kwargs", ")", ":", "summary", "=", "kwargs", ".", "pop", "(", "'summary'", ",", "'Placeholder for summary'", ")", "md", "=", "Metadata", "(", "*", "*", "kwargs", ")", "md", ".", "name", "=", "name", "md", ".", "version", "=", "version", "md", ".", "summary", "=", "summary", "or", "'Placeholder for summary'", "return", "Distribution", "(", "md", ")" ]
A convenience method for making a dist given just a name and version.
[ "A", "convenience", "method", "for", "making", "a", "dist", "given", "just", "a", "name", "and", "version", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1330-L1339
25,592
pypa/pipenv
pipenv/vendor/distlib/database.py
_Cache.clear
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
python
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
[ "def", "clear", "(", "self", ")", ":", "self", ".", "name", ".", "clear", "(", ")", "self", ".", "path", ".", "clear", "(", ")", "self", ".", "generated", "=", "False" ]
Clear the cache, setting it to its initial state.
[ "Clear", "the", "cache", "setting", "it", "to", "its", "initial", "state", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L57-L63
25,593
pypa/pipenv
pipenv/vendor/distlib/database.py
DistributionPath._generate_cache
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in self._yield_distributions(): if isinstance(dist, InstalledDistribution): self._cache.add(dist) else: self._cache_egg.add(dist) if gen_dist: self._cache.generated = True if gen_egg: self._cache_egg.generated = True
python
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in self._yield_distributions(): if isinstance(dist, InstalledDistribution): self._cache.add(dist) else: self._cache_egg.add(dist) if gen_dist: self._cache.generated = True if gen_egg: self._cache_egg.generated = True
[ "def", "_generate_cache", "(", "self", ")", ":", "gen_dist", "=", "not", "self", ".", "_cache", ".", "generated", "gen_egg", "=", "self", ".", "_include_egg", "and", "not", "self", ".", "_cache_egg", ".", "generated", "if", "gen_dist", "or", "gen_egg", ":", "for", "dist", "in", "self", ".", "_yield_distributions", "(", ")", ":", "if", "isinstance", "(", "dist", ",", "InstalledDistribution", ")", ":", "self", ".", "_cache", ".", "add", "(", "dist", ")", "else", ":", "self", ".", "_cache_egg", ".", "add", "(", "dist", ")", "if", "gen_dist", ":", "self", ".", "_cache", ".", "generated", "=", "True", "if", "gen_egg", ":", "self", ".", "_cache_egg", ".", "generated", "=", "True" ]
Scan the path for distributions and populate the cache with those that are found.
[ "Scan", "the", "path", "for", "distributions", "and", "populate", "the", "cache", "with", "those", "that", "are", "found", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L159-L176
25,594
pypa/pipenv
pipenv/vendor/distlib/database.py
DistributionPath.get_distribution
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
python
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
[ "def", "get_distribution", "(", "self", ",", "name", ")", ":", "result", "=", "None", "name", "=", "name", ".", "lower", "(", ")", "if", "not", "self", ".", "_cache_enabled", ":", "for", "dist", "in", "self", ".", "_yield_distributions", "(", ")", ":", "if", "dist", ".", "key", "==", "name", ":", "result", "=", "dist", "break", "else", ":", "self", ".", "_generate_cache", "(", ")", "if", "name", "in", "self", ".", "_cache", ".", "name", ":", "result", "=", "self", ".", "_cache", ".", "name", "[", "name", "]", "[", "0", "]", "elif", "self", ".", "_include_egg", "and", "name", "in", "self", ".", "_cache_egg", ".", "name", ":", "result", "=", "self", ".", "_cache_egg", ".", "name", "[", "name", "]", "[", "0", "]", "return", "result" ]
Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None``
[ "Looks", "for", "a", "named", "distribution", "on", "the", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L222-L246
25,595
pypa/pipenv
pipenv/vendor/distlib/database.py
DistributionPath.get_file_path
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
python
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
[ "def", "get_file_path", "(", "self", ",", "name", ",", "relative_path", ")", ":", "dist", "=", "self", ".", "get_distribution", "(", "name", ")", "if", "dist", "is", "None", ":", "raise", "LookupError", "(", "'no distribution named %r found'", "%", "name", ")", "return", "dist", ".", "get_resource_path", "(", "relative_path", ")" ]
Return the path to a resource file.
[ "Return", "the", "path", "to", "a", "resource", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L289-L296
25,596
pypa/pipenv
pipenv/vendor/distlib/database.py
DistributionPath.get_exported_entries
def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned. """ for dist in self.get_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: yield d[name] else: for v in d.values(): yield v
python
def get_exported_entries(self, category, name=None): """ Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned. """ for dist in self.get_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: yield d[name] else: for v in d.values(): yield v
[ "def", "get_exported_entries", "(", "self", ",", "category", ",", "name", "=", "None", ")", ":", "for", "dist", "in", "self", ".", "get_distributions", "(", ")", ":", "r", "=", "dist", ".", "exports", "if", "category", "in", "r", ":", "d", "=", "r", "[", "category", "]", "if", "name", "is", "not", "None", ":", "if", "name", "in", "d", ":", "yield", "d", "[", "name", "]", "else", ":", "for", "v", "in", "d", ".", "values", "(", ")", ":", "yield", "v" ]
Return all of the exported entries in a particular category. :param category: The category to search for entries. :param name: If specified, only entries with that name are returned.
[ "Return", "all", "of", "the", "exported", "entries", "in", "a", "particular", "category", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L298-L314
25,597
pypa/pipenv
pipenv/vendor/distlib/database.py
BaseInstalledDistribution.get_hash
def get_hash(self, data, hasher=None): """ Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str """ if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(data).digest() digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii') return '%s%s' % (prefix, digest)
python
def get_hash(self, data, hasher=None): """ Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str """ if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(data).digest() digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii') return '%s%s' % (prefix, digest)
[ "def", "get_hash", "(", "self", ",", "data", ",", "hasher", "=", "None", ")", ":", "if", "hasher", "is", "None", ":", "hasher", "=", "self", ".", "hasher", "if", "hasher", "is", "None", ":", "hasher", "=", "hashlib", ".", "md5", "prefix", "=", "''", "else", ":", "hasher", "=", "getattr", "(", "hashlib", ",", "hasher", ")", "prefix", "=", "'%s='", "%", "self", ".", "hasher", "digest", "=", "hasher", "(", "data", ")", ".", "digest", "(", ")", "digest", "=", "base64", ".", "urlsafe_b64encode", "(", "digest", ")", ".", "rstrip", "(", "b'='", ")", ".", "decode", "(", "'ascii'", ")", "return", "'%s%s'", "%", "(", "prefix", ",", "digest", ")" ]
Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``, ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and ``'sha512'``. If no hasher is specified, the ``hasher`` attribute of the :class:`InstalledDistribution` instance is used. If the hasher is determined to be ``None``, MD5 is used as the hashing algorithm. :returns: The hash of the data. If a hasher was explicitly specified, the returned hash will be prefixed with the specified hasher followed by '='. :rtype: str
[ "Get", "the", "hash", "of", "some", "data", "using", "a", "particular", "hash", "algorithm", "if", "specified", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L497-L526
25,598
pypa/pipenv
pipenv/vendor/distlib/database.py
InstalledDistribution.read_exports
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
python
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
[ "def", "read_exports", "(", "self", ")", ":", "result", "=", "{", "}", "r", "=", "self", ".", "get_distinfo_resource", "(", "EXPORTS_FILENAME", ")", "if", "r", ":", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "result", "=", "read_exports", "(", "stream", ")", "return", "result" ]
Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
[ "Read", "exports", "data", "from", "a", "file", "in", ".", "ini", "format", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L617-L630
25,599
pypa/pipenv
pipenv/vendor/distlib/database.py
InstalledDistribution.write_installed_files
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
python
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
[ "def", "write_installed_files", "(", "self", ",", "paths", ",", "prefix", ",", "dry_run", "=", "False", ")", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "''", ")", "base", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "base_under_prefix", "=", "base", ".", "startswith", "(", "prefix", ")", "base", "=", "os", ".", "path", ".", "join", "(", "base", ",", "''", ")", "record_path", "=", "self", ".", "get_distinfo_file", "(", "'RECORD'", ")", "logger", ".", "info", "(", "'creating %s'", ",", "record_path", ")", "if", "dry_run", ":", "return", "None", "with", "CSVWriter", "(", "record_path", ")", "as", "writer", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "or", "path", ".", "endswith", "(", "(", "'.pyc'", ",", "'.pyo'", ")", ")", ":", "# do not put size and hash, as in PEP-376", "hash_value", "=", "size", "=", "''", "else", ":", "size", "=", "'%d'", "%", "os", ".", "path", ".", "getsize", "(", "path", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "fp", ":", "hash_value", "=", "self", ".", "get_hash", "(", "fp", ".", "read", "(", ")", ")", "if", "path", ".", "startswith", "(", "base", ")", "or", "(", "base_under_prefix", "and", "path", ".", "startswith", "(", "prefix", ")", ")", ":", "path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "base", ")", "writer", ".", "writerow", "(", "(", "path", ",", "hash_value", ",", "size", ")", ")", "# add the RECORD file itself", "if", "record_path", ".", "startswith", "(", "base", ")", ":", "record_path", "=", "os", ".", "path", ".", "relpath", "(", "record_path", ",", "base", ")", "writer", ".", "writerow", "(", "(", "record_path", ",", "''", ",", "''", ")", ")", "return", "record_path" ]
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths.
[ "Writes", "the", "RECORD", "file", "using", "the", "paths", "iterable", "passed", "in", ".", "Any", "existing", "RECORD", "file", "is", "silently", "overwritten", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L673-L706