repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
pypa/pipenv
pipenv/patched/notpip/_internal/req/__init__.py
install_given_reqs
def install_given_reqs( to_install, # type: List[InstallRequirement] install_options, # type: List[str] global_options=(), # type: Sequence[str] *args, **kwargs ): # type: (...) -> List[InstallRequirement] """ Install everything in the given list. (to be called after having downloaded and unpacked the packages) """ if to_install: logger.info( 'Installing collected packages: %s', ', '.join([req.name for req in to_install]), ) with indent_log(): for requirement in to_install: if requirement.conflicts_with: logger.info( 'Found existing installation: %s', requirement.conflicts_with, ) with indent_log(): uninstalled_pathset = requirement.uninstall( auto_confirm=True ) try: requirement.install( install_options, global_options, *args, **kwargs ) except Exception: should_rollback = ( requirement.conflicts_with and not requirement.install_succeeded ) # if install did not succeed, rollback previous uninstall if should_rollback: uninstalled_pathset.rollback() raise else: should_commit = ( requirement.conflicts_with and requirement.install_succeeded ) if should_commit: uninstalled_pathset.commit() requirement.remove_temporary_source() return to_install
python
def install_given_reqs( to_install, # type: List[InstallRequirement] install_options, # type: List[str] global_options=(), # type: Sequence[str] *args, **kwargs ): # type: (...) -> List[InstallRequirement] """ Install everything in the given list. (to be called after having downloaded and unpacked the packages) """ if to_install: logger.info( 'Installing collected packages: %s', ', '.join([req.name for req in to_install]), ) with indent_log(): for requirement in to_install: if requirement.conflicts_with: logger.info( 'Found existing installation: %s', requirement.conflicts_with, ) with indent_log(): uninstalled_pathset = requirement.uninstall( auto_confirm=True ) try: requirement.install( install_options, global_options, *args, **kwargs ) except Exception: should_rollback = ( requirement.conflicts_with and not requirement.install_succeeded ) # if install did not succeed, rollback previous uninstall if should_rollback: uninstalled_pathset.rollback() raise else: should_commit = ( requirement.conflicts_with and requirement.install_succeeded ) if should_commit: uninstalled_pathset.commit() requirement.remove_temporary_source() return to_install
[ "def", "install_given_reqs", "(", "to_install", ",", "# type: List[InstallRequirement]", "install_options", ",", "# type: List[str]", "global_options", "=", "(", ")", ",", "# type: Sequence[str]", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (...) -> List[InstallRequirement]", "if", "to_install", ":", "logger", ".", "info", "(", "'Installing collected packages: %s'", ",", "', '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "to_install", "]", ")", ",", ")", "with", "indent_log", "(", ")", ":", "for", "requirement", "in", "to_install", ":", "if", "requirement", ".", "conflicts_with", ":", "logger", ".", "info", "(", "'Found existing installation: %s'", ",", "requirement", ".", "conflicts_with", ",", ")", "with", "indent_log", "(", ")", ":", "uninstalled_pathset", "=", "requirement", ".", "uninstall", "(", "auto_confirm", "=", "True", ")", "try", ":", "requirement", ".", "install", "(", "install_options", ",", "global_options", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "should_rollback", "=", "(", "requirement", ".", "conflicts_with", "and", "not", "requirement", ".", "install_succeeded", ")", "# if install did not succeed, rollback previous uninstall", "if", "should_rollback", ":", "uninstalled_pathset", ".", "rollback", "(", ")", "raise", "else", ":", "should_commit", "=", "(", "requirement", ".", "conflicts_with", "and", "requirement", ".", "install_succeeded", ")", "if", "should_commit", ":", "uninstalled_pathset", ".", "commit", "(", ")", "requirement", ".", "remove_temporary_source", "(", ")", "return", "to_install" ]
Install everything in the given list. (to be called after having downloaded and unpacked the packages)
[ "Install", "everything", "in", "the", "given", "list", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/__init__.py#L22-L77
train
pypa/pipenv
pipenv/vendor/yaspin/termcolor.py
cprint
def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ print((colored(text, color, on_color, attrs)), **kwargs)
python
def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ print((colored(text, color, on_color, attrs)), **kwargs)
[ "def", "cprint", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "print", "(", "(", "colored", "(", "text", ",", "color", ",", "on_color", ",", "attrs", ")", ")", ",", "*", "*", "kwargs", ")" ]
Print colorize text. It accepts arguments of print function.
[ "Print", "colorize", "text", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/termcolor.py#L118-L124
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
get_provider
def get_provider(moduleOrReq): """Return an IResourceProvider for the named module or requirement""" if isinstance(moduleOrReq, Requirement): return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] try: module = sys.modules[moduleOrReq] except KeyError: __import__(moduleOrReq) module = sys.modules[moduleOrReq] loader = getattr(module, '__loader__', None) return _find_adapter(_provider_factories, loader)(module)
python
def get_provider(moduleOrReq): """Return an IResourceProvider for the named module or requirement""" if isinstance(moduleOrReq, Requirement): return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] try: module = sys.modules[moduleOrReq] except KeyError: __import__(moduleOrReq) module = sys.modules[moduleOrReq] loader = getattr(module, '__loader__', None) return _find_adapter(_provider_factories, loader)(module)
[ "def", "get_provider", "(", "moduleOrReq", ")", ":", "if", "isinstance", "(", "moduleOrReq", ",", "Requirement", ")", ":", "return", "working_set", ".", "find", "(", "moduleOrReq", ")", "or", "require", "(", "str", "(", "moduleOrReq", ")", ")", "[", "0", "]", "try", ":", "module", "=", "sys", ".", "modules", "[", "moduleOrReq", "]", "except", "KeyError", ":", "__import__", "(", "moduleOrReq", ")", "module", "=", "sys", ".", "modules", "[", "moduleOrReq", "]", "loader", "=", "getattr", "(", "module", ",", "'__loader__'", ",", "None", ")", "return", "_find_adapter", "(", "_provider_factories", ",", "loader", ")", "(", "module", ")" ]
Return an IResourceProvider for the named module or requirement
[ "Return", "an", "IResourceProvider", "for", "the", "named", "module", "or", "requirement" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L352-L362
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
get_build_platform
def get_build_platform(): """Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X. """ from sysconfig import get_platform plat = get_platform() if sys.platform == "darwin" and not plat.startswith('macosx-'): try: version = _macosx_vers() machine = os.uname()[4].replace(" ", "_") return "macosx-%d.%d-%s" % ( int(version[0]), int(version[1]), _macosx_arch(machine), ) except ValueError: # if someone is running a non-Mac darwin system, this will fall # through to the default implementation pass return plat
python
def get_build_platform(): """Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X. """ from sysconfig import get_platform plat = get_platform() if sys.platform == "darwin" and not plat.startswith('macosx-'): try: version = _macosx_vers() machine = os.uname()[4].replace(" ", "_") return "macosx-%d.%d-%s" % ( int(version[0]), int(version[1]), _macosx_arch(machine), ) except ValueError: # if someone is running a non-Mac darwin system, this will fall # through to the default implementation pass return plat
[ "def", "get_build_platform", "(", ")", ":", "from", "sysconfig", "import", "get_platform", "plat", "=", "get_platform", "(", ")", "if", "sys", ".", "platform", "==", "\"darwin\"", "and", "not", "plat", ".", "startswith", "(", "'macosx-'", ")", ":", "try", ":", "version", "=", "_macosx_vers", "(", ")", "machine", "=", "os", ".", "uname", "(", ")", "[", "4", "]", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "return", "\"macosx-%d.%d-%s\"", "%", "(", "int", "(", "version", "[", "0", "]", ")", ",", "int", "(", "version", "[", "1", "]", ")", ",", "_macosx_arch", "(", "machine", ")", ",", ")", "except", "ValueError", ":", "# if someone is running a non-Mac darwin system, this will fall", "# through to the default implementation", "pass", "return", "plat" ]
Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X.
[ "Return", "this", "platform", "s", "string", "for", "platform", "-", "specific", "distributions" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L385-L406
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
compatible_platforms
def compatible_platforms(provided, required): """Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes. """ if provided is None or required is None or provided == required: # easy case return True # Mac OS X special cases reqMac = macosVersionString.match(required) if reqMac: provMac = macosVersionString.match(provided) # is this a Mac package? if not provMac: # this is backwards compatibility for packages built before # setuptools 0.6. All packages built after this point will # use the new macosx designation. provDarwin = darwinVersionString.match(provided) if provDarwin: dversion = int(provDarwin.group(1)) macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2)) if dversion == 7 and macosversion >= "10.3" or \ dversion == 8 and macosversion >= "10.4": return True # egg isn't macosx or legacy darwin return False # are they the same major version and machine type? if provMac.group(1) != reqMac.group(1) or \ provMac.group(3) != reqMac.group(3): return False # is the required OS major update >= the provided one? if int(provMac.group(2)) > int(reqMac.group(2)): return False return True # XXX Linux and other platforms' special cases should go here return False
python
def compatible_platforms(provided, required): """Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes. """ if provided is None or required is None or provided == required: # easy case return True # Mac OS X special cases reqMac = macosVersionString.match(required) if reqMac: provMac = macosVersionString.match(provided) # is this a Mac package? if not provMac: # this is backwards compatibility for packages built before # setuptools 0.6. All packages built after this point will # use the new macosx designation. provDarwin = darwinVersionString.match(provided) if provDarwin: dversion = int(provDarwin.group(1)) macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2)) if dversion == 7 and macosversion >= "10.3" or \ dversion == 8 and macosversion >= "10.4": return True # egg isn't macosx or legacy darwin return False # are they the same major version and machine type? if provMac.group(1) != reqMac.group(1) or \ provMac.group(3) != reqMac.group(3): return False # is the required OS major update >= the provided one? if int(provMac.group(2)) > int(reqMac.group(2)): return False return True # XXX Linux and other platforms' special cases should go here return False
[ "def", "compatible_platforms", "(", "provided", ",", "required", ")", ":", "if", "provided", "is", "None", "or", "required", "is", "None", "or", "provided", "==", "required", ":", "# easy case", "return", "True", "# Mac OS X special cases", "reqMac", "=", "macosVersionString", ".", "match", "(", "required", ")", "if", "reqMac", ":", "provMac", "=", "macosVersionString", ".", "match", "(", "provided", ")", "# is this a Mac package?", "if", "not", "provMac", ":", "# this is backwards compatibility for packages built before", "# setuptools 0.6. All packages built after this point will", "# use the new macosx designation.", "provDarwin", "=", "darwinVersionString", ".", "match", "(", "provided", ")", "if", "provDarwin", ":", "dversion", "=", "int", "(", "provDarwin", ".", "group", "(", "1", ")", ")", "macosversion", "=", "\"%s.%s\"", "%", "(", "reqMac", ".", "group", "(", "1", ")", ",", "reqMac", ".", "group", "(", "2", ")", ")", "if", "dversion", "==", "7", "and", "macosversion", ">=", "\"10.3\"", "or", "dversion", "==", "8", "and", "macosversion", ">=", "\"10.4\"", ":", "return", "True", "# egg isn't macosx or legacy darwin", "return", "False", "# are they the same major version and machine type?", "if", "provMac", ".", "group", "(", "1", ")", "!=", "reqMac", ".", "group", "(", "1", ")", "or", "provMac", ".", "group", "(", "3", ")", "!=", "reqMac", ".", "group", "(", "3", ")", ":", "return", "False", "# is the required OS major update >= the provided one?", "if", "int", "(", "provMac", ".", "group", "(", "2", ")", ")", ">", "int", "(", "reqMac", ".", "group", "(", "2", ")", ")", ":", "return", "False", "return", "True", "# XXX Linux and other platforms' special cases should go here", "return", "False" ]
Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes.
[ "Can", "code", "for", "the", "provided", "platform", "run", "on", "the", "required", "platform?" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L415-L458
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
run_script
def run_script(dist_spec, script_name): """Locate distribution `dist_spec` and run its `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
python
def run_script(dist_spec, script_name): """Locate distribution `dist_spec` and run its `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "dist_spec", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "name", "require", "(", "dist_spec", ")", "[", "0", "]", ".", "run_script", "(", "script_name", ",", "ns", ")" ]
Locate distribution `dist_spec` and run its `script_name` script
[ "Locate", "distribution", "dist_spec", "and", "run", "its", "script_name", "script" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L461-L467
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
get_distribution
def get_distribution(dist): """Return a current distribution object for a Requirement or string""" if isinstance(dist, six.string_types): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) if not isinstance(dist, Distribution): raise TypeError("Expected string, Requirement, or Distribution", dist) return dist
python
def get_distribution(dist): """Return a current distribution object for a Requirement or string""" if isinstance(dist, six.string_types): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) if not isinstance(dist, Distribution): raise TypeError("Expected string, Requirement, or Distribution", dist) return dist
[ "def", "get_distribution", "(", "dist", ")", ":", "if", "isinstance", "(", "dist", ",", "six", ".", "string_types", ")", ":", "dist", "=", "Requirement", ".", "parse", "(", "dist", ")", "if", "isinstance", "(", "dist", ",", "Requirement", ")", ":", "dist", "=", "get_provider", "(", "dist", ")", "if", "not", "isinstance", "(", "dist", ",", "Distribution", ")", ":", "raise", "TypeError", "(", "\"Expected string, Requirement, or Distribution\"", ",", "dist", ")", "return", "dist" ]
Return a current distribution object for a Requirement or string
[ "Return", "a", "current", "distribution", "object", "for", "a", "Requirement", "or", "string" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L474-L482
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
safe_version
def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
python
def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "try", ":", "# normalize the version", "return", "str", "(", "packaging", ".", "version", ".", "Version", "(", "version", ")", ")", "except", "packaging", ".", "version", ".", "InvalidVersion", ":", "version", "=", "version", ".", "replace", "(", "' '", ",", "'.'", ")", "return", "re", ".", "sub", "(", "'[^A-Za-z0-9.]+'", ",", "'-'", ",", "version", ")" ]
Convert an arbitrary string to a standard version string
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1323-L1332
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
invalid_marker
def invalid_marker(text): """ Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise. """ try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False
python
def invalid_marker(text): """ Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise. """ try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False
[ "def", "invalid_marker", "(", "text", ")", ":", "try", ":", "evaluate_marker", "(", "text", ")", "except", "SyntaxError", "as", "e", ":", "e", ".", "filename", "=", "None", "e", ".", "lineno", "=", "None", "return", "e", "return", "False" ]
Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise.
[ "Validate", "text", "as", "a", "PEP", "508", "environment", "marker", ";", "return", "an", "exception", "if", "invalid", "or", "False", "otherwise", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1352-L1363
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
evaluate_marker
def evaluate_marker(text, extra=None): """ Evaluate a PEP 508 environment marker. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'pyparsing' module. """ try: marker = packaging.markers.Marker(text) return marker.evaluate() except packaging.markers.InvalidMarker as e: raise SyntaxError(e)
python
def evaluate_marker(text, extra=None): """ Evaluate a PEP 508 environment marker. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'pyparsing' module. """ try: marker = packaging.markers.Marker(text) return marker.evaluate() except packaging.markers.InvalidMarker as e: raise SyntaxError(e)
[ "def", "evaluate_marker", "(", "text", ",", "extra", "=", "None", ")", ":", "try", ":", "marker", "=", "packaging", ".", "markers", ".", "Marker", "(", "text", ")", "return", "marker", ".", "evaluate", "(", ")", "except", "packaging", ".", "markers", ".", "InvalidMarker", "as", "e", ":", "raise", "SyntaxError", "(", "e", ")" ]
Evaluate a PEP 508 environment marker. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'pyparsing' module.
[ "Evaluate", "a", "PEP", "508", "environment", "marker", ".", "Return", "a", "boolean", "indicating", "the", "marker", "result", "in", "this", "environment", ".", "Raise", "SyntaxError", "if", "marker", "is", "invalid", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1366-L1378
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
find_distributions
def find_distributions(path_item, only=False): """Yield distributions accessible via `path_item`""" importer = get_importer(path_item) finder = _find_adapter(_distribution_finders, importer) return finder(importer, path_item, only)
python
def find_distributions(path_item, only=False): """Yield distributions accessible via `path_item`""" importer = get_importer(path_item) finder = _find_adapter(_distribution_finders, importer) return finder(importer, path_item, only)
[ "def", "find_distributions", "(", "path_item", ",", "only", "=", "False", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "finder", "=", "_find_adapter", "(", "_distribution_finders", ",", "importer", ")", "return", "finder", "(", "importer", ",", "path_item", ",", "only", ")" ]
Yield distributions accessible via `path_item`
[ "Yield", "distributions", "accessible", "via", "path_item" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1870-L1874
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
find_eggs_in_zip
def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only: # don't yield nested distros return for subitem in metadata.resource_listdir('/'): if _is_egg_path(subitem): subpath = os.path.join(path_item, subitem) dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) for dist in dists: yield dist elif subitem.lower().endswith('.dist-info'): subpath = os.path.join(path_item, subitem) submeta = EggMetadata(zipimport.zipimporter(subpath)) submeta.egg_info = subpath yield Distribution.from_location(path_item, subitem, submeta)
python
def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only: # don't yield nested distros return for subitem in metadata.resource_listdir('/'): if _is_egg_path(subitem): subpath = os.path.join(path_item, subitem) dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) for dist in dists: yield dist elif subitem.lower().endswith('.dist-info'): subpath = os.path.join(path_item, subitem) submeta = EggMetadata(zipimport.zipimporter(subpath)) submeta.egg_info = subpath yield Distribution.from_location(path_item, subitem, submeta)
[ "def", "find_eggs_in_zip", "(", "importer", ",", "path_item", ",", "only", "=", "False", ")", ":", "if", "importer", ".", "archive", ".", "endswith", "(", "'.whl'", ")", ":", "# wheels are not supported with this finder", "# they don't have PKG-INFO metadata, and won't ever contain eggs", "return", "metadata", "=", "EggMetadata", "(", "importer", ")", "if", "metadata", ".", "has_metadata", "(", "'PKG-INFO'", ")", ":", "yield", "Distribution", ".", "from_filename", "(", "path_item", ",", "metadata", "=", "metadata", ")", "if", "only", ":", "# don't yield nested distros", "return", "for", "subitem", "in", "metadata", ".", "resource_listdir", "(", "'/'", ")", ":", "if", "_is_egg_path", "(", "subitem", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "subitem", ")", "dists", "=", "find_eggs_in_zip", "(", "zipimport", ".", "zipimporter", "(", "subpath", ")", ",", "subpath", ")", "for", "dist", "in", "dists", ":", "yield", "dist", "elif", "subitem", ".", "lower", "(", ")", ".", "endswith", "(", "'.dist-info'", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "subitem", ")", "submeta", "=", "EggMetadata", "(", "zipimport", ".", "zipimporter", "(", "subpath", ")", ")", "submeta", ".", "egg_info", "=", "subpath", "yield", "Distribution", ".", "from_location", "(", "path_item", ",", "subitem", ",", "submeta", ")" ]
Find eggs in zip files; possibly multiple nested eggs.
[ "Find", "eggs", "in", "zip", "files", ";", "possibly", "multiple", "nested", "eggs", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1877-L1901
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_by_version_descending
def _by_version_descending(names): """ Given a list of filenames, return them in descending order by version number. >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg' >>> _by_version_descending(names) ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg'] """ def _by_version(name): """ Parse each component of the filename """ name, ext = os.path.splitext(name) parts = itertools.chain(name.split('-'), [ext]) return [packaging.version.parse(part) for part in parts] return sorted(names, key=_by_version, reverse=True)
python
def _by_version_descending(names): """ Given a list of filenames, return them in descending order by version number. >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg' >>> _by_version_descending(names) ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg'] """ def _by_version(name): """ Parse each component of the filename """ name, ext = os.path.splitext(name) parts = itertools.chain(name.split('-'), [ext]) return [packaging.version.parse(part) for part in parts] return sorted(names, key=_by_version, reverse=True)
[ "def", "_by_version_descending", "(", "names", ")", ":", "def", "_by_version", "(", "name", ")", ":", "\"\"\"\n Parse each component of the filename\n \"\"\"", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "parts", "=", "itertools", ".", "chain", "(", "name", ".", "split", "(", "'-'", ")", ",", "[", "ext", "]", ")", "return", "[", "packaging", ".", "version", ".", "parse", "(", "part", ")", "for", "part", "in", "parts", "]", "return", "sorted", "(", "names", ",", "key", "=", "_by_version", ",", "reverse", "=", "True", ")" ]
Given a list of filenames, return them in descending order by version number. >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg' >>> _by_version_descending(names) ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
[ "Given", "a", "list", "of", "filenames", "return", "them", "in", "descending", "order", "by", "version", "number", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1914-L1937
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
find_on_path
def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item, 'EGG-INFO') ) ) return entries = safe_listdir(path_item) # for performance, before sorting by version, # screen entries for only those that will yield # distributions filtered = ( entry for entry in entries if dist_factory(path_item, entry, only) ) # scan for .egg and .egg-info in directory path_item_entries = _by_version_descending(filtered) for entry in path_item_entries: fullpath = os.path.join(path_item, entry) factory = dist_factory(path_item, entry, only) for dist in factory(fullpath): yield dist
python
def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item, 'EGG-INFO') ) ) return entries = safe_listdir(path_item) # for performance, before sorting by version, # screen entries for only those that will yield # distributions filtered = ( entry for entry in entries if dist_factory(path_item, entry, only) ) # scan for .egg and .egg-info in directory path_item_entries = _by_version_descending(filtered) for entry in path_item_entries: fullpath = os.path.join(path_item, entry) factory = dist_factory(path_item, entry, only) for dist in factory(fullpath): yield dist
[ "def", "find_on_path", "(", "importer", ",", "path_item", ",", "only", "=", "False", ")", ":", "path_item", "=", "_normalize_cached", "(", "path_item", ")", "if", "_is_unpacked_egg", "(", "path_item", ")", ":", "yield", "Distribution", ".", "from_filename", "(", "path_item", ",", "metadata", "=", "PathMetadata", "(", "path_item", ",", "os", ".", "path", ".", "join", "(", "path_item", ",", "'EGG-INFO'", ")", ")", ")", "return", "entries", "=", "safe_listdir", "(", "path_item", ")", "# for performance, before sorting by version,", "# screen entries for only those that will yield", "# distributions", "filtered", "=", "(", "entry", "for", "entry", "in", "entries", "if", "dist_factory", "(", "path_item", ",", "entry", ",", "only", ")", ")", "# scan for .egg and .egg-info in directory", "path_item_entries", "=", "_by_version_descending", "(", "filtered", ")", "for", "entry", "in", "path_item_entries", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "entry", ")", "factory", "=", "dist_factory", "(", "path_item", ",", "entry", ",", "only", ")", "for", "dist", "in", "factory", "(", "fullpath", ")", ":", "yield", "dist" ]
Yield distributions accessible on a sys.path directory
[ "Yield", "distributions", "accessible", "on", "a", "sys", ".", "path", "directory" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1940-L1969
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
dist_factory
def dist_factory(path_item, entry, only): """ Return a dist_factory for a path_item and entry """ lower = entry.lower() is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info'))) return ( distributions_from_metadata if is_meta else find_distributions if not only and _is_egg_path(entry) else resolve_egg_link if not only and lower.endswith('.egg-link') else NoDists() )
python
def dist_factory(path_item, entry, only): """ Return a dist_factory for a path_item and entry """ lower = entry.lower() is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info'))) return ( distributions_from_metadata if is_meta else find_distributions if not only and _is_egg_path(entry) else resolve_egg_link if not only and lower.endswith('.egg-link') else NoDists() )
[ "def", "dist_factory", "(", "path_item", ",", "entry", ",", "only", ")", ":", "lower", "=", "entry", ".", "lower", "(", ")", "is_meta", "=", "any", "(", "map", "(", "lower", ".", "endswith", ",", "(", "'.egg-info'", ",", "'.dist-info'", ")", ")", ")", "return", "(", "distributions_from_metadata", "if", "is_meta", "else", "find_distributions", "if", "not", "only", "and", "_is_egg_path", "(", "entry", ")", "else", "resolve_egg_link", "if", "not", "only", "and", "lower", ".", "endswith", "(", "'.egg-link'", ")", "else", "NoDists", "(", ")", ")" ]
Return a dist_factory for a path_item and entry
[ "Return", "a", "dist_factory", "for", "a", "path_item", "and", "entry" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1972-L1986
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
safe_listdir
def safe_listdir(path): """ Attempt to list contents of path, but suppress some exceptions. """ try: return os.listdir(path) except (PermissionError, NotADirectoryError): pass except OSError as e: # Ignore the directory if does not exist, not a directory or # permission denied ignorable = ( e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT) # Python 2 on Windows needs to be handled this way :( or getattr(e, "winerror", None) == 267 ) if not ignorable: raise return ()
python
def safe_listdir(path): """ Attempt to list contents of path, but suppress some exceptions. """ try: return os.listdir(path) except (PermissionError, NotADirectoryError): pass except OSError as e: # Ignore the directory if does not exist, not a directory or # permission denied ignorable = ( e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT) # Python 2 on Windows needs to be handled this way :( or getattr(e, "winerror", None) == 267 ) if not ignorable: raise return ()
[ "def", "safe_listdir", "(", "path", ")", ":", "try", ":", "return", "os", ".", "listdir", "(", "path", ")", "except", "(", "PermissionError", ",", "NotADirectoryError", ")", ":", "pass", "except", "OSError", "as", "e", ":", "# Ignore the directory if does not exist, not a directory or", "# permission denied", "ignorable", "=", "(", "e", ".", "errno", "in", "(", "errno", ".", "ENOTDIR", ",", "errno", ".", "EACCES", ",", "errno", ".", "ENOENT", ")", "# Python 2 on Windows needs to be handled this way :(", "or", "getattr", "(", "e", ",", "\"winerror\"", ",", "None", ")", "==", "267", ")", "if", "not", "ignorable", ":", "raise", "return", "(", ")" ]
Attempt to list contents of path, but suppress some exceptions.
[ "Attempt", "to", "list", "contents", "of", "path", "but", "suppress", "some", "exceptions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2006-L2024
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
non_empty_lines
def non_empty_lines(path): """ Yield non-empty lines from file at path """ with open(path) as f: for line in f: line = line.strip() if line: yield line
python
def non_empty_lines(path): """ Yield non-empty lines from file at path """ with open(path) as f: for line in f: line = line.strip() if line: yield line
[ "def", "non_empty_lines", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "yield", "line" ]
Yield non-empty lines from file at path
[ "Yield", "non", "-", "empty", "lines", "from", "file", "at", "path" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2042-L2050
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
resolve_egg_link
def resolve_egg_link(path): """ Given a path to an .egg-link, resolve distributions present in the referenced path. """ referenced_paths = non_empty_lines(path) resolved_paths = ( os.path.join(os.path.dirname(path), ref) for ref in referenced_paths ) dist_groups = map(find_distributions, resolved_paths) return next(dist_groups, ())
python
def resolve_egg_link(path): """ Given a path to an .egg-link, resolve distributions present in the referenced path. """ referenced_paths = non_empty_lines(path) resolved_paths = ( os.path.join(os.path.dirname(path), ref) for ref in referenced_paths ) dist_groups = map(find_distributions, resolved_paths) return next(dist_groups, ())
[ "def", "resolve_egg_link", "(", "path", ")", ":", "referenced_paths", "=", "non_empty_lines", "(", "path", ")", "resolved_paths", "=", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "ref", ")", "for", "ref", "in", "referenced_paths", ")", "dist_groups", "=", "map", "(", "find_distributions", ",", "resolved_paths", ")", "return", "next", "(", "dist_groups", ",", "(", ")", ")" ]
Given a path to an .egg-link, resolve distributions present in the referenced path.
[ "Given", "a", "path", "to", "an", ".", "egg", "-", "link", "resolve", "distributions", "present", "in", "the", "referenced", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2053-L2064
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_handle_ns
def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None # capture warnings due to #1111 with warnings.catch_warnings(): warnings.simplefilter("ignore") loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = types.ModuleType(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module, '__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) _rebuild_mod_path(path, packageName, module) return subpath
python
def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None # capture warnings due to #1111 with warnings.catch_warnings(): warnings.simplefilter("ignore") loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = types.ModuleType(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module, '__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) _rebuild_mod_path(path, packageName, module) return subpath
[ "def", "_handle_ns", "(", "packageName", ",", "path_item", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "if", "importer", "is", "None", ":", "return", "None", "# capture warnings due to #1111", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "loader", "=", "importer", ".", "find_module", "(", "packageName", ")", "if", "loader", "is", "None", ":", "return", "None", "module", "=", "sys", ".", "modules", ".", "get", "(", "packageName", ")", "if", "module", "is", "None", ":", "module", "=", "sys", ".", "modules", "[", "packageName", "]", "=", "types", ".", "ModuleType", "(", "packageName", ")", "module", ".", "__path__", "=", "[", "]", "_set_parent_ns", "(", "packageName", ")", "elif", "not", "hasattr", "(", "module", ",", "'__path__'", ")", ":", "raise", "TypeError", "(", "\"Not a package:\"", ",", "packageName", ")", "handler", "=", "_find_adapter", "(", "_namespace_handlers", ",", "importer", ")", "subpath", "=", "handler", "(", "importer", ",", "path_item", ",", "packageName", ",", "module", ")", "if", "subpath", "is", "not", "None", ":", "path", "=", "module", ".", "__path__", "path", ".", "append", "(", "subpath", ")", "loader", ".", "load_module", "(", "packageName", ")", "_rebuild_mod_path", "(", "path", ",", "packageName", ",", "module", ")", "return", "subpath" ]
Ensure that named package includes a subpath of path_item (if needed)
[ "Ensure", "that", "named", "package", "includes", "a", "subpath", "of", "path_item", "(", "if", "needed", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2094-L2122
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_rebuild_mod_path
def _rebuild_mod_path(orig_path, package_name, module): """ Rebuild module.__path__ ensuring that all entries are ordered corresponding to their sys.path order """ sys_path = [_normalize_cached(p) for p in sys.path] def safe_sys_path_index(entry): """ Workaround for #520 and #513. """ try: return sys_path.index(entry) except ValueError: return float('inf') def position_in_sys_path(path): """ Return the ordinal of the path based on its position in sys.path """ path_parts = path.split(os.sep) module_parts = package_name.count('.') + 1 parts = path_parts[:-module_parts] return safe_sys_path_index(_normalize_cached(os.sep.join(parts))) new_path = sorted(orig_path, key=position_in_sys_path) new_path = [_normalize_cached(p) for p in new_path] if isinstance(module.__path__, list): module.__path__[:] = new_path else: module.__path__ = new_path
python
def _rebuild_mod_path(orig_path, package_name, module): """ Rebuild module.__path__ ensuring that all entries are ordered corresponding to their sys.path order """ sys_path = [_normalize_cached(p) for p in sys.path] def safe_sys_path_index(entry): """ Workaround for #520 and #513. """ try: return sys_path.index(entry) except ValueError: return float('inf') def position_in_sys_path(path): """ Return the ordinal of the path based on its position in sys.path """ path_parts = path.split(os.sep) module_parts = package_name.count('.') + 1 parts = path_parts[:-module_parts] return safe_sys_path_index(_normalize_cached(os.sep.join(parts))) new_path = sorted(orig_path, key=position_in_sys_path) new_path = [_normalize_cached(p) for p in new_path] if isinstance(module.__path__, list): module.__path__[:] = new_path else: module.__path__ = new_path
[ "def", "_rebuild_mod_path", "(", "orig_path", ",", "package_name", ",", "module", ")", ":", "sys_path", "=", "[", "_normalize_cached", "(", "p", ")", "for", "p", "in", "sys", ".", "path", "]", "def", "safe_sys_path_index", "(", "entry", ")", ":", "\"\"\"\n Workaround for #520 and #513.\n \"\"\"", "try", ":", "return", "sys_path", ".", "index", "(", "entry", ")", "except", "ValueError", ":", "return", "float", "(", "'inf'", ")", "def", "position_in_sys_path", "(", "path", ")", ":", "\"\"\"\n Return the ordinal of the path based on its position in sys.path\n \"\"\"", "path_parts", "=", "path", ".", "split", "(", "os", ".", "sep", ")", "module_parts", "=", "package_name", ".", "count", "(", "'.'", ")", "+", "1", "parts", "=", "path_parts", "[", ":", "-", "module_parts", "]", "return", "safe_sys_path_index", "(", "_normalize_cached", "(", "os", ".", "sep", ".", "join", "(", "parts", ")", ")", ")", "new_path", "=", "sorted", "(", "orig_path", ",", "key", "=", "position_in_sys_path", ")", "new_path", "=", "[", "_normalize_cached", "(", "p", ")", "for", "p", "in", "new_path", "]", "if", "isinstance", "(", "module", ".", "__path__", ",", "list", ")", ":", "module", ".", "__path__", "[", ":", "]", "=", "new_path", "else", ":", "module", ".", "__path__", "=", "new_path" ]
Rebuild module.__path__ ensuring that all entries are ordered corresponding to their sys.path order
[ "Rebuild", "module", ".", "__path__", "ensuring", "that", "all", "entries", "are", "ordered", "corresponding", "to", "their", "sys", ".", "path", "order" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2125-L2156
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
declare_namespace
def declare_namespace(packageName): """Declare that package 'packageName' is a namespace package""" _imp.acquire_lock() try: if packageName in _namespace_packages: return path = sys.path parent, _, _ = packageName.rpartition('.') if parent: declare_namespace(parent) if parent not in _namespace_packages: __import__(parent) try: path = sys.modules[parent].__path__ except AttributeError: raise TypeError("Not a package:", parent) # Track what packages are namespaces, so when new path items are added, # they can be updated _namespace_packages.setdefault(parent or None, []).append(packageName) _namespace_packages.setdefault(packageName, []) for path_item in path: # Ensure all the parent's path items are reflected in the child, # if they apply _handle_ns(packageName, path_item) finally: _imp.release_lock()
python
def declare_namespace(packageName): """Declare that package 'packageName' is a namespace package""" _imp.acquire_lock() try: if packageName in _namespace_packages: return path = sys.path parent, _, _ = packageName.rpartition('.') if parent: declare_namespace(parent) if parent not in _namespace_packages: __import__(parent) try: path = sys.modules[parent].__path__ except AttributeError: raise TypeError("Not a package:", parent) # Track what packages are namespaces, so when new path items are added, # they can be updated _namespace_packages.setdefault(parent or None, []).append(packageName) _namespace_packages.setdefault(packageName, []) for path_item in path: # Ensure all the parent's path items are reflected in the child, # if they apply _handle_ns(packageName, path_item) finally: _imp.release_lock()
[ "def", "declare_namespace", "(", "packageName", ")", ":", "_imp", ".", "acquire_lock", "(", ")", "try", ":", "if", "packageName", "in", "_namespace_packages", ":", "return", "path", "=", "sys", ".", "path", "parent", ",", "_", ",", "_", "=", "packageName", ".", "rpartition", "(", "'.'", ")", "if", "parent", ":", "declare_namespace", "(", "parent", ")", "if", "parent", "not", "in", "_namespace_packages", ":", "__import__", "(", "parent", ")", "try", ":", "path", "=", "sys", ".", "modules", "[", "parent", "]", ".", "__path__", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Not a package:\"", ",", "parent", ")", "# Track what packages are namespaces, so when new path items are added,", "# they can be updated", "_namespace_packages", ".", "setdefault", "(", "parent", "or", "None", ",", "[", "]", ")", ".", "append", "(", "packageName", ")", "_namespace_packages", ".", "setdefault", "(", "packageName", ",", "[", "]", ")", "for", "path_item", "in", "path", ":", "# Ensure all the parent's path items are reflected in the child,", "# if they apply", "_handle_ns", "(", "packageName", ",", "path_item", ")", "finally", ":", "_imp", ".", "release_lock", "(", ")" ]
Declare that package 'packageName' is a namespace package
[ "Declare", "that", "package", "packageName", "is", "a", "namespace", "package" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2159-L2190
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
fixup_namespace_packages
def fixup_namespace_packages(path_item, parent=None): """Ensure that previously-declared namespace packages include path_item""" _imp.acquire_lock() try: for package in _namespace_packages.get(parent, ()): subpath = _handle_ns(package, path_item) if subpath: fixup_namespace_packages(subpath, package) finally: _imp.release_lock()
python
def fixup_namespace_packages(path_item, parent=None): """Ensure that previously-declared namespace packages include path_item""" _imp.acquire_lock() try: for package in _namespace_packages.get(parent, ()): subpath = _handle_ns(package, path_item) if subpath: fixup_namespace_packages(subpath, package) finally: _imp.release_lock()
[ "def", "fixup_namespace_packages", "(", "path_item", ",", "parent", "=", "None", ")", ":", "_imp", ".", "acquire_lock", "(", ")", "try", ":", "for", "package", "in", "_namespace_packages", ".", "get", "(", "parent", ",", "(", ")", ")", ":", "subpath", "=", "_handle_ns", "(", "package", ",", "path_item", ")", "if", "subpath", ":", "fixup_namespace_packages", "(", "subpath", ",", "package", ")", "finally", ":", "_imp", ".", "release_lock", "(", ")" ]
Ensure that previously-declared namespace packages include path_item
[ "Ensure", "that", "previously", "-", "declared", "namespace", "packages", "include", "path_item" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2193-L2202
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
file_ns_handler
def file_ns_handler(importer, path_item, packageName, module): """Compute an ns-package subpath for a filesystem or zipfile importer""" subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: break else: # Only return the path if it's not already there return subpath
python
def file_ns_handler(importer, path_item, packageName, module): """Compute an ns-package subpath for a filesystem or zipfile importer""" subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: break else: # Only return the path if it's not already there return subpath
[ "def", "file_ns_handler", "(", "importer", ",", "path_item", ",", "packageName", ",", "module", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "packageName", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "normalized", "=", "_normalize_cached", "(", "subpath", ")", "for", "item", "in", "module", ".", "__path__", ":", "if", "_normalize_cached", "(", "item", ")", "==", "normalized", ":", "break", "else", ":", "# Only return the path if it's not already there", "return", "subpath" ]
Compute an ns-package subpath for a filesystem or zipfile importer
[ "Compute", "an", "ns", "-", "package", "subpath", "for", "a", "filesystem", "or", "zipfile", "importer" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2205-L2215
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
normalize_path
def normalize_path(filename): """Normalize a file/dir name for comparison purposes""" return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
python
def normalize_path(filename): """Normalize a file/dir name for comparison purposes""" return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
[ "def", "normalize_path", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "normpath", "(", "_cygwin_patch", "(", "filename", ")", ")", ")", ")" ]
Normalize a file/dir name for comparison purposes
[ "Normalize", "a", "file", "/", "dir", "name", "for", "comparison", "purposes" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2232-L2234
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_is_unpacked_egg
def _is_unpacked_egg(path): """ Determine if given path appears to be an unpacked egg. """ return ( _is_egg_path(path) and os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO')) )
python
def _is_unpacked_egg(path): """ Determine if given path appears to be an unpacked egg. """ return ( _is_egg_path(path) and os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO')) )
[ "def", "_is_unpacked_egg", "(", "path", ")", ":", "return", "(", "_is_egg_path", "(", "path", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'EGG-INFO'", ",", "'PKG-INFO'", ")", ")", ")" ]
Determine if given path appears to be an unpacked egg.
[ "Determine", "if", "given", "path", "appears", "to", "be", "an", "unpacked", "egg", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2263-L2270
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_version_from_file
def _version_from_file(lines): """ Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise. """ def is_version_line(line): return line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(value.strip()) or None
python
def _version_from_file(lines): """ Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise. """ def is_version_line(line): return line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(value.strip()) or None
[ "def", "_version_from_file", "(", "lines", ")", ":", "def", "is_version_line", "(", "line", ")", ":", "return", "line", ".", "lower", "(", ")", ".", "startswith", "(", "'version:'", ")", "version_lines", "=", "filter", "(", "is_version_line", ",", "lines", ")", "line", "=", "next", "(", "iter", "(", "version_lines", ")", ",", "''", ")", "_", ",", "_", ",", "value", "=", "line", ".", "partition", "(", "':'", ")", "return", "safe_version", "(", "value", ".", "strip", "(", ")", ")", "or", "None" ]
Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise.
[ "Given", "an", "iterable", "of", "lines", "from", "a", "Metadata", "file", "return", "the", "value", "of", "the", "Version", "field", "if", "present", "or", "None", "otherwise", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2451-L2461
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
parse_requirements
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) for line in lines: # Drop comments -- a hash without a space may be in a URL. if ' #' in line: line = line[:line.find(' #')] # If there is a line continuation, drop it, and append the next line. if line.endswith('\\'): line = line[:-2].strip() try: line += next(lines) except StopIteration: return yield Requirement(line)
python
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) for line in lines: # Drop comments -- a hash without a space may be in a URL. if ' #' in line: line = line[:line.find(' #')] # If there is a line continuation, drop it, and append the next line. if line.endswith('\\'): line = line[:-2].strip() try: line += next(lines) except StopIteration: return yield Requirement(line)
[ "def", "parse_requirements", "(", "strs", ")", ":", "# create a steppable iterator, so we can handle \\-continuations", "lines", "=", "iter", "(", "yield_lines", "(", "strs", ")", ")", "for", "line", "in", "lines", ":", "# Drop comments -- a hash without a space may be in a URL.", "if", "' #'", "in", "line", ":", "line", "=", "line", "[", ":", "line", ".", "find", "(", "' #'", ")", "]", "# If there is a line continuation, drop it, and append the next line.", "if", "line", ".", "endswith", "(", "'\\\\'", ")", ":", "line", "=", "line", "[", ":", "-", "2", "]", ".", "strip", "(", ")", "try", ":", "line", "+=", "next", "(", "lines", ")", "except", "StopIteration", ":", "return", "yield", "Requirement", "(", "line", ")" ]
Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof.
[ "Yield", "Requirement", "objects", "for", "each", "specification", "in", "strs" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2951-L2970
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_find_adapter
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
python
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
[ "def", "_find_adapter", "(", "registry", ",", "ob", ")", ":", "types", "=", "_always_object", "(", "inspect", ".", "getmro", "(", "getattr", "(", "ob", ",", "'__class__'", ",", "type", "(", "ob", ")", ")", ")", ")", "for", "t", "in", "types", ":", "if", "t", "in", "registry", ":", "return", "registry", "[", "t", "]" ]
Return an adapter factory for `ob` from `registry`
[ "Return", "an", "adapter", "factory", "for", "ob", "from", "registry" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L3037-L3042
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ensure_directory
def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) py31compat.makedirs(dirname, exist_ok=True)
python
def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) py31compat.makedirs(dirname, exist_ok=True)
[ "def", "ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "py31compat", ".", "makedirs", "(", "dirname", ",", "exist_ok", "=", "True", ")" ]
Ensure that the parent directory of `path` exists
[ "Ensure", "that", "the", "parent", "directory", "of", "path", "exists" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L3045-L3048
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
split_sections
def split_sections(s): """Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``. """ section = None content = [] for line in yield_lines(s): if line.startswith("["): if line.endswith("]"): if section or content: yield section, content section = line[1:-1].strip() content = [] else: raise ValueError("Invalid section heading", line) else: content.append(line) # wrap up last segment yield section, content
python
def split_sections(s): """Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``. """ section = None content = [] for line in yield_lines(s): if line.startswith("["): if line.endswith("]"): if section or content: yield section, content section = line[1:-1].strip() content = [] else: raise ValueError("Invalid section heading", line) else: content.append(line) # wrap up last segment yield section, content
[ "def", "split_sections", "(", "s", ")", ":", "section", "=", "None", "content", "=", "[", "]", "for", "line", "in", "yield_lines", "(", "s", ")", ":", "if", "line", ".", "startswith", "(", "\"[\"", ")", ":", "if", "line", ".", "endswith", "(", "\"]\"", ")", ":", "if", "section", "or", "content", ":", "yield", "section", ",", "content", "section", "=", "line", "[", "1", ":", "-", "1", "]", ".", "strip", "(", ")", "content", "=", "[", "]", "else", ":", "raise", "ValueError", "(", "\"Invalid section heading\"", ",", "line", ")", "else", ":", "content", ".", "append", "(", "line", ")", "# wrap up last segment", "yield", "section", ",", "content" ]
Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``.
[ "Split", "a", "string", "or", "iterable", "thereof", "into", "(", "section", "content", ")", "pairs" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L3064-L3087
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
VersionConflict.with_context
def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args)
python
def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args)
[ "def", "with_context", "(", "self", ",", "required_by", ")", ":", "if", "not", "required_by", ":", "return", "self", "args", "=", "self", ".", "args", "+", "(", "required_by", ",", ")", "return", "ContextualVersionConflict", "(", "*", "args", ")" ]
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
[ "If", "required_by", "is", "non", "-", "empty", "return", "a", "version", "of", "self", "that", "is", "a", "ContextualVersionConflict", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L277-L285
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet._build_master
def _build_master(cls): """ Prepare the master working set. """ ws = cls() try: from __main__ import __requires__ except ImportError: # The main program does not list any requirements return ws # ensure the requirements are met try: ws.require(__requires__) except VersionConflict: return cls._build_from_requirements(__requires__) return ws
python
def _build_master(cls): """ Prepare the master working set. """ ws = cls() try: from __main__ import __requires__ except ImportError: # The main program does not list any requirements return ws # ensure the requirements are met try: ws.require(__requires__) except VersionConflict: return cls._build_from_requirements(__requires__) return ws
[ "def", "_build_master", "(", "cls", ")", ":", "ws", "=", "cls", "(", ")", "try", ":", "from", "__main__", "import", "__requires__", "except", "ImportError", ":", "# The main program does not list any requirements", "return", "ws", "# ensure the requirements are met", "try", ":", "ws", ".", "require", "(", "__requires__", ")", "except", "VersionConflict", ":", "return", "cls", ".", "_build_from_requirements", "(", "__requires__", ")", "return", "ws" ]
Prepare the master working set.
[ "Prepare", "the", "master", "working", "set", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L568-L585
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet._build_from_requirements
def _build_from_requirements(cls, req_spec): """ Build a working set from a requirement spec. Rewrites sys.path. """ # try it without defaults already on sys.path # by starting with an empty path ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) # add any missing entries from sys.path for entry in sys.path: if entry not in ws.entries: ws.add_entry(entry) # then copy back to sys.path sys.path[:] = ws.entries return ws
python
def _build_from_requirements(cls, req_spec): """ Build a working set from a requirement spec. Rewrites sys.path. """ # try it without defaults already on sys.path # by starting with an empty path ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) # add any missing entries from sys.path for entry in sys.path: if entry not in ws.entries: ws.add_entry(entry) # then copy back to sys.path sys.path[:] = ws.entries return ws
[ "def", "_build_from_requirements", "(", "cls", ",", "req_spec", ")", ":", "# try it without defaults already on sys.path", "# by starting with an empty path", "ws", "=", "cls", "(", "[", "]", ")", "reqs", "=", "parse_requirements", "(", "req_spec", ")", "dists", "=", "ws", ".", "resolve", "(", "reqs", ",", "Environment", "(", ")", ")", "for", "dist", "in", "dists", ":", "ws", ".", "add", "(", "dist", ")", "# add any missing entries from sys.path", "for", "entry", "in", "sys", ".", "path", ":", "if", "entry", "not", "in", "ws", ".", "entries", ":", "ws", ".", "add_entry", "(", "entry", ")", "# then copy back to sys.path", "sys", ".", "path", "[", ":", "]", "=", "ws", ".", "entries", "return", "ws" ]
Build a working set from a requirement spec. Rewrites sys.path.
[ "Build", "a", "working", "set", "from", "a", "requirement", "spec", ".", "Rewrites", "sys", ".", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L588-L607
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet.add_entry
def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.) """ self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False)
python
def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.) """ self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False)
[ "def", "add_entry", "(", "self", ",", "entry", ")", ":", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "for", "dist", "in", "find_distributions", "(", "entry", ",", "True", ")", ":", "self", ".", "add", "(", "dist", ",", "entry", ",", "False", ")" ]
Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.)
[ "Add", "a", "path", "item", "to", ".", "entries", "finding", "any", "distributions", "on", "it" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L609-L622
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet.iter_entry_points
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ return ( entry for dist in self for entry in dist.get_entry_map(group).values() if name is None or name == entry.name )
python
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ return ( entry for dist in self for entry in dist.get_entry_map(group).values() if name is None or name == entry.name )
[ "def", "iter_entry_points", "(", "self", ",", "group", ",", "name", "=", "None", ")", ":", "return", "(", "entry", "for", "dist", "in", "self", "for", "entry", "in", "dist", ".", "get_entry_map", "(", "group", ")", ".", "values", "(", ")", "if", "name", "is", "None", "or", "name", "==", "entry", ".", "name", ")" ]
Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).
[ "Yield", "entry", "point", "objects", "from", "group", "matching", "name" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L644-L656
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet.run_script
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
python
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "self", ",", "requires", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "name", "self", ".", "require", "(", "requires", ")", "[", "0", "]", ".", "run_script", "(", "script_name", ",", "ns", ")" ]
Locate distribution for `requires` and run `script_name` script
[ "Locate", "distribution", "for", "requires", "and", "run", "script_name", "script" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L658-L664
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet.require
def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
python
def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
[ "def", "require", "(", "self", ",", "*", "requirements", ")", ":", "needed", "=", "self", ".", "resolve", "(", "parse_requirements", "(", "requirements", ")", ")", "for", "dist", "in", "needed", ":", "self", ".", "add", "(", "dist", ")", "return", "needed" ]
Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set.
[ "Ensure", "that", "distributions", "matching", "requirements", "are", "activated" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L889-L903
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
WorkingSet.subscribe
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
python
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ",", "existing", "=", "True", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "if", "not", "existing", ":", "return", "for", "dist", "in", "self", ":", "callback", "(", "dist", ")" ]
Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well.
[ "Invoke", "callback", "for", "all", "distributions" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L905-L917
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
_ReqExtras.markers_pass
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req, ()) + (extras or (None,)) ) return not req.marker or any(extra_evals)
python
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req, ()) + (extras or (None,)) ) return not req.marker or any(extra_evals)
[ "def", "markers_pass", "(", "self", ",", "req", ",", "extras", "=", "None", ")", ":", "extra_evals", "=", "(", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", "for", "extra", "in", "self", ".", "get", "(", "req", ",", "(", ")", ")", "+", "(", "extras", "or", "(", "None", ",", ")", ")", ")", "return", "not", "req", ".", "marker", "or", "any", "(", "extra_evals", ")" ]
Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True.
[ "Evaluate", "markers", "for", "req", "against", "each", "extra", "that", "demanded", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L942-L954
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Environment.scan
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
python
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
[ "def", "scan", "(", "self", ",", "search_path", "=", "None", ")", ":", "if", "search_path", "is", "None", ":", "search_path", "=", "sys", ".", "path", "for", "item", "in", "search_path", ":", "for", "dist", "in", "find_distributions", "(", "item", ")", ":", "self", ".", "add", "(", "dist", ")" ]
Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.
[ "Scan", "search_path", "for", "distributions", "usable", "in", "this", "environment" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1002-L1015
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Environment.add
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
python
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "self", ".", "can_add", "(", "dist", ")", "and", "dist", ".", "has_version", "(", ")", ":", "dists", "=", "self", ".", "_distmap", ".", "setdefault", "(", "dist", ".", "key", ",", "[", "]", ")", "if", "dist", "not", "in", "dists", ":", "dists", ".", "append", "(", "dist", ")", "dists", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "'hashcmp'", ")", ",", "reverse", "=", "True", ")" ]
Add `dist` if we ``can_add()`` it and it has not already been added
[ "Add", "dist", "if", "we", "can_add", "()", "it", "and", "it", "has", "not", "already", "been", "added" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1028-L1035
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Environment.best_match
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned. """ try: dist = working_set.find(req) except VersionConflict: if not replace_conflicting: raise dist = None if dist is not None: return dist for dist in self[req.key]: if dist in req: return dist # try to download/install return self.obtain(req, installer)
python
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned. """ try: dist = working_set.find(req) except VersionConflict: if not replace_conflicting: raise dist = None if dist is not None: return dist for dist in self[req.key]: if dist in req: return dist # try to download/install return self.obtain(req, installer)
[ "def", "best_match", "(", "self", ",", "req", ",", "working_set", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ")", ":", "try", ":", "dist", "=", "working_set", ".", "find", "(", "req", ")", "except", "VersionConflict", ":", "if", "not", "replace_conflicting", ":", "raise", "dist", "=", "None", "if", "dist", "is", "not", "None", ":", "return", "dist", "for", "dist", "in", "self", "[", "req", ".", "key", "]", ":", "if", "dist", "in", "req", ":", "return", "dist", "# try to download/install", "return", "self", ".", "obtain", "(", "req", ",", "installer", ")" ]
Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned.
[ "Find", "distribution", "best", "matching", "req", "and", "usable", "on", "working_set" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1037-L1063
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ResourceManager.extraction_error
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
python
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
[ "def", "extraction_error", "(", "self", ")", ":", "old_exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "cache_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "tmpl", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\"", ")", ".", "lstrip", "(", ")", "err", "=", "ExtractionError", "(", "tmpl", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "err", ".", "manager", "=", "self", "err", ".", "cache_path", "=", "cache_path", "err", ".", "original_error", "=", "old_exc", "raise", "err" ]
Give an error message for problems extracting file(s)
[ "Give", "an", "error", "message", "for", "problems", "extracting", "file", "(", "s", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1164-L1190
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ResourceManager._warn_unsafe_extraction_path
def _warn_unsafe_extraction_path(path): """ If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details. """ if os.name == 'nt' and not path.startswith(os.environ['windir']): # On Windows, permissions are generally restrictive by default # and temp directories are not writable by other users, so # bypass the warning. return mode = os.stat(path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: msg = ( "%s is writable by group/others and vulnerable to attack " "when " "used with get_resource_filename. Consider a more secure " "location (set with .set_extraction_path or the " "PYTHON_EGG_CACHE environment variable)." % path ) warnings.warn(msg, UserWarning)
python
def _warn_unsafe_extraction_path(path): """ If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details. """ if os.name == 'nt' and not path.startswith(os.environ['windir']): # On Windows, permissions are generally restrictive by default # and temp directories are not writable by other users, so # bypass the warning. return mode = os.stat(path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: msg = ( "%s is writable by group/others and vulnerable to attack " "when " "used with get_resource_filename. Consider a more secure " "location (set with .set_extraction_path or the " "PYTHON_EGG_CACHE environment variable)." % path ) warnings.warn(msg, UserWarning)
[ "def", "_warn_unsafe_extraction_path", "(", "path", ")", ":", "if", "os", ".", "name", "==", "'nt'", "and", "not", "path", ".", "startswith", "(", "os", ".", "environ", "[", "'windir'", "]", ")", ":", "# On Windows, permissions are generally restrictive by default", "# and temp directories are not writable by other users, so", "# bypass the warning.", "return", "mode", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "if", "mode", "&", "stat", ".", "S_IWOTH", "or", "mode", "&", "stat", ".", "S_IWGRP", ":", "msg", "=", "(", "\"%s is writable by group/others and vulnerable to attack \"", "\"when \"", "\"used with get_resource_filename. Consider a more secure \"", "\"location (set with .set_extraction_path or the \"", "\"PYTHON_EGG_CACHE environment variable).\"", "%", "path", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")" ]
If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details.
[ "If", "the", "default", "extraction", "path", "is", "overridden", "and", "set", "to", "an", "insecure", "location", "such", "as", "/", "tmp", "it", "opens", "up", "an", "opportunity", "for", "an", "attacker", "to", "replace", "an", "extracted", "file", "with", "an", "unauthorized", "payload", ".", "Warn", "the", "user", "if", "a", "known", "insecure", "location", "is", "used", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1218-L1241
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ResourceManager.postprocess
def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns. """ if os.name == 'posix': # Make the resource executable mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 os.chmod(tempname, mode)
python
def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns. """ if os.name == 'posix': # Make the resource executable mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 os.chmod(tempname, mode)
[ "def", "postprocess", "(", "self", ",", "tempname", ",", "filename", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "# Make the resource executable", "mode", "=", "(", "(", "os", ".", "stat", "(", "tempname", ")", ".", "st_mode", ")", "|", "0o555", ")", "&", "0o7777", "os", ".", "chmod", "(", "tempname", ",", "mode", ")" ]
Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns.
[ "Perform", "any", "platform", "-", "specific", "postprocessing", "of", "tempname" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1243-L1261
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ZipManifests.build
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with zipfile.ZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
python
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with zipfile.ZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
[ "def", "build", "(", "cls", ",", "path", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "path", ")", "as", "zfile", ":", "items", "=", "(", "(", "name", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ",", "zfile", ".", "getinfo", "(", "name", ")", ",", ")", "for", "name", "in", "zfile", ".", "namelist", "(", ")", ")", "return", "dict", "(", "items", ")" ]
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows.
[ "Build", "a", "dictionary", "similar", "to", "the", "zipimport", "directory", "caches", "except", "instead", "of", "tuples", "store", "ZipInfo", "objects", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1562-L1578
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
MemoizedZipManifests.load
def load(self, path): """ Load a manifest at path or return a suitable manifest already loaded. """ path = os.path.normpath(path) mtime = os.stat(path).st_mtime if path not in self or self[path].mtime != mtime: manifest = self.build(path) self[path] = self.manifest_mod(manifest, mtime) return self[path].manifest
python
def load(self, path): """ Load a manifest at path or return a suitable manifest already loaded. """ path = os.path.normpath(path) mtime = os.stat(path).st_mtime if path not in self or self[path].mtime != mtime: manifest = self.build(path) self[path] = self.manifest_mod(manifest, mtime) return self[path].manifest
[ "def", "load", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "mtime", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mtime", "if", "path", "not", "in", "self", "or", "self", "[", "path", "]", ".", "mtime", "!=", "mtime", ":", "manifest", "=", "self", ".", "build", "(", "path", ")", "self", "[", "path", "]", "=", "self", ".", "manifest_mod", "(", "manifest", ",", "mtime", ")", "return", "self", "[", "path", "]", ".", "manifest" ]
Load a manifest at path or return a suitable manifest already loaded.
[ "Load", "a", "manifest", "at", "path", "or", "return", "a", "suitable", "manifest", "already", "loaded", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1589-L1600
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
ZipProvider._is_current
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size != size or stat.st_mtime != timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
python
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size != size or stat.st_mtime != timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
[ "def", "_is_current", "(", "self", ",", "file_path", ",", "zip_path", ")", ":", "timestamp", ",", "size", "=", "self", ".", "_get_date_and_size", "(", "self", ".", "zipinfo", "[", "zip_path", "]", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "False", "stat", "=", "os", ".", "stat", "(", "file_path", ")", "if", "stat", ".", "st_size", "!=", "size", "or", "stat", ".", "st_mtime", "!=", "timestamp", ":", "return", "False", "# check that the contents match", "zip_contents", "=", "self", ".", "loader", ".", "get_data", "(", "zip_path", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "return", "zip_contents", "==", "file_contents" ]
Return True if the file_path is current for this zip_path
[ "Return", "True", "if", "the", "file_path", "is", "current", "for", "this", "zip_path" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1716-L1730
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EntryPoint.load
def load(self, require=True, *args, **kwargs): """ Require packages for this EntryPoint, then resolve it. """ if not require or args or kwargs: warnings.warn( "Parameters to load are deprecated. Call .resolve and " ".require separately.", PkgResourcesDeprecationWarning, stacklevel=2, ) if require: self.require(*args, **kwargs) return self.resolve()
python
def load(self, require=True, *args, **kwargs): """ Require packages for this EntryPoint, then resolve it. """ if not require or args or kwargs: warnings.warn( "Parameters to load are deprecated. Call .resolve and " ".require separately.", PkgResourcesDeprecationWarning, stacklevel=2, ) if require: self.require(*args, **kwargs) return self.resolve()
[ "def", "load", "(", "self", ",", "require", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "require", "or", "args", "or", "kwargs", ":", "warnings", ".", "warn", "(", "\"Parameters to load are deprecated. Call .resolve and \"", "\".require separately.\"", ",", "PkgResourcesDeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "if", "require", ":", "self", ".", "require", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "resolve", "(", ")" ]
Require packages for this EntryPoint, then resolve it.
[ "Require", "packages", "for", "this", "EntryPoint", "then", "resolve", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2333-L2346
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EntryPoint.resolve
def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc))
python
def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc))
[ "def", "resolve", "(", "self", ")", ":", "module", "=", "__import__", "(", "self", ".", "module_name", ",", "fromlist", "=", "[", "'__name__'", "]", ",", "level", "=", "0", ")", "try", ":", "return", "functools", ".", "reduce", "(", "getattr", ",", "self", ".", "attrs", ",", "module", ")", "except", "AttributeError", "as", "exc", ":", "raise", "ImportError", "(", "str", "(", "exc", ")", ")" ]
Resolve the entry point from its module and attrs.
[ "Resolve", "the", "entry", "point", "from", "its", "module", "and", "attrs", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2348-L2356
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EntryPoint.parse
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist)
python
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist)
[ "def", "parse", "(", "cls", ",", "src", ",", "dist", "=", "None", ")", ":", "m", "=", "cls", ".", "pattern", ".", "match", "(", "src", ")", "if", "not", "m", ":", "msg", "=", "\"EntryPoint must be in 'name=module:attrs [extras]' format\"", "raise", "ValueError", "(", "msg", ",", "src", ")", "res", "=", "m", ".", "groupdict", "(", ")", "extras", "=", "cls", ".", "_parse_extras", "(", "res", "[", "'extras'", "]", ")", "attrs", "=", "res", "[", "'attr'", "]", ".", "split", "(", "'.'", ")", "if", "res", "[", "'attr'", "]", "else", "(", ")", "return", "cls", "(", "res", "[", "'name'", "]", ",", "res", "[", "'module'", "]", ",", "attrs", ",", "extras", ",", "dist", ")" ]
Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional
[ "Parse", "a", "single", "entry", "point", "from", "string", "src" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2381-L2398
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EntryPoint.parse_group
def parse_group(cls, group, lines, dist=None): """Parse an entry point group""" if not MODULE(group): raise ValueError("Invalid group name", group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if ep.name in this: raise ValueError("Duplicate entry point", group, ep.name) this[ep.name] = ep return this
python
def parse_group(cls, group, lines, dist=None): """Parse an entry point group""" if not MODULE(group): raise ValueError("Invalid group name", group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if ep.name in this: raise ValueError("Duplicate entry point", group, ep.name) this[ep.name] = ep return this
[ "def", "parse_group", "(", "cls", ",", "group", ",", "lines", ",", "dist", "=", "None", ")", ":", "if", "not", "MODULE", "(", "group", ")", ":", "raise", "ValueError", "(", "\"Invalid group name\"", ",", "group", ")", "this", "=", "{", "}", "for", "line", "in", "yield_lines", "(", "lines", ")", ":", "ep", "=", "cls", ".", "parse", "(", "line", ",", "dist", ")", "if", "ep", ".", "name", "in", "this", ":", "raise", "ValueError", "(", "\"Duplicate entry point\"", ",", "group", ",", "ep", ".", "name", ")", "this", "[", "ep", ".", "name", "]", "=", "ep", "return", "this" ]
Parse an entry point group
[ "Parse", "an", "entry", "point", "group" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2410-L2420
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EntryPoint.parse_map
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
python
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "maps", "=", "{", "}", "for", "group", ",", "lines", "in", "data", ":", "if", "group", "is", "None", ":", "if", "not", "lines", ":", "continue", "raise", "ValueError", "(", "\"Entry points must be listed in groups\"", ")", "group", "=", "group", ".", "strip", "(", ")", "if", "group", "in", "maps", ":", "raise", "ValueError", "(", "\"Duplicate group name\"", ",", "group", ")", "maps", "[", "group", "]", "=", "cls", ".", "parse_group", "(", "group", ",", "lines", ",", "dist", ")", "return", "maps" ]
Parse a map of entry point groups
[ "Parse", "a", "map", "of", "entry", "point", "groups" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2423-L2439
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution._dep_map
def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) return self.__dep_map
python
def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) return self.__dep_map
[ "def", "_dep_map", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dep_map", "except", "AttributeError", ":", "self", ".", "__dep_map", "=", "self", ".", "_filter_extras", "(", "self", ".", "_build_dep_map", "(", ")", ")", "return", "self", ".", "__dep_map" ]
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
[ "A", "map", "of", "extra", "to", "its", "list", "of", "(", "direct", ")", "requirements", "for", "this", "distribution", "including", "the", "null", "extra", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2593-L2602
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution._filter_extras
def _filter_extras(dm): """ Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers. """ for extra in list(filter(None, dm)): new_extra = extra reqs = dm.pop(extra) new_extra, _, marker = extra.partition(':') fails_marker = marker and ( invalid_marker(marker) or not evaluate_marker(marker) ) if fails_marker: reqs = [] new_extra = safe_extra(new_extra) or None dm.setdefault(new_extra, []).extend(reqs) return dm
python
def _filter_extras(dm): """ Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers. """ for extra in list(filter(None, dm)): new_extra = extra reqs = dm.pop(extra) new_extra, _, marker = extra.partition(':') fails_marker = marker and ( invalid_marker(marker) or not evaluate_marker(marker) ) if fails_marker: reqs = [] new_extra = safe_extra(new_extra) or None dm.setdefault(new_extra, []).extend(reqs) return dm
[ "def", "_filter_extras", "(", "dm", ")", ":", "for", "extra", "in", "list", "(", "filter", "(", "None", ",", "dm", ")", ")", ":", "new_extra", "=", "extra", "reqs", "=", "dm", ".", "pop", "(", "extra", ")", "new_extra", ",", "_", ",", "marker", "=", "extra", ".", "partition", "(", "':'", ")", "fails_marker", "=", "marker", "and", "(", "invalid_marker", "(", "marker", ")", "or", "not", "evaluate_marker", "(", "marker", ")", ")", "if", "fails_marker", ":", "reqs", "=", "[", "]", "new_extra", "=", "safe_extra", "(", "new_extra", ")", "or", "None", "dm", ".", "setdefault", "(", "new_extra", ",", "[", "]", ")", ".", "extend", "(", "reqs", ")", "return", "dm" ]
Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers.
[ "Given", "a", "mapping", "of", "extras", "to", "dependencies", "strip", "off", "environment", "markers", "and", "filter", "out", "any", "dependencies", "not", "matching", "the", "markers", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2605-L2624
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.requires
def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps
python
def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps
[ "def", "requires", "(", "self", ",", "extras", "=", "(", ")", ")", ":", "dm", "=", "self", ".", "_dep_map", "deps", "=", "[", "]", "deps", ".", "extend", "(", "dm", ".", "get", "(", "None", ",", "(", ")", ")", ")", "for", "ext", "in", "extras", ":", "try", ":", "deps", ".", "extend", "(", "dm", "[", "safe_extra", "(", "ext", ")", "]", ")", "except", "KeyError", ":", "raise", "UnknownExtra", "(", "\"%s has no such extra feature %r\"", "%", "(", "self", ",", "ext", ")", ")", "return", "deps" ]
List of Requirements needed for this distro if `extras` are used
[ "List", "of", "Requirements", "needed", "for", "this", "distro", "if", "extras", "are", "used" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2633-L2645
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.activate
def activate(self, path=None, replace=False): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=replace) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg)
python
def activate(self, path=None, replace=False): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=replace) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg)
[ "def", "activate", "(", "self", ",", "path", "=", "None", ",", "replace", "=", "False", ")", ":", "if", "path", "is", "None", ":", "path", "=", "sys", ".", "path", "self", ".", "insert_on", "(", "path", ",", "replace", "=", "replace", ")", "if", "path", "is", "sys", ".", "path", ":", "fixup_namespace_packages", "(", "self", ".", "location", ")", "for", "pkg", "in", "self", ".", "_get_metadata", "(", "'namespace_packages.txt'", ")", ":", "if", "pkg", "in", "sys", ".", "modules", ":", "declare_namespace", "(", "pkg", ")" ]
Ensure distribution is importable on `path` (default=sys.path)
[ "Ensure", "distribution", "is", "importable", "on", "path", "(", "default", "=", "sys", ".", "path", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2652-L2661
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.egg_name
def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename
python
def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename
[ "def", "egg_name", "(", "self", ")", ":", "filename", "=", "\"%s-%s-py%s\"", "%", "(", "to_filename", "(", "self", ".", "project_name", ")", ",", "to_filename", "(", "self", ".", "version", ")", ",", "self", ".", "py_version", "or", "PY_MAJOR", ")", "if", "self", ".", "platform", ":", "filename", "+=", "'-'", "+", "self", ".", "platform", "return", "filename" ]
Return what this distribution's standard .egg filename should be
[ "Return", "what", "this", "distribution", "s", "standard", ".", "egg", "filename", "should", "be" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2663-L2672
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.as_requirement
def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec)
python
def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec)
[ "def", "as_requirement", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "parsed_version", ",", "packaging", ".", "version", ".", "Version", ")", ":", "spec", "=", "\"%s==%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "else", ":", "spec", "=", "\"%s===%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "return", "Requirement", ".", "parse", "(", "spec", ")" ]
Return a ``Requirement`` that matches this distribution exactly
[ "Return", "a", "Requirement", "that", "matches", "this", "distribution", "exactly" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2714-L2721
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.load_entry_point
def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
python
def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
[ "def", "load_entry_point", "(", "self", ",", "group", ",", "name", ")", ":", "ep", "=", "self", ".", "get_entry_info", "(", "group", ",", "name", ")", "if", "ep", "is", "None", ":", "raise", "ImportError", "(", "\"Entry point %r not found\"", "%", "(", "(", "group", ",", "name", ")", ",", ")", ")", "return", "ep", ".", "load", "(", ")" ]
Return the `name` entry point of `group` or raise ImportError
[ "Return", "the", "name", "entry", "point", "of", "group", "or", "raise", "ImportError" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2723-L2728
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.get_entry_map
def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group, {}) return ep_map
python
def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group, {}) return ep_map
[ "def", "get_entry_map", "(", "self", ",", "group", "=", "None", ")", ":", "try", ":", "ep_map", "=", "self", ".", "_ep_map", "except", "AttributeError", ":", "ep_map", "=", "self", ".", "_ep_map", "=", "EntryPoint", ".", "parse_map", "(", "self", ".", "_get_metadata", "(", "'entry_points.txt'", ")", ",", "self", ")", "if", "group", "is", "not", "None", ":", "return", "ep_map", ".", "get", "(", "group", ",", "{", "}", ")", "return", "ep_map" ]
Return the entry point map for `group`, or the full entry map
[ "Return", "the", "entry", "point", "map", "for", "group", "or", "the", "full", "entry", "map" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2730-L2740
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
Distribution.clone
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
python
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
[ "def", "clone", "(", "self", ",", "*", "*", "kw", ")", ":", "names", "=", "'project_name version py_version platform location precedence'", "for", "attr", "in", "names", ".", "split", "(", ")", ":", "kw", ".", "setdefault", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ",", "None", ")", ")", "kw", ".", "setdefault", "(", "'metadata'", ",", "self", ".", "_provider", ")", "return", "self", ".", "__class__", "(", "*", "*", "kw", ")" ]
Copy this distribution, substituting in any changed keyword args
[ "Copy", "this", "distribution", "substituting", "in", "any", "changed", "keyword", "args" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2844-L2850
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
EggInfoDistribution._reload_version
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename. """ md_version = _version_from_file(self._get_metadata(self.PKG_INFO)) if md_version: self._version = md_version return self
python
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename. """ md_version = _version_from_file(self._get_metadata(self.PKG_INFO)) if md_version: self._version = md_version return self
[ "def", "_reload_version", "(", "self", ")", ":", "md_version", "=", "_version_from_file", "(", "self", ".", "_get_metadata", "(", "self", ".", "PKG_INFO", ")", ")", "if", "md_version", ":", "self", ".", "_version", "=", "md_version", "return", "self" ]
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename.
[ "Packages", "installed", "by", "distutils", "(", "e", ".", "g", ".", "numpy", "or", "scipy", ")", "which", "uses", "an", "old", "safe_version", "and", "so", "their", "version", "numbers", "can", "get", "mangled", "when", "converted", "to", "filenames", "(", "e", ".", "g", ".", "1", ".", "11", ".", "0", ".", "dev0", "+", "2329eae", "to", "1", ".", "11", ".", "0", ".", "dev0_2329eae", ")", ".", "These", "distributions", "will", "not", "be", "parsed", "properly", "downstream", "by", "Distribution", "and", "safe_version", "so", "take", "an", "extra", "step", "and", "try", "to", "get", "the", "version", "number", "from", "the", "metadata", "file", "itself", "instead", "of", "the", "filename", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2858-L2873
train
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
DistInfoDistribution._compute_dependencies
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: reqs.extend(parse_requirements(req)) def reqs_for_extra(extra): for req in reqs: if not req.marker or req.marker.evaluate({'extra': extra}): yield req common = frozenset(reqs_for_extra(None)) dm[None].extend(common) for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: s_extra = safe_extra(extra.strip()) dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common) return dm
python
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: reqs.extend(parse_requirements(req)) def reqs_for_extra(extra): for req in reqs: if not req.marker or req.marker.evaluate({'extra': extra}): yield req common = frozenset(reqs_for_extra(None)) dm[None].extend(common) for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: s_extra = safe_extra(extra.strip()) dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common) return dm
[ "def", "_compute_dependencies", "(", "self", ")", ":", "dm", "=", "self", ".", "__dep_map", "=", "{", "None", ":", "[", "]", "}", "reqs", "=", "[", "]", "# Including any condition expressions", "for", "req", "in", "self", ".", "_parsed_pkg_info", ".", "get_all", "(", "'Requires-Dist'", ")", "or", "[", "]", ":", "reqs", ".", "extend", "(", "parse_requirements", "(", "req", ")", ")", "def", "reqs_for_extra", "(", "extra", ")", ":", "for", "req", "in", "reqs", ":", "if", "not", "req", ".", "marker", "or", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", ":", "yield", "req", "common", "=", "frozenset", "(", "reqs_for_extra", "(", "None", ")", ")", "dm", "[", "None", "]", ".", "extend", "(", "common", ")", "for", "extra", "in", "self", ".", "_parsed_pkg_info", ".", "get_all", "(", "'Provides-Extra'", ")", "or", "[", "]", ":", "s_extra", "=", "safe_extra", "(", "extra", ".", "strip", "(", ")", ")", "dm", "[", "s_extra", "]", "=", "list", "(", "frozenset", "(", "reqs_for_extra", "(", "extra", ")", ")", "-", "common", ")", "return", "dm" ]
Recompute this distribution's dependencies.
[ "Recompute", "this", "distribution", "s", "dependencies", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2902-L2923
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
DefinitionSchema._expand_logical_shortcuts
def _expand_logical_shortcuts(cls, schema): """ Expand agglutinated rules in a definition-schema. :param schema: The schema-definition to expand. :return: The expanded schema-definition. """ def is_of_rule(x): return isinstance(x, _str_type) and \ x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_')) for field in schema: for of_rule in (x for x in schema[field] if is_of_rule(x)): operator, rule = of_rule.split('_') schema[field].update({operator: []}) for value in schema[field][of_rule]: schema[field][operator].append({rule: value}) del schema[field][of_rule] return schema
python
def _expand_logical_shortcuts(cls, schema): """ Expand agglutinated rules in a definition-schema. :param schema: The schema-definition to expand. :return: The expanded schema-definition. """ def is_of_rule(x): return isinstance(x, _str_type) and \ x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_')) for field in schema: for of_rule in (x for x in schema[field] if is_of_rule(x)): operator, rule = of_rule.split('_') schema[field].update({operator: []}) for value in schema[field][of_rule]: schema[field][operator].append({rule: value}) del schema[field][of_rule] return schema
[ "def", "_expand_logical_shortcuts", "(", "cls", ",", "schema", ")", ":", "def", "is_of_rule", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "_str_type", ")", "and", "x", ".", "startswith", "(", "(", "'allof_'", ",", "'anyof_'", ",", "'noneof_'", ",", "'oneof_'", ")", ")", "for", "field", "in", "schema", ":", "for", "of_rule", "in", "(", "x", "for", "x", "in", "schema", "[", "field", "]", "if", "is_of_rule", "(", "x", ")", ")", ":", "operator", ",", "rule", "=", "of_rule", ".", "split", "(", "'_'", ")", "schema", "[", "field", "]", ".", "update", "(", "{", "operator", ":", "[", "]", "}", ")", "for", "value", "in", "schema", "[", "field", "]", "[", "of_rule", "]", ":", "schema", "[", "field", "]", "[", "operator", "]", ".", "append", "(", "{", "rule", ":", "value", "}", ")", "del", "schema", "[", "field", "]", "[", "of_rule", "]", "return", "schema" ]
Expand agglutinated rules in a definition-schema. :param schema: The schema-definition to expand. :return: The expanded schema-definition.
[ "Expand", "agglutinated", "rules", "in", "a", "definition", "-", "schema", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L116-L133
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
DefinitionSchema._validate
def _validate(self, schema): """ Validates a schema that defines rules against supported rules. :param schema: The schema to be validated as a legal cerberus schema according to the rules of this Validator object. """ if isinstance(schema, _str_type): schema = self.validator.schema_registry.get(schema, schema) if schema is None: raise SchemaError(errors.SCHEMA_ERROR_MISSING) schema = copy(schema) for field in schema: if isinstance(schema[field], _str_type): schema[field] = rules_set_registry.get(schema[field], schema[field]) if not self.schema_validator(schema, normalize=False): raise SchemaError(self.schema_validator.errors)
python
def _validate(self, schema): """ Validates a schema that defines rules against supported rules. :param schema: The schema to be validated as a legal cerberus schema according to the rules of this Validator object. """ if isinstance(schema, _str_type): schema = self.validator.schema_registry.get(schema, schema) if schema is None: raise SchemaError(errors.SCHEMA_ERROR_MISSING) schema = copy(schema) for field in schema: if isinstance(schema[field], _str_type): schema[field] = rules_set_registry.get(schema[field], schema[field]) if not self.schema_validator(schema, normalize=False): raise SchemaError(self.schema_validator.errors)
[ "def", "_validate", "(", "self", ",", "schema", ")", ":", "if", "isinstance", "(", "schema", ",", "_str_type", ")", ":", "schema", "=", "self", ".", "validator", ".", "schema_registry", ".", "get", "(", "schema", ",", "schema", ")", "if", "schema", "is", "None", ":", "raise", "SchemaError", "(", "errors", ".", "SCHEMA_ERROR_MISSING", ")", "schema", "=", "copy", "(", "schema", ")", "for", "field", "in", "schema", ":", "if", "isinstance", "(", "schema", "[", "field", "]", ",", "_str_type", ")", ":", "schema", "[", "field", "]", "=", "rules_set_registry", ".", "get", "(", "schema", "[", "field", "]", ",", "schema", "[", "field", "]", ")", "if", "not", "self", ".", "schema_validator", "(", "schema", ",", "normalize", "=", "False", ")", ":", "raise", "SchemaError", "(", "self", ".", "schema_validator", ".", "errors", ")" ]
Validates a schema that defines rules against supported rules. :param schema: The schema to be validated as a legal cerberus schema according to the rules of this Validator object.
[ "Validates", "a", "schema", "that", "defines", "rules", "against", "supported", "rules", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L200-L219
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
SchemaValidatorMixin._validate_logical
def _validate_logical(self, rule, field, value): """ {'allowed': ('allof', 'anyof', 'noneof', 'oneof')} """ if not isinstance(value, Sequence): self._error(field, errors.BAD_TYPE) return validator = self._get_child_validator( document_crumb=rule, allow_unknown=False, schema=self.target_validator.validation_rules) for constraints in value: _hash = (mapping_hash({'turing': constraints}), mapping_hash(self.target_validator.types_mapping)) if _hash in self.target_validator._valid_schemas: continue validator(constraints, normalize=False) if validator._errors: self._error(validator._errors) else: self.target_validator._valid_schemas.add(_hash)
python
def _validate_logical(self, rule, field, value): """ {'allowed': ('allof', 'anyof', 'noneof', 'oneof')} """ if not isinstance(value, Sequence): self._error(field, errors.BAD_TYPE) return validator = self._get_child_validator( document_crumb=rule, allow_unknown=False, schema=self.target_validator.validation_rules) for constraints in value: _hash = (mapping_hash({'turing': constraints}), mapping_hash(self.target_validator.types_mapping)) if _hash in self.target_validator._valid_schemas: continue validator(constraints, normalize=False) if validator._errors: self._error(validator._errors) else: self.target_validator._valid_schemas.add(_hash)
[ "def", "_validate_logical", "(", "self", ",", "rule", ",", "field", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Sequence", ")", ":", "self", ".", "_error", "(", "field", ",", "errors", ".", "BAD_TYPE", ")", "return", "validator", "=", "self", ".", "_get_child_validator", "(", "document_crumb", "=", "rule", ",", "allow_unknown", "=", "False", ",", "schema", "=", "self", ".", "target_validator", ".", "validation_rules", ")", "for", "constraints", "in", "value", ":", "_hash", "=", "(", "mapping_hash", "(", "{", "'turing'", ":", "constraints", "}", ")", ",", "mapping_hash", "(", "self", ".", "target_validator", ".", "types_mapping", ")", ")", "if", "_hash", "in", "self", ".", "target_validator", ".", "_valid_schemas", ":", "continue", "validator", "(", "constraints", ",", "normalize", "=", "False", ")", "if", "validator", ".", "_errors", ":", "self", ".", "_error", "(", "validator", ".", "_errors", ")", "else", ":", "self", ".", "target_validator", ".", "_valid_schemas", ".", "add", "(", "_hash", ")" ]
{'allowed': ('allof', 'anyof', 'noneof', 'oneof')}
[ "{", "allowed", ":", "(", "allof", "anyof", "noneof", "oneof", ")", "}" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L275-L295
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
Registry.add
def add(self, name, definition): """ Register a definition to the registry. Existing definitions are replaced silently. :param name: The name which can be used as reference in a validation schema. :type name: :class:`str` :param definition: The definition. :type definition: any :term:`mapping` """ self._storage[name] = self._expand_definition(definition)
python
def add(self, name, definition): """ Register a definition to the registry. Existing definitions are replaced silently. :param name: The name which can be used as reference in a validation schema. :type name: :class:`str` :param definition: The definition. :type definition: any :term:`mapping` """ self._storage[name] = self._expand_definition(definition)
[ "def", "add", "(", "self", ",", "name", ",", "definition", ")", ":", "self", ".", "_storage", "[", "name", "]", "=", "self", ".", "_expand_definition", "(", "definition", ")" ]
Register a definition to the registry. Existing definitions are replaced silently. :param name: The name which can be used as reference in a validation schema. :type name: :class:`str` :param definition: The definition. :type definition: any :term:`mapping`
[ "Register", "a", "definition", "to", "the", "registry", ".", "Existing", "definitions", "are", "replaced", "silently", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L423-L432
train
pypa/pipenv
pipenv/vendor/cerberus/schema.py
Registry.extend
def extend(self, definitions): """ Add several definitions at once. Existing definitions are replaced silently. :param definitions: The names and definitions. :type definitions: a :term:`mapping` or an :term:`iterable` with two-value :class:`tuple` s """ for name, definition in dict(definitions).items(): self.add(name, definition)
python
def extend(self, definitions): """ Add several definitions at once. Existing definitions are replaced silently. :param definitions: The names and definitions. :type definitions: a :term:`mapping` or an :term:`iterable` with two-value :class:`tuple` s """ for name, definition in dict(definitions).items(): self.add(name, definition)
[ "def", "extend", "(", "self", ",", "definitions", ")", ":", "for", "name", ",", "definition", "in", "dict", "(", "definitions", ")", ".", "items", "(", ")", ":", "self", ".", "add", "(", "name", ",", "definition", ")" ]
Add several definitions at once. Existing definitions are replaced silently. :param definitions: The names and definitions. :type definitions: a :term:`mapping` or an :term:`iterable` with two-value :class:`tuple` s
[ "Add", "several", "definitions", "at", "once", ".", "Existing", "definitions", "are", "replaced", "silently", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/schema.py#L443-L451
train
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/subversion.py
Subversion.export
def export(self, location): """Export the svn repository at the url to the destination location""" url, rev_options = self.get_url_rev_options(self.url) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exists(location): # Subversion doesn't like to check out over an existing # directory --force fixes this, but was only added in svn 1.5 rmtree(location) cmd_args = ['export'] + rev_options.to_args() + [url, location] self.run_command(cmd_args, show_stdout=False)
python
def export(self, location): """Export the svn repository at the url to the destination location""" url, rev_options = self.get_url_rev_options(self.url) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exists(location): # Subversion doesn't like to check out over an existing # directory --force fixes this, but was only added in svn 1.5 rmtree(location) cmd_args = ['export'] + rev_options.to_args() + [url, location] self.run_command(cmd_args, show_stdout=False)
[ "def", "export", "(", "self", ",", "location", ")", ":", "url", ",", "rev_options", "=", "self", ".", "get_url_rev_options", "(", "self", ".", "url", ")", "logger", ".", "info", "(", "'Exporting svn repository %s to %s'", ",", "url", ",", "location", ")", "with", "indent_log", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "location", ")", ":", "# Subversion doesn't like to check out over an existing", "# directory --force fixes this, but was only added in svn 1.5", "rmtree", "(", "location", ")", "cmd_args", "=", "[", "'export'", "]", "+", "rev_options", ".", "to_args", "(", ")", "+", "[", "url", ",", "location", "]", "self", ".", "run_command", "(", "cmd_args", ",", "show_stdout", "=", "False", ")" ]
Export the svn repository at the url to the destination location
[ "Export", "the", "svn", "repository", "at", "the", "url", "to", "the", "destination", "location" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/subversion.py#L31-L42
train
pypa/pipenv
pipenv/patched/notpip/_internal/vcs/subversion.py
Subversion.get_netloc_and_auth
def get_netloc_and_auth(self, netloc, scheme): """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for # svn+ssh URLs, so keep the auth information in the URL. return super(Subversion, self).get_netloc_and_auth( netloc, scheme) return split_auth_from_netloc(netloc)
python
def get_netloc_and_auth(self, netloc, scheme): """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for # svn+ssh URLs, so keep the auth information in the URL. return super(Subversion, self).get_netloc_and_auth( netloc, scheme) return split_auth_from_netloc(netloc)
[ "def", "get_netloc_and_auth", "(", "self", ",", "netloc", ",", "scheme", ")", ":", "if", "scheme", "==", "'ssh'", ":", "# The --username and --password options can't be used for", "# svn+ssh URLs, so keep the auth information in the URL.", "return", "super", "(", "Subversion", ",", "self", ")", ".", "get_netloc_and_auth", "(", "netloc", ",", "scheme", ")", "return", "split_auth_from_netloc", "(", "netloc", ")" ]
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
[ "This", "override", "allows", "the", "auth", "information", "to", "be", "passed", "to", "svn", "via", "the", "--", "username", "and", "--", "password", "options", "instead", "of", "via", "the", "URL", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/subversion.py#L91-L102
train
pypa/pipenv
pipenv/vendor/vistir/contextmanagers.py
cd
def cd(path): """Context manager to temporarily change working directories :param str path: The directory to move into >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' >>> with cd("/home/user/code/otherdir/subdir"): ... print("Changed directory: %s" % os.path.abspath(os.curdir)) Changed directory: /home/user/code/otherdir/subdir >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' """ if not path: return prev_cwd = Path.cwd().as_posix() if isinstance(path, Path): path = path.as_posix() os.chdir(str(path)) try: yield finally: os.chdir(prev_cwd)
python
def cd(path): """Context manager to temporarily change working directories :param str path: The directory to move into >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' >>> with cd("/home/user/code/otherdir/subdir"): ... print("Changed directory: %s" % os.path.abspath(os.curdir)) Changed directory: /home/user/code/otherdir/subdir >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' """ if not path: return prev_cwd = Path.cwd().as_posix() if isinstance(path, Path): path = path.as_posix() os.chdir(str(path)) try: yield finally: os.chdir(prev_cwd)
[ "def", "cd", "(", "path", ")", ":", "if", "not", "path", ":", "return", "prev_cwd", "=", "Path", ".", "cwd", "(", ")", ".", "as_posix", "(", ")", "if", "isinstance", "(", "path", ",", "Path", ")", ":", "path", "=", "path", ".", "as_posix", "(", ")", "os", ".", "chdir", "(", "str", "(", "path", ")", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "prev_cwd", ")" ]
Context manager to temporarily change working directories :param str path: The directory to move into >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo' >>> with cd("/home/user/code/otherdir/subdir"): ... print("Changed directory: %s" % os.path.abspath(os.curdir)) Changed directory: /home/user/code/otherdir/subdir >>> print(os.path.abspath(os.curdir)) '/home/user/code/myrepo'
[ "Context", "manager", "to", "temporarily", "change", "working", "directories" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L63-L85
train
pypa/pipenv
pipenv/vendor/vistir/contextmanagers.py
spinner
def spinner( spinner_name=None, start_text=None, handler_map=None, nospin=False, write_to_stdout=True, ): """Get a spinner object or a dummy spinner to wrap a context. :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"}) :param str start_text: Text to start off the spinner with (default: {None}) :param dict handler_map: Handler map for signals to be handled gracefully (default: {None}) :param bool nospin: If true, use the dummy spinner (default: {False}) :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True) :return: A spinner object which can be manipulated while alive :rtype: :class:`~vistir.spin.VistirSpinner` Raises: RuntimeError -- Raised if the spinner extra is not installed """ from .spin import create_spinner has_yaspin = None try: import yaspin except ImportError: has_yaspin = False if not nospin: raise RuntimeError( "Failed to import spinner! Reinstall vistir with command:" " pip install --upgrade vistir[spinner]" ) else: spinner_name = "" else: has_yaspin = True spinner_name = "" use_yaspin = (has_yaspin is False) or (nospin is True) if has_yaspin is None or has_yaspin is True and not nospin: use_yaspin = True if start_text is None and use_yaspin is True: start_text = "Running..." with create_spinner( spinner_name=spinner_name, text=start_text, handler_map=handler_map, nospin=nospin, use_yaspin=use_yaspin, write_to_stdout=write_to_stdout, ) as _spinner: yield _spinner
python
def spinner( spinner_name=None, start_text=None, handler_map=None, nospin=False, write_to_stdout=True, ): """Get a spinner object or a dummy spinner to wrap a context. :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"}) :param str start_text: Text to start off the spinner with (default: {None}) :param dict handler_map: Handler map for signals to be handled gracefully (default: {None}) :param bool nospin: If true, use the dummy spinner (default: {False}) :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True) :return: A spinner object which can be manipulated while alive :rtype: :class:`~vistir.spin.VistirSpinner` Raises: RuntimeError -- Raised if the spinner extra is not installed """ from .spin import create_spinner has_yaspin = None try: import yaspin except ImportError: has_yaspin = False if not nospin: raise RuntimeError( "Failed to import spinner! Reinstall vistir with command:" " pip install --upgrade vistir[spinner]" ) else: spinner_name = "" else: has_yaspin = True spinner_name = "" use_yaspin = (has_yaspin is False) or (nospin is True) if has_yaspin is None or has_yaspin is True and not nospin: use_yaspin = True if start_text is None and use_yaspin is True: start_text = "Running..." with create_spinner( spinner_name=spinner_name, text=start_text, handler_map=handler_map, nospin=nospin, use_yaspin=use_yaspin, write_to_stdout=write_to_stdout, ) as _spinner: yield _spinner
[ "def", "spinner", "(", "spinner_name", "=", "None", ",", "start_text", "=", "None", ",", "handler_map", "=", "None", ",", "nospin", "=", "False", ",", "write_to_stdout", "=", "True", ",", ")", ":", "from", ".", "spin", "import", "create_spinner", "has_yaspin", "=", "None", "try", ":", "import", "yaspin", "except", "ImportError", ":", "has_yaspin", "=", "False", "if", "not", "nospin", ":", "raise", "RuntimeError", "(", "\"Failed to import spinner! Reinstall vistir with command:\"", "\" pip install --upgrade vistir[spinner]\"", ")", "else", ":", "spinner_name", "=", "\"\"", "else", ":", "has_yaspin", "=", "True", "spinner_name", "=", "\"\"", "use_yaspin", "=", "(", "has_yaspin", "is", "False", ")", "or", "(", "nospin", "is", "True", ")", "if", "has_yaspin", "is", "None", "or", "has_yaspin", "is", "True", "and", "not", "nospin", ":", "use_yaspin", "=", "True", "if", "start_text", "is", "None", "and", "use_yaspin", "is", "True", ":", "start_text", "=", "\"Running...\"", "with", "create_spinner", "(", "spinner_name", "=", "spinner_name", ",", "text", "=", "start_text", ",", "handler_map", "=", "handler_map", ",", "nospin", "=", "nospin", ",", "use_yaspin", "=", "use_yaspin", ",", "write_to_stdout", "=", "write_to_stdout", ",", ")", "as", "_spinner", ":", "yield", "_spinner" ]
Get a spinner object or a dummy spinner to wrap a context. :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"}) :param str start_text: Text to start off the spinner with (default: {None}) :param dict handler_map: Handler map for signals to be handled gracefully (default: {None}) :param bool nospin: If true, use the dummy spinner (default: {False}) :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True) :return: A spinner object which can be manipulated while alive :rtype: :class:`~vistir.spin.VistirSpinner` Raises: RuntimeError -- Raised if the spinner extra is not installed
[ "Get", "a", "spinner", "object", "or", "a", "dummy", "spinner", "to", "wrap", "a", "context", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L111-L162
train
pypa/pipenv
pipenv/vendor/vistir/contextmanagers.py
atomic_open_for_write
def atomic_open_for_write(target, binary=False, newline=None, encoding=None): """Atomically open `target` for writing. This is based on Lektor's `atomic_open()` utility, but simplified a lot to handle only writing, and skip many multi-process/thread edge cases handled by Werkzeug. :param str target: Target filename to write :param bool binary: Whether to open in binary mode, default False :param str newline: The newline character to use when writing, determined from system if not supplied :param str encoding: The encoding to use when writing, defaults to system encoding How this works: * Create a temp file (in the same directory of the actual target), and yield for surrounding code to write to it. * If some thing goes wrong, try to remove the temp file. The actual target is not touched whatsoever. * If everything goes well, close the temp file, and replace the actual target with this new file. .. code:: python >>> fn = "test_file.txt" >>> def read_test_file(filename=fn): with open(filename, 'r') as fh: print(fh.read().strip()) >>> with open(fn, "w") as fh: fh.write("this is some test text") >>> read_test_file() this is some test text >>> def raise_exception_while_writing(filename): with open(filename, "w") as fh: fh.write("writing some new text") raise RuntimeError("Uh oh, hope your file didn't get overwritten") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: Uh oh, hope your file didn't get overwritten >>> read_test_file() writing some new text # Now try with vistir >>> def raise_exception_while_writing(filename): with vistir.contextmanagers.atomic_open_for_write(filename) as fh: fh.write("Overwriting all the text from before with even newer text") raise RuntimeError("But did it get overwritten now?") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: But did it get overwritten now? >>> read_test_file() writing some new text """ mode = "w+b" if binary else "w" f = NamedTemporaryFile( dir=os.path.dirname(target), prefix=".__atomic-write", mode=mode, encoding=encoding, newline=newline, delete=False, ) # set permissions to 0644 os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: yield f except BaseException: f.close() try: os.remove(f.name) except OSError: pass raise else: f.close() try: os.remove(target) # This is needed on Windows. except OSError: pass os.rename(f.name, target)
python
def atomic_open_for_write(target, binary=False, newline=None, encoding=None): """Atomically open `target` for writing. This is based on Lektor's `atomic_open()` utility, but simplified a lot to handle only writing, and skip many multi-process/thread edge cases handled by Werkzeug. :param str target: Target filename to write :param bool binary: Whether to open in binary mode, default False :param str newline: The newline character to use when writing, determined from system if not supplied :param str encoding: The encoding to use when writing, defaults to system encoding How this works: * Create a temp file (in the same directory of the actual target), and yield for surrounding code to write to it. * If some thing goes wrong, try to remove the temp file. The actual target is not touched whatsoever. * If everything goes well, close the temp file, and replace the actual target with this new file. .. code:: python >>> fn = "test_file.txt" >>> def read_test_file(filename=fn): with open(filename, 'r') as fh: print(fh.read().strip()) >>> with open(fn, "w") as fh: fh.write("this is some test text") >>> read_test_file() this is some test text >>> def raise_exception_while_writing(filename): with open(filename, "w") as fh: fh.write("writing some new text") raise RuntimeError("Uh oh, hope your file didn't get overwritten") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: Uh oh, hope your file didn't get overwritten >>> read_test_file() writing some new text # Now try with vistir >>> def raise_exception_while_writing(filename): with vistir.contextmanagers.atomic_open_for_write(filename) as fh: fh.write("Overwriting all the text from before with even newer text") raise RuntimeError("But did it get overwritten now?") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: But did it get overwritten now? >>> read_test_file() writing some new text """ mode = "w+b" if binary else "w" f = NamedTemporaryFile( dir=os.path.dirname(target), prefix=".__atomic-write", mode=mode, encoding=encoding, newline=newline, delete=False, ) # set permissions to 0644 os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) try: yield f except BaseException: f.close() try: os.remove(f.name) except OSError: pass raise else: f.close() try: os.remove(target) # This is needed on Windows. except OSError: pass os.rename(f.name, target)
[ "def", "atomic_open_for_write", "(", "target", ",", "binary", "=", "False", ",", "newline", "=", "None", ",", "encoding", "=", "None", ")", ":", "mode", "=", "\"w+b\"", "if", "binary", "else", "\"w\"", "f", "=", "NamedTemporaryFile", "(", "dir", "=", "os", ".", "path", ".", "dirname", "(", "target", ")", ",", "prefix", "=", "\".__atomic-write\"", ",", "mode", "=", "mode", ",", "encoding", "=", "encoding", ",", "newline", "=", "newline", ",", "delete", "=", "False", ",", ")", "# set permissions to 0644", "os", ".", "chmod", "(", "f", ".", "name", ",", "stat", ".", "S_IWUSR", "|", "stat", ".", "S_IRUSR", "|", "stat", ".", "S_IRGRP", "|", "stat", ".", "S_IROTH", ")", "try", ":", "yield", "f", "except", "BaseException", ":", "f", ".", "close", "(", ")", "try", ":", "os", ".", "remove", "(", "f", ".", "name", ")", "except", "OSError", ":", "pass", "raise", "else", ":", "f", ".", "close", "(", ")", "try", ":", "os", ".", "remove", "(", "target", ")", "# This is needed on Windows.", "except", "OSError", ":", "pass", "os", ".", "rename", "(", "f", ".", "name", ",", "target", ")" ]
Atomically open `target` for writing. This is based on Lektor's `atomic_open()` utility, but simplified a lot to handle only writing, and skip many multi-process/thread edge cases handled by Werkzeug. :param str target: Target filename to write :param bool binary: Whether to open in binary mode, default False :param str newline: The newline character to use when writing, determined from system if not supplied :param str encoding: The encoding to use when writing, defaults to system encoding How this works: * Create a temp file (in the same directory of the actual target), and yield for surrounding code to write to it. * If some thing goes wrong, try to remove the temp file. The actual target is not touched whatsoever. * If everything goes well, close the temp file, and replace the actual target with this new file. .. code:: python >>> fn = "test_file.txt" >>> def read_test_file(filename=fn): with open(filename, 'r') as fh: print(fh.read().strip()) >>> with open(fn, "w") as fh: fh.write("this is some test text") >>> read_test_file() this is some test text >>> def raise_exception_while_writing(filename): with open(filename, "w") as fh: fh.write("writing some new text") raise RuntimeError("Uh oh, hope your file didn't get overwritten") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: Uh oh, hope your file didn't get overwritten >>> read_test_file() writing some new text # Now try with vistir >>> def raise_exception_while_writing(filename): with vistir.contextmanagers.atomic_open_for_write(filename) as fh: fh.write("Overwriting all the text from before with even newer text") raise RuntimeError("But did it get overwritten now?") >>> raise_exception_while_writing(fn) Traceback (most recent call last): ... RuntimeError: But did it get overwritten now? >>> read_test_file() writing some new text
[ "Atomically", "open", "target", "for", "writing", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L166-L252
train
pypa/pipenv
pipenv/vendor/vistir/contextmanagers.py
open_file
def open_file(link, session=None, stream=True): """ Open local or remote file for reading. :type link: pip._internal.index.Link or str :type session: requests.Session :param bool stream: Try to stream if remote, default True :raises ValueError: If link points to a local directory. :return: a context manager to the opened file-like object """ if not isinstance(link, six.string_types): try: link = link.url_without_fragment except AttributeError: raise ValueError("Cannot parse url from unkown type: {0!r}".format(link)) if not is_valid_url(link) and os.path.exists(link): link = path_to_url(link) if is_file_url(link): # Local URL local_path = url_to_path(link) if os.path.isdir(local_path): raise ValueError("Cannot open directory for read: {}".format(link)) else: with io.open(local_path, "rb") as local_file: yield local_file else: # Remote URL headers = {"Accept-Encoding": "identity"} if not session: from requests import Session session = Session() with session.get(link, headers=headers, stream=stream) as resp: try: raw = getattr(resp, "raw", None) result = raw if raw else resp yield result finally: if raw: conn = getattr(raw, "_connection") if conn is not None: conn.close() result.close()
python
def open_file(link, session=None, stream=True): """ Open local or remote file for reading. :type link: pip._internal.index.Link or str :type session: requests.Session :param bool stream: Try to stream if remote, default True :raises ValueError: If link points to a local directory. :return: a context manager to the opened file-like object """ if not isinstance(link, six.string_types): try: link = link.url_without_fragment except AttributeError: raise ValueError("Cannot parse url from unkown type: {0!r}".format(link)) if not is_valid_url(link) and os.path.exists(link): link = path_to_url(link) if is_file_url(link): # Local URL local_path = url_to_path(link) if os.path.isdir(local_path): raise ValueError("Cannot open directory for read: {}".format(link)) else: with io.open(local_path, "rb") as local_file: yield local_file else: # Remote URL headers = {"Accept-Encoding": "identity"} if not session: from requests import Session session = Session() with session.get(link, headers=headers, stream=stream) as resp: try: raw = getattr(resp, "raw", None) result = raw if raw else resp yield result finally: if raw: conn = getattr(raw, "_connection") if conn is not None: conn.close() result.close()
[ "def", "open_file", "(", "link", ",", "session", "=", "None", ",", "stream", "=", "True", ")", ":", "if", "not", "isinstance", "(", "link", ",", "six", ".", "string_types", ")", ":", "try", ":", "link", "=", "link", ".", "url_without_fragment", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"Cannot parse url from unkown type: {0!r}\"", ".", "format", "(", "link", ")", ")", "if", "not", "is_valid_url", "(", "link", ")", "and", "os", ".", "path", ".", "exists", "(", "link", ")", ":", "link", "=", "path_to_url", "(", "link", ")", "if", "is_file_url", "(", "link", ")", ":", "# Local URL", "local_path", "=", "url_to_path", "(", "link", ")", "if", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "raise", "ValueError", "(", "\"Cannot open directory for read: {}\"", ".", "format", "(", "link", ")", ")", "else", ":", "with", "io", ".", "open", "(", "local_path", ",", "\"rb\"", ")", "as", "local_file", ":", "yield", "local_file", "else", ":", "# Remote URL", "headers", "=", "{", "\"Accept-Encoding\"", ":", "\"identity\"", "}", "if", "not", "session", ":", "from", "requests", "import", "Session", "session", "=", "Session", "(", ")", "with", "session", ".", "get", "(", "link", ",", "headers", "=", "headers", ",", "stream", "=", "stream", ")", "as", "resp", ":", "try", ":", "raw", "=", "getattr", "(", "resp", ",", "\"raw\"", ",", "None", ")", "result", "=", "raw", "if", "raw", "else", "resp", "yield", "result", "finally", ":", "if", "raw", ":", "conn", "=", "getattr", "(", "raw", ",", "\"_connection\"", ")", "if", "conn", "is", "not", "None", ":", "conn", ".", "close", "(", ")", "result", ".", "close", "(", ")" ]
Open local or remote file for reading. :type link: pip._internal.index.Link or str :type session: requests.Session :param bool stream: Try to stream if remote, default True :raises ValueError: If link points to a local directory. :return: a context manager to the opened file-like object
[ "Open", "local", "or", "remote", "file", "for", "reading", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L256-L300
train
pypa/pipenv
pipenv/vendor/vistir/contextmanagers.py
replaced_stream
def replaced_stream(stream_name): """ Context manager to temporarily swap out *stream_name* with a stream wrapper. :param str stream_name: The name of a sys stream to wrap :returns: A ``StreamWrapper`` replacement, temporarily >>> orig_stdout = sys.stdout >>> with replaced_stream("stdout") as stdout: ... sys.stdout.write("hello") ... assert stdout.getvalue() == "hello" >>> sys.stdout.write("hello") 'hello' """ orig_stream = getattr(sys, stream_name) new_stream = six.StringIO() try: setattr(sys, stream_name, new_stream) yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stream)
python
def replaced_stream(stream_name): """ Context manager to temporarily swap out *stream_name* with a stream wrapper. :param str stream_name: The name of a sys stream to wrap :returns: A ``StreamWrapper`` replacement, temporarily >>> orig_stdout = sys.stdout >>> with replaced_stream("stdout") as stdout: ... sys.stdout.write("hello") ... assert stdout.getvalue() == "hello" >>> sys.stdout.write("hello") 'hello' """ orig_stream = getattr(sys, stream_name) new_stream = six.StringIO() try: setattr(sys, stream_name, new_stream) yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stream)
[ "def", "replaced_stream", "(", "stream_name", ")", ":", "orig_stream", "=", "getattr", "(", "sys", ",", "stream_name", ")", "new_stream", "=", "six", ".", "StringIO", "(", ")", "try", ":", "setattr", "(", "sys", ",", "stream_name", ",", "new_stream", ")", "yield", "getattr", "(", "sys", ",", "stream_name", ")", "finally", ":", "setattr", "(", "sys", ",", "stream_name", ",", "orig_stream", ")" ]
Context manager to temporarily swap out *stream_name* with a stream wrapper. :param str stream_name: The name of a sys stream to wrap :returns: A ``StreamWrapper`` replacement, temporarily >>> orig_stdout = sys.stdout >>> with replaced_stream("stdout") as stdout: ... sys.stdout.write("hello") ... assert stdout.getvalue() == "hello" >>> sys.stdout.write("hello") 'hello'
[ "Context", "manager", "to", "temporarily", "swap", "out", "*", "stream_name", "*", "with", "a", "stream", "wrapper", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/contextmanagers.py#L304-L325
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.read_nonblocking
def read_nonblocking(self, size=1, timeout=None): """This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored. """ try: s = os.read(self.child_fd, size) except OSError as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Empty string style platform.') s = self._decoder.decode(s, final=False) self._log(s, 'read') return s
python
def read_nonblocking(self, size=1, timeout=None): """This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored. """ try: s = os.read(self.child_fd, size) except OSError as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF self.flag_eof = True raise EOF('End Of File (EOF). Empty string style platform.') s = self._decoder.decode(s, final=False) self._log(s, 'read') return s
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "None", ")", ":", "try", ":", "s", "=", "os", ".", "read", "(", "self", ".", "child_fd", ",", "size", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "args", "[", "0", "]", "==", "errno", ".", "EIO", ":", "# Linux-style EOF", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF). Exception style platform.'", ")", "raise", "if", "s", "==", "b''", ":", "# BSD-style EOF", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF). Empty string style platform.'", ")", "s", "=", "self", ".", "_decoder", ".", "decode", "(", "s", ",", "final", "=", "False", ")", "self", ".", "_log", "(", "s", ",", "'read'", ")", "return", "s" ]
This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored.
[ "This", "reads", "data", "from", "the", "file", "descriptor", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L157-L180
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.compile_pattern_list
def compile_pattern_list(self, patterns): '''This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ... ''' if patterns is None: return [] if not isinstance(patterns, list): patterns = [patterns] # Allow dot to match \n compile_flags = re.DOTALL if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for idx, p in enumerate(patterns): if isinstance(p, self.allowed_string_types): p = self._coerce_expect_string(p) compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif isinstance(p, type(re.compile(''))): compiled_pattern_list.append(p) else: self._pattern_type_err(p) return compiled_pattern_list
python
def compile_pattern_list(self, patterns): '''This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ... ''' if patterns is None: return [] if not isinstance(patterns, list): patterns = [patterns] # Allow dot to match \n compile_flags = re.DOTALL if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for idx, p in enumerate(patterns): if isinstance(p, self.allowed_string_types): p = self._coerce_expect_string(p) compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif isinstance(p, type(re.compile(''))): compiled_pattern_list.append(p) else: self._pattern_type_err(p) return compiled_pattern_list
[ "def", "compile_pattern_list", "(", "self", ",", "patterns", ")", ":", "if", "patterns", "is", "None", ":", "return", "[", "]", "if", "not", "isinstance", "(", "patterns", ",", "list", ")", ":", "patterns", "=", "[", "patterns", "]", "# Allow dot to match \\n", "compile_flags", "=", "re", ".", "DOTALL", "if", "self", ".", "ignorecase", ":", "compile_flags", "=", "compile_flags", "|", "re", ".", "IGNORECASE", "compiled_pattern_list", "=", "[", "]", "for", "idx", ",", "p", "in", "enumerate", "(", "patterns", ")", ":", "if", "isinstance", "(", "p", ",", "self", ".", "allowed_string_types", ")", ":", "p", "=", "self", ".", "_coerce_expect_string", "(", "p", ")", "compiled_pattern_list", ".", "append", "(", "re", ".", "compile", "(", "p", ",", "compile_flags", ")", ")", "elif", "p", "is", "EOF", ":", "compiled_pattern_list", ".", "append", "(", "EOF", ")", "elif", "p", "is", "TIMEOUT", ":", "compiled_pattern_list", ".", "append", "(", "TIMEOUT", ")", "elif", "isinstance", "(", "p", ",", "type", "(", "re", ".", "compile", "(", "''", ")", ")", ")", ":", "compiled_pattern_list", ".", "append", "(", "p", ")", "else", ":", "self", ".", "_pattern_type_err", "(", "p", ")", "return", "compiled_pattern_list" ]
This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ...
[ "This", "compiles", "a", "pattern", "-", "string", "or", "a", "list", "of", "pattern", "-", "strings", ".", "Patterns", "must", "be", "a", "StringType", "EOF", "TIMEOUT", "SRE_Pattern", "or", "a", "list", "of", "those", ".", "Patterns", "may", "also", "be", "None", "which", "results", "in", "an", "empty", "list", "(", "you", "might", "do", "this", "if", "waiting", "for", "an", "EOF", "or", "TIMEOUT", "condition", "without", "expecting", "any", "pattern", ")", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L192-L238
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.expect
def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect(['bar', 'foo', 'foobar']) # returns 1('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect(['foobar', 'foo']) # returns 0('foobar') if all input is available at once, # but returns 1('foo') if parts of the final 'bar' arrive late When a match is found for the given pattern, the class instance attribute *match* becomes an re.MatchObject result. Should an EOF or TIMEOUT pattern match, then the match attribute will be an instance of that exception class. The pairing before and after class instance attributes are views of the data preceding and following the matching pattern. On general exception, class attribute *before* is all data received up to the exception, while *match* and *after* attributes are value None. When the keyword argument timeout is -1 (default), then TIMEOUT will raise after the default value specified by the class timeout attribute. When None, TIMEOUT will not be raised and may block indefinitely until match. When the keyword argument searchwindowsize is -1 (default), then the value specified by the class maxread attribute is used. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect(['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect(pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). On Python 3.4, or Python 3.3 with asyncio installed, passing ``async_=True`` will make this return an :mod:`asyncio` coroutine, which you can yield from to get the same result that this method would normally give directly. So, inside a coroutine, you can replace this code:: index = p.expect(patterns) With this non-blocking form:: index = yield from p.expect(patterns, async_=True) ''' if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_list(compiled_pattern_list, timeout, searchwindowsize, async_)
python
def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect(['bar', 'foo', 'foobar']) # returns 1('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect(['foobar', 'foo']) # returns 0('foobar') if all input is available at once, # but returns 1('foo') if parts of the final 'bar' arrive late When a match is found for the given pattern, the class instance attribute *match* becomes an re.MatchObject result. Should an EOF or TIMEOUT pattern match, then the match attribute will be an instance of that exception class. The pairing before and after class instance attributes are views of the data preceding and following the matching pattern. On general exception, class attribute *before* is all data received up to the exception, while *match* and *after* attributes are value None. When the keyword argument timeout is -1 (default), then TIMEOUT will raise after the default value specified by the class timeout attribute. When None, TIMEOUT will not be raised and may block indefinitely until match. When the keyword argument searchwindowsize is -1 (default), then the value specified by the class maxread attribute is used. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect(['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect(pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). On Python 3.4, or Python 3.3 with asyncio installed, passing ``async_=True`` will make this return an :mod:`asyncio` coroutine, which you can yield from to get the same result that this method would normally give directly. So, inside a coroutine, you can replace this code:: index = p.expect(patterns) With this non-blocking form:: index = yield from p.expect(patterns, async_=True) ''' if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_list(compiled_pattern_list, timeout, searchwindowsize, async_)
[ "def", "expect", "(", "self", ",", "pattern", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ",", "async_", "=", "False", ",", "*", "*", "kw", ")", ":", "if", "'async'", "in", "kw", ":", "async_", "=", "kw", ".", "pop", "(", "'async'", ")", "if", "kw", ":", "raise", "TypeError", "(", "\"Unknown keyword arguments: {}\"", ".", "format", "(", "kw", ")", ")", "compiled_pattern_list", "=", "self", ".", "compile_pattern_list", "(", "pattern", ")", "return", "self", ".", "expect_list", "(", "compiled_pattern_list", ",", "timeout", ",", "searchwindowsize", ",", "async_", ")" ]
This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect(['bar', 'foo', 'foobar']) # returns 1('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect(['foobar', 'foo']) # returns 0('foobar') if all input is available at once, # but returns 1('foo') if parts of the final 'bar' arrive late When a match is found for the given pattern, the class instance attribute *match* becomes an re.MatchObject result. Should an EOF or TIMEOUT pattern match, then the match attribute will be an instance of that exception class. The pairing before and after class instance attributes are views of the data preceding and following the matching pattern. On general exception, class attribute *before* is all data received up to the exception, while *match* and *after* attributes are value None. When the keyword argument timeout is -1 (default), then TIMEOUT will raise after the default value specified by the class timeout attribute. When None, TIMEOUT will not be raised and may block indefinitely until match. When the keyword argument searchwindowsize is -1 (default), then the value specified by the class maxread attribute is used. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect(['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect(pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). On Python 3.4, or Python 3.3 with asyncio installed, passing ``async_=True`` will make this return an :mod:`asyncio` coroutine, which you can yield from to get the same result that this method would normally give directly. So, inside a coroutine, you can replace this code:: index = p.expect(patterns) With this non-blocking form:: index = yield from p.expect(patterns, async_=True)
[ "This", "seeks", "through", "the", "stream", "until", "a", "pattern", "is", "matched", ".", "The", "pattern", "is", "overloaded", "and", "may", "take", "several", "types", ".", "The", "pattern", "can", "be", "a", "StringType", "EOF", "a", "compiled", "re", "or", "a", "list", "of", "any", "of", "those", "types", ".", "Strings", "will", "be", "compiled", "to", "re", "types", ".", "This", "returns", "the", "index", "into", "the", "pattern", "list", ".", "If", "the", "pattern", "was", "not", "a", "list", "this", "returns", "index", "0", "on", "a", "successful", "match", ".", "This", "may", "raise", "exceptions", "for", "EOF", "or", "TIMEOUT", ".", "To", "avoid", "the", "EOF", "or", "TIMEOUT", "exceptions", "add", "EOF", "or", "TIMEOUT", "to", "the", "pattern", "list", ".", "That", "will", "cause", "expect", "to", "match", "an", "EOF", "or", "TIMEOUT", "condition", "instead", "of", "raising", "an", "exception", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L240-L341
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.expect_list
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. ''' if timeout == -1: timeout = self.timeout if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) exp = Expecter(self, searcher_re(pattern_list), searchwindowsize) if async_: from ._async import expect_async return expect_async(exp, timeout) else: return exp.expect_loop(timeout)
python
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. ''' if timeout == -1: timeout = self.timeout if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) exp = Expecter(self, searcher_re(pattern_list), searchwindowsize) if async_: from ._async import expect_async return expect_async(exp, timeout) else: return exp.expect_loop(timeout)
[ "def", "expect_list", "(", "self", ",", "pattern_list", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ",", "async_", "=", "False", ",", "*", "*", "kw", ")", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "if", "'async'", "in", "kw", ":", "async_", "=", "kw", ".", "pop", "(", "'async'", ")", "if", "kw", ":", "raise", "TypeError", "(", "\"Unknown keyword arguments: {}\"", ".", "format", "(", "kw", ")", ")", "exp", "=", "Expecter", "(", "self", ",", "searcher_re", "(", "pattern_list", ")", ",", "searchwindowsize", ")", "if", "async_", ":", "from", ".", "_async", "import", "expect_async", "return", "expect_async", "(", "exp", ",", "timeout", ")", "else", ":", "return", "exp", ".", "expect_loop", "(", "timeout", ")" ]
This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine.
[ "This", "takes", "a", "list", "of", "compiled", "regular", "expressions", "and", "returns", "the", "index", "into", "the", "pattern_list", "that", "matched", "the", "child", "output", ".", "The", "list", "may", "also", "contain", "EOF", "or", "TIMEOUT", "(", "which", "are", "not", "compiled", "regular", "expressions", ")", ".", "This", "method", "is", "similar", "to", "the", "expect", "()", "method", "except", "that", "expect_list", "()", "does", "not", "recompile", "the", "pattern", "list", "on", "every", "call", ".", "This", "may", "help", "if", "you", "are", "trying", "to", "optimize", "for", "speed", "otherwise", "just", "use", "the", "expect", "()", "method", ".", "This", "is", "called", "by", "expect", "()", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L343-L369
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.expect_exact
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match. Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. ''' if timeout == -1: timeout = self.timeout if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) if (isinstance(pattern_list, self.allowed_string_types) or pattern_list in (TIMEOUT, EOF)): pattern_list = [pattern_list] def prepare_pattern(pattern): if pattern in (TIMEOUT, EOF): return pattern if isinstance(pattern, self.allowed_string_types): return self._coerce_expect_string(pattern) self._pattern_type_err(pattern) try: pattern_list = iter(pattern_list) except TypeError: self._pattern_type_err(pattern_list) pattern_list = [prepare_pattern(p) for p in pattern_list] exp = Expecter(self, searcher_string(pattern_list), searchwindowsize) if async_: from ._async import expect_async return expect_async(exp, timeout) else: return exp.expect_loop(timeout)
python
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match. Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. ''' if timeout == -1: timeout = self.timeout if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) if (isinstance(pattern_list, self.allowed_string_types) or pattern_list in (TIMEOUT, EOF)): pattern_list = [pattern_list] def prepare_pattern(pattern): if pattern in (TIMEOUT, EOF): return pattern if isinstance(pattern, self.allowed_string_types): return self._coerce_expect_string(pattern) self._pattern_type_err(pattern) try: pattern_list = iter(pattern_list) except TypeError: self._pattern_type_err(pattern_list) pattern_list = [prepare_pattern(p) for p in pattern_list] exp = Expecter(self, searcher_string(pattern_list), searchwindowsize) if async_: from ._async import expect_async return expect_async(exp, timeout) else: return exp.expect_loop(timeout)
[ "def", "expect_exact", "(", "self", ",", "pattern_list", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ",", "async_", "=", "False", ",", "*", "*", "kw", ")", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "if", "'async'", "in", "kw", ":", "async_", "=", "kw", ".", "pop", "(", "'async'", ")", "if", "kw", ":", "raise", "TypeError", "(", "\"Unknown keyword arguments: {}\"", ".", "format", "(", "kw", ")", ")", "if", "(", "isinstance", "(", "pattern_list", ",", "self", ".", "allowed_string_types", ")", "or", "pattern_list", "in", "(", "TIMEOUT", ",", "EOF", ")", ")", ":", "pattern_list", "=", "[", "pattern_list", "]", "def", "prepare_pattern", "(", "pattern", ")", ":", "if", "pattern", "in", "(", "TIMEOUT", ",", "EOF", ")", ":", "return", "pattern", "if", "isinstance", "(", "pattern", ",", "self", ".", "allowed_string_types", ")", ":", "return", "self", ".", "_coerce_expect_string", "(", "pattern", ")", "self", ".", "_pattern_type_err", "(", "pattern", ")", "try", ":", "pattern_list", "=", "iter", "(", "pattern_list", ")", "except", "TypeError", ":", "self", ".", "_pattern_type_err", "(", "pattern_list", ")", "pattern_list", "=", "[", "prepare_pattern", "(", "p", ")", "for", "p", "in", "pattern_list", "]", "exp", "=", "Expecter", "(", "self", ",", "searcher_string", "(", "pattern_list", ")", ",", "searchwindowsize", ")", "if", "async_", ":", "from", ".", "_async", "import", "expect_async", "return", "expect_async", "(", "exp", ",", "timeout", ")", "else", ":", "return", "exp", ".", "expect_loop", "(", "timeout", ")" ]
This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match. Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine.
[ "This", "is", "similar", "to", "expect", "()", "but", "uses", "plain", "string", "matching", "instead", "of", "compiled", "regular", "expressions", "in", "pattern_list", ".", "The", "pattern_list", "may", "be", "a", "string", ";", "a", "list", "or", "other", "sequence", "of", "strings", ";", "or", "TIMEOUT", "and", "EOF", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L371-L418
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.expect_loop
def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1): '''This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. ''' exp = Expecter(self, searcher, searchwindowsize) return exp.expect_loop(timeout)
python
def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1): '''This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. ''' exp = Expecter(self, searcher, searchwindowsize) return exp.expect_loop(timeout)
[ "def", "expect_loop", "(", "self", ",", "searcher", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ")", ":", "exp", "=", "Expecter", "(", "self", ",", "searcher", ",", "searchwindowsize", ")", "return", "exp", ".", "expect_loop", "(", "timeout", ")" ]
This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions.
[ "This", "is", "the", "common", "loop", "used", "inside", "expect", ".", "The", "searcher", "should", "be", "an", "instance", "of", "searcher_re", "or", "searcher_string", "which", "describes", "how", "and", "what", "to", "search", "for", "in", "the", "input", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L420-L428
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.read
def read(self, size=-1): '''This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. ''' if size == 0: return self.string_type() if size < 0: # delimiter default is EOF self.expect(self.delimiter) return self.before # I could have done this more directly by not using expect(), but # I deliberately decided to couple read() to expect() so that # I would catch any bugs early and ensure consistent behavior. # It's a little less efficient, but there is less for me to # worry about if I have to later modify read() or expect(). # Note, it's OK if size==-1 in the regex. That just means it # will never match anything in which case we stop only on EOF. cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL) # delimiter default is EOF index = self.expect([cre, self.delimiter]) if index == 0: ### FIXME self.before should be ''. Should I assert this? return self.after return self.before
python
def read(self, size=-1): '''This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. ''' if size == 0: return self.string_type() if size < 0: # delimiter default is EOF self.expect(self.delimiter) return self.before # I could have done this more directly by not using expect(), but # I deliberately decided to couple read() to expect() so that # I would catch any bugs early and ensure consistent behavior. # It's a little less efficient, but there is less for me to # worry about if I have to later modify read() or expect(). # Note, it's OK if size==-1 in the regex. That just means it # will never match anything in which case we stop only on EOF. cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL) # delimiter default is EOF index = self.expect([cre, self.delimiter]) if index == 0: ### FIXME self.before should be ''. Should I assert this? return self.after return self.before
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "0", ":", "return", "self", ".", "string_type", "(", ")", "if", "size", "<", "0", ":", "# delimiter default is EOF", "self", ".", "expect", "(", "self", ".", "delimiter", ")", "return", "self", ".", "before", "# I could have done this more directly by not using expect(), but", "# I deliberately decided to couple read() to expect() so that", "# I would catch any bugs early and ensure consistent behavior.", "# It's a little less efficient, but there is less for me to", "# worry about if I have to later modify read() or expect().", "# Note, it's OK if size==-1 in the regex. That just means it", "# will never match anything in which case we stop only on EOF.", "cre", "=", "re", ".", "compile", "(", "self", ".", "_coerce_expect_string", "(", "'.{%d}'", "%", "size", ")", ",", "re", ".", "DOTALL", ")", "# delimiter default is EOF", "index", "=", "self", ".", "expect", "(", "[", "cre", ",", "self", ".", "delimiter", "]", ")", "if", "index", "==", "0", ":", "### FIXME self.before should be ''. Should I assert this?", "return", "self", ".", "after", "return", "self", ".", "before" ]
This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately.
[ "This", "reads", "at", "most", "size", "bytes", "from", "the", "file", "(", "less", "if", "the", "read", "hits", "EOF", "before", "obtaining", "size", "bytes", ")", ".", "If", "the", "size", "argument", "is", "negative", "or", "omitted", "read", "all", "data", "until", "EOF", "is", "reached", ".", "The", "bytes", "are", "returned", "as", "a", "string", "object", ".", "An", "empty", "string", "is", "returned", "when", "EOF", "is", "encountered", "immediately", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L430-L457
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.readline
def readline(self, size=-1): '''This reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because this is what the pseudotty device returns. So contrary to what you may expect you will receive newlines as \\r\\n. If the size argument is 0 then an empty string is returned. In all other cases the size argument is ignored, which is not standard behavior for a file-like object. ''' if size == 0: return self.string_type() # delimiter default is EOF index = self.expect([self.crlf, self.delimiter]) if index == 0: return self.before + self.crlf else: return self.before
python
def readline(self, size=-1): '''This reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because this is what the pseudotty device returns. So contrary to what you may expect you will receive newlines as \\r\\n. If the size argument is 0 then an empty string is returned. In all other cases the size argument is ignored, which is not standard behavior for a file-like object. ''' if size == 0: return self.string_type() # delimiter default is EOF index = self.expect([self.crlf, self.delimiter]) if index == 0: return self.before + self.crlf else: return self.before
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "0", ":", "return", "self", ".", "string_type", "(", ")", "# delimiter default is EOF", "index", "=", "self", ".", "expect", "(", "[", "self", ".", "crlf", ",", "self", ".", "delimiter", "]", ")", "if", "index", "==", "0", ":", "return", "self", ".", "before", "+", "self", ".", "crlf", "else", ":", "return", "self", ".", "before" ]
This reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because this is what the pseudotty device returns. So contrary to what you may expect you will receive newlines as \\r\\n. If the size argument is 0 then an empty string is returned. In all other cases the size argument is ignored, which is not standard behavior for a file-like object.
[ "This", "reads", "and", "returns", "one", "entire", "line", ".", "The", "newline", "at", "the", "end", "of", "line", "is", "returned", "as", "part", "of", "the", "string", "unless", "the", "file", "ends", "without", "a", "newline", ".", "An", "empty", "string", "is", "returned", "if", "EOF", "is", "encountered", "immediately", ".", "This", "looks", "for", "a", "newline", "as", "a", "CR", "/", "LF", "pair", "(", "\\\\", "r", "\\\\", "n", ")", "even", "on", "UNIX", "because", "this", "is", "what", "the", "pseudotty", "device", "returns", ".", "So", "contrary", "to", "what", "you", "may", "expect", "you", "will", "receive", "newlines", "as", "\\\\", "r", "\\\\", "n", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L459-L478
train
pypa/pipenv
pipenv/vendor/pexpect/spawnbase.py
SpawnBase.readlines
def readlines(self, sizehint=-1): '''This reads until EOF using readline() and returns a list containing the lines thus read. The optional 'sizehint' argument is ignored. Remember, because this reads until EOF that means the child process should have closed its stdout. If you run this method on a child that is still running with its stdout open then this method will block until it timesout.''' lines = [] while True: line = self.readline() if not line: break lines.append(line) return lines
python
def readlines(self, sizehint=-1): '''This reads until EOF using readline() and returns a list containing the lines thus read. The optional 'sizehint' argument is ignored. Remember, because this reads until EOF that means the child process should have closed its stdout. If you run this method on a child that is still running with its stdout open then this method will block until it timesout.''' lines = [] while True: line = self.readline() if not line: break lines.append(line) return lines
[ "def", "readlines", "(", "self", ",", "sizehint", "=", "-", "1", ")", ":", "lines", "=", "[", "]", "while", "True", ":", "line", "=", "self", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "lines", ".", "append", "(", "line", ")", "return", "lines" ]
This reads until EOF using readline() and returns a list containing the lines thus read. The optional 'sizehint' argument is ignored. Remember, because this reads until EOF that means the child process should have closed its stdout. If you run this method on a child that is still running with its stdout open then this method will block until it timesout.
[ "This", "reads", "until", "EOF", "using", "readline", "()", "and", "returns", "a", "list", "containing", "the", "lines", "thus", "read", ".", "The", "optional", "sizehint", "argument", "is", "ignored", ".", "Remember", "because", "this", "reads", "until", "EOF", "that", "means", "the", "child", "process", "should", "have", "closed", "its", "stdout", ".", "If", "you", "run", "this", "method", "on", "a", "child", "that", "is", "still", "running", "with", "its", "stdout", "open", "then", "this", "method", "will", "block", "until", "it", "timesout", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L485-L499
train
pypa/pipenv
pipenv/vendor/click/_termui_impl.py
_length_hint
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except (AttributeError, TypeError): try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, int_types) or \ hint < 0: return None return hint
python
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except (AttributeError, TypeError): try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, int_types) or \ hint < 0: return None return hint
[ "def", "_length_hint", "(", "obj", ")", ":", "try", ":", "return", "len", "(", "obj", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "try", ":", "get_hint", "=", "type", "(", "obj", ")", ".", "__length_hint__", "except", "AttributeError", ":", "return", "None", "try", ":", "hint", "=", "get_hint", "(", "obj", ")", "except", "TypeError", ":", "return", "None", "if", "hint", "is", "NotImplemented", "or", "not", "isinstance", "(", "hint", ",", "int_types", ")", "or", "hint", "<", "0", ":", "return", "None", "return", "hint" ]
Returns the length hint of an object.
[ "Returns", "the", "length", "hint", "of", "an", "object", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L34-L51
train
pypa/pipenv
pipenv/vendor/click/_termui_impl.py
_tempfilepager
def _tempfilepager(generator, cmd, color): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(text) encoding = get_best_encoding(sys.stdout) with open_stream(filename, 'wb')[0] as f: f.write(text.encode(encoding)) try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename)
python
def _tempfilepager(generator, cmd, color): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(text) encoding = get_best_encoding(sys.stdout) with open_stream(filename, 'wb')[0] as f: f.write(text.encode(encoding)) try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename)
[ "def", "_tempfilepager", "(", "generator", ",", "cmd", ",", "color", ")", ":", "import", "tempfile", "filename", "=", "tempfile", ".", "mktemp", "(", ")", "# TODO: This never terminates if the passed generator never terminates.", "text", "=", "\"\"", ".", "join", "(", "generator", ")", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "encoding", "=", "get_best_encoding", "(", "sys", ".", "stdout", ")", "with", "open_stream", "(", "filename", ",", "'wb'", ")", "[", "0", "]", "as", "f", ":", "f", ".", "write", "(", "text", ".", "encode", "(", "encoding", ")", ")", "try", ":", "os", ".", "system", "(", "cmd", "+", "' \"'", "+", "filename", "+", "'\"'", ")", "finally", ":", "os", ".", "unlink", "(", "filename", ")" ]
Page through text by invoking a program on a temporary file.
[ "Page", "through", "text", "by", "invoking", "a", "program", "on", "a", "temporary", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L370-L384
train
pypa/pipenv
pipenv/vendor/click/_termui_impl.py
_nullpager
def _nullpager(stream, generator, color): """Simply print unformatted text. This is the ultimate fallback.""" for text in generator: if not color: text = strip_ansi(text) stream.write(text)
python
def _nullpager(stream, generator, color): """Simply print unformatted text. This is the ultimate fallback.""" for text in generator: if not color: text = strip_ansi(text) stream.write(text)
[ "def", "_nullpager", "(", "stream", ",", "generator", ",", "color", ")", ":", "for", "text", "in", "generator", ":", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "stream", ".", "write", "(", "text", ")" ]
Simply print unformatted text. This is the ultimate fallback.
[ "Simply", "print", "unformatted", "text", ".", "This", "is", "the", "ultimate", "fallback", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L387-L392
train
pypa/pipenv
pipenv/vendor/click/_termui_impl.py
ProgressBar.generator
def generator(self): """ Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. """ if not self.entered: raise RuntimeError('You need to use progress bars in a with block.') if self.is_hidden: for rv in self.iter: yield rv else: for rv in self.iter: self.current_item = rv yield rv self.update(1) self.finish() self.render_progress()
python
def generator(self): """ Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. """ if not self.entered: raise RuntimeError('You need to use progress bars in a with block.') if self.is_hidden: for rv in self.iter: yield rv else: for rv in self.iter: self.current_item = rv yield rv self.update(1) self.finish() self.render_progress()
[ "def", "generator", "(", "self", ")", ":", "if", "not", "self", ".", "entered", ":", "raise", "RuntimeError", "(", "'You need to use progress bars in a with block.'", ")", "if", "self", ".", "is_hidden", ":", "for", "rv", "in", "self", ".", "iter", ":", "yield", "rv", "else", ":", "for", "rv", "in", "self", ".", "iter", ":", "self", ".", "current_item", "=", "rv", "yield", "rv", "self", ".", "update", "(", "1", ")", "self", ".", "finish", "(", ")", "self", ".", "render_progress", "(", ")" ]
Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns.
[ "Returns", "a", "generator", "which", "yields", "the", "items", "added", "to", "the", "bar", "during", "construction", "and", "updates", "the", "progress", "bar", "*", "after", "*", "the", "yielded", "block", "returns", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_termui_impl.py#L272-L290
train
pypa/pipenv
pipenv/progress.py
bar
def bar( it, label="", width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=None, every=1, ): """Progress iterator. Wrap your iterables with it.""" count = len(it) if expected_size is None else expected_size with Bar( label=label, width=width, hide=hide, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=count, every=every, ) as bar: for i, item in enumerate(it): yield item bar.show(i + 1)
python
def bar( it, label="", width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=None, every=1, ): """Progress iterator. Wrap your iterables with it.""" count = len(it) if expected_size is None else expected_size with Bar( label=label, width=width, hide=hide, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=count, every=every, ) as bar: for i, item in enumerate(it): yield item bar.show(i + 1)
[ "def", "bar", "(", "it", ",", "label", "=", "\"\"", ",", "width", "=", "32", ",", "hide", "=", "None", ",", "empty_char", "=", "BAR_EMPTY_CHAR", ",", "filled_char", "=", "BAR_FILLED_CHAR", ",", "expected_size", "=", "None", ",", "every", "=", "1", ",", ")", ":", "count", "=", "len", "(", "it", ")", "if", "expected_size", "is", "None", "else", "expected_size", "with", "Bar", "(", "label", "=", "label", ",", "width", "=", "width", ",", "hide", "=", "hide", ",", "empty_char", "=", "BAR_EMPTY_CHAR", ",", "filled_char", "=", "BAR_FILLED_CHAR", ",", "expected_size", "=", "count", ",", "every", "=", "every", ",", ")", "as", "bar", ":", "for", "i", ",", "item", "in", "enumerate", "(", "it", ")", ":", "yield", "item", "bar", ".", "show", "(", "i", "+", "1", ")" ]
Progress iterator. Wrap your iterables with it.
[ "Progress", "iterator", ".", "Wrap", "your", "iterables", "with", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/progress.py#L154-L178
train
pypa/pipenv
pipenv/progress.py
dots
def dots(it, label="", hide=None, every=1): """Progress iterator. Prints a dot for each item being iterated""" count = 0 if not hide: STREAM.write(label) for i, item in enumerate(it): if not hide: if i % every == 0: # True every "every" updates STREAM.write(DOTS_CHAR) sys.stderr.flush() count += 1 yield item STREAM.write("\n") STREAM.flush()
python
def dots(it, label="", hide=None, every=1): """Progress iterator. Prints a dot for each item being iterated""" count = 0 if not hide: STREAM.write(label) for i, item in enumerate(it): if not hide: if i % every == 0: # True every "every" updates STREAM.write(DOTS_CHAR) sys.stderr.flush() count += 1 yield item STREAM.write("\n") STREAM.flush()
[ "def", "dots", "(", "it", ",", "label", "=", "\"\"", ",", "hide", "=", "None", ",", "every", "=", "1", ")", ":", "count", "=", "0", "if", "not", "hide", ":", "STREAM", ".", "write", "(", "label", ")", "for", "i", ",", "item", "in", "enumerate", "(", "it", ")", ":", "if", "not", "hide", ":", "if", "i", "%", "every", "==", "0", ":", "# True every \"every\" updates", "STREAM", ".", "write", "(", "DOTS_CHAR", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "count", "+=", "1", "yield", "item", "STREAM", ".", "write", "(", "\"\\n\"", ")", "STREAM", ".", "flush", "(", ")" ]
Progress iterator. Prints a dot for each item being iterated
[ "Progress", "iterator", ".", "Prints", "a", "dot", "for", "each", "item", "being", "iterated" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/progress.py#L181-L195
train
pypa/pipenv
pipenv/vendor/semver.py
parse
def parse(version): """Parse version to major, minor, patch, pre-release, build parts. :param version: version string :return: dictionary with the keys 'build', 'major', 'minor', 'patch', and 'prerelease'. The prerelease or build keys can be None if not provided :rtype: dict >>> import semver >>> ver = semver.parse('3.4.5-pre.2+build.4') >>> ver['major'] 3 >>> ver['minor'] 4 >>> ver['patch'] 5 >>> ver['prerelease'] 'pre.2' >>> ver['build'] 'build.4' """ match = _REGEX.match(version) if match is None: raise ValueError('%s is not valid SemVer string' % version) version_parts = match.groupdict() version_parts['major'] = int(version_parts['major']) version_parts['minor'] = int(version_parts['minor']) version_parts['patch'] = int(version_parts['patch']) return version_parts
python
def parse(version): """Parse version to major, minor, patch, pre-release, build parts. :param version: version string :return: dictionary with the keys 'build', 'major', 'minor', 'patch', and 'prerelease'. The prerelease or build keys can be None if not provided :rtype: dict >>> import semver >>> ver = semver.parse('3.4.5-pre.2+build.4') >>> ver['major'] 3 >>> ver['minor'] 4 >>> ver['patch'] 5 >>> ver['prerelease'] 'pre.2' >>> ver['build'] 'build.4' """ match = _REGEX.match(version) if match is None: raise ValueError('%s is not valid SemVer string' % version) version_parts = match.groupdict() version_parts['major'] = int(version_parts['major']) version_parts['minor'] = int(version_parts['minor']) version_parts['patch'] = int(version_parts['patch']) return version_parts
[ "def", "parse", "(", "version", ")", ":", "match", "=", "_REGEX", ".", "match", "(", "version", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "'%s is not valid SemVer string'", "%", "version", ")", "version_parts", "=", "match", ".", "groupdict", "(", ")", "version_parts", "[", "'major'", "]", "=", "int", "(", "version_parts", "[", "'major'", "]", ")", "version_parts", "[", "'minor'", "]", "=", "int", "(", "version_parts", "[", "'minor'", "]", ")", "version_parts", "[", "'patch'", "]", "=", "int", "(", "version_parts", "[", "'patch'", "]", ")", "return", "version_parts" ]
Parse version to major, minor, patch, pre-release, build parts. :param version: version string :return: dictionary with the keys 'build', 'major', 'minor', 'patch', and 'prerelease'. The prerelease or build keys can be None if not provided :rtype: dict >>> import semver >>> ver = semver.parse('3.4.5-pre.2+build.4') >>> ver['major'] 3 >>> ver['minor'] 4 >>> ver['patch'] 5 >>> ver['prerelease'] 'pre.2' >>> ver['build'] 'build.4'
[ "Parse", "version", "to", "major", "minor", "patch", "pre", "-", "release", "build", "parts", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L41-L73
train
pypa/pipenv
pipenv/vendor/semver.py
parse_version_info
def parse_version_info(version): """Parse version string to a VersionInfo instance. :param version: version string :return: a :class:`VersionInfo` instance :rtype: :class:`VersionInfo` >>> import semver >>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4") >>> version_info.major 3 >>> version_info.minor 4 >>> version_info.patch 5 >>> version_info.prerelease 'pre.2' >>> version_info.build 'build.4' """ parts = parse(version) version_info = VersionInfo( parts['major'], parts['minor'], parts['patch'], parts['prerelease'], parts['build']) return version_info
python
def parse_version_info(version): """Parse version string to a VersionInfo instance. :param version: version string :return: a :class:`VersionInfo` instance :rtype: :class:`VersionInfo` >>> import semver >>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4") >>> version_info.major 3 >>> version_info.minor 4 >>> version_info.patch 5 >>> version_info.prerelease 'pre.2' >>> version_info.build 'build.4' """ parts = parse(version) version_info = VersionInfo( parts['major'], parts['minor'], parts['patch'], parts['prerelease'], parts['build']) return version_info
[ "def", "parse_version_info", "(", "version", ")", ":", "parts", "=", "parse", "(", "version", ")", "version_info", "=", "VersionInfo", "(", "parts", "[", "'major'", "]", ",", "parts", "[", "'minor'", "]", ",", "parts", "[", "'patch'", "]", ",", "parts", "[", "'prerelease'", "]", ",", "parts", "[", "'build'", "]", ")", "return", "version_info" ]
Parse version string to a VersionInfo instance. :param version: version string :return: a :class:`VersionInfo` instance :rtype: :class:`VersionInfo` >>> import semver >>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4") >>> version_info.major 3 >>> version_info.minor 4 >>> version_info.patch 5 >>> version_info.prerelease 'pre.2' >>> version_info.build 'build.4'
[ "Parse", "version", "string", "to", "a", "VersionInfo", "instance", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L190-L215
train
pypa/pipenv
pipenv/vendor/semver.py
compare
def compare(ver1, ver2): """Compare two versions :param ver1: version string 1 :param ver2: version string 2 :return: The return value is negative if ver1 < ver2, zero if ver1 == ver2 and strictly positive if ver1 > ver2 :rtype: int >>> import semver >>> semver.compare("1.0.0", "2.0.0") -1 >>> semver.compare("2.0.0", "1.0.0") 1 >>> semver.compare("2.0.0", "2.0.0") 0 """ v1, v2 = parse(ver1), parse(ver2) return _compare_by_keys(v1, v2)
python
def compare(ver1, ver2): """Compare two versions :param ver1: version string 1 :param ver2: version string 2 :return: The return value is negative if ver1 < ver2, zero if ver1 == ver2 and strictly positive if ver1 > ver2 :rtype: int >>> import semver >>> semver.compare("1.0.0", "2.0.0") -1 >>> semver.compare("2.0.0", "1.0.0") 1 >>> semver.compare("2.0.0", "2.0.0") 0 """ v1, v2 = parse(ver1), parse(ver2) return _compare_by_keys(v1, v2)
[ "def", "compare", "(", "ver1", ",", "ver2", ")", ":", "v1", ",", "v2", "=", "parse", "(", "ver1", ")", ",", "parse", "(", "ver2", ")", "return", "_compare_by_keys", "(", "v1", ",", "v2", ")" ]
Compare two versions :param ver1: version string 1 :param ver2: version string 2 :return: The return value is negative if ver1 < ver2, zero if ver1 == ver2 and strictly positive if ver1 > ver2 :rtype: int >>> import semver >>> semver.compare("1.0.0", "2.0.0") -1 >>> semver.compare("2.0.0", "1.0.0") 1 >>> semver.compare("2.0.0", "2.0.0") 0
[ "Compare", "two", "versions" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L264-L284
train
pypa/pipenv
pipenv/vendor/semver.py
match
def match(version, match_expr): """Compare two versions through a comparison :param str version: a version string :param str match_expr: operator and version; valid operators are < smaller than > greater than >= greator or equal than <= smaller or equal than == equal != not equal :return: True if the expression matches the version, otherwise False :rtype: bool >>> import semver >>> semver.match("2.0.0", ">=1.0.0") True >>> semver.match("1.0.0", ">1.0.0") False """ prefix = match_expr[:2] if prefix in ('>=', '<=', '==', '!='): match_version = match_expr[2:] elif prefix and prefix[0] in ('>', '<'): prefix = prefix[0] match_version = match_expr[1:] else: raise ValueError("match_expr parameter should be in format <op><ver>, " "where <op> is one of " "['<', '>', '==', '<=', '>=', '!=']. " "You provided: %r" % match_expr) possibilities_dict = { '>': (1,), '<': (-1,), '==': (0,), '!=': (-1, 1), '>=': (0, 1), '<=': (-1, 0) } possibilities = possibilities_dict[prefix] cmp_res = compare(version, match_version) return cmp_res in possibilities
python
def match(version, match_expr): """Compare two versions through a comparison :param str version: a version string :param str match_expr: operator and version; valid operators are < smaller than > greater than >= greator or equal than <= smaller or equal than == equal != not equal :return: True if the expression matches the version, otherwise False :rtype: bool >>> import semver >>> semver.match("2.0.0", ">=1.0.0") True >>> semver.match("1.0.0", ">1.0.0") False """ prefix = match_expr[:2] if prefix in ('>=', '<=', '==', '!='): match_version = match_expr[2:] elif prefix and prefix[0] in ('>', '<'): prefix = prefix[0] match_version = match_expr[1:] else: raise ValueError("match_expr parameter should be in format <op><ver>, " "where <op> is one of " "['<', '>', '==', '<=', '>=', '!=']. " "You provided: %r" % match_expr) possibilities_dict = { '>': (1,), '<': (-1,), '==': (0,), '!=': (-1, 1), '>=': (0, 1), '<=': (-1, 0) } possibilities = possibilities_dict[prefix] cmp_res = compare(version, match_version) return cmp_res in possibilities
[ "def", "match", "(", "version", ",", "match_expr", ")", ":", "prefix", "=", "match_expr", "[", ":", "2", "]", "if", "prefix", "in", "(", "'>='", ",", "'<='", ",", "'=='", ",", "'!='", ")", ":", "match_version", "=", "match_expr", "[", "2", ":", "]", "elif", "prefix", "and", "prefix", "[", "0", "]", "in", "(", "'>'", ",", "'<'", ")", ":", "prefix", "=", "prefix", "[", "0", "]", "match_version", "=", "match_expr", "[", "1", ":", "]", "else", ":", "raise", "ValueError", "(", "\"match_expr parameter should be in format <op><ver>, \"", "\"where <op> is one of \"", "\"['<', '>', '==', '<=', '>=', '!=']. \"", "\"You provided: %r\"", "%", "match_expr", ")", "possibilities_dict", "=", "{", "'>'", ":", "(", "1", ",", ")", ",", "'<'", ":", "(", "-", "1", ",", ")", ",", "'=='", ":", "(", "0", ",", ")", ",", "'!='", ":", "(", "-", "1", ",", "1", ")", ",", "'>='", ":", "(", "0", ",", "1", ")", ",", "'<='", ":", "(", "-", "1", ",", "0", ")", "}", "possibilities", "=", "possibilities_dict", "[", "prefix", "]", "cmp_res", "=", "compare", "(", "version", ",", "match_version", ")", "return", "cmp_res", "in", "possibilities" ]
Compare two versions through a comparison :param str version: a version string :param str match_expr: operator and version; valid operators are < smaller than > greater than >= greator or equal than <= smaller or equal than == equal != not equal :return: True if the expression matches the version, otherwise False :rtype: bool >>> import semver >>> semver.match("2.0.0", ">=1.0.0") True >>> semver.match("1.0.0", ">1.0.0") False
[ "Compare", "two", "versions", "through", "a", "comparison" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L287-L331
train
pypa/pipenv
pipenv/vendor/semver.py
max_ver
def max_ver(ver1, ver2): """Returns the greater version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the greater version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.max_ver("1.0.0", "2.0.0") '2.0.0' """ cmp_res = compare(ver1, ver2) if cmp_res == 0 or cmp_res == 1: return ver1 else: return ver2
python
def max_ver(ver1, ver2): """Returns the greater version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the greater version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.max_ver("1.0.0", "2.0.0") '2.0.0' """ cmp_res = compare(ver1, ver2) if cmp_res == 0 or cmp_res == 1: return ver1 else: return ver2
[ "def", "max_ver", "(", "ver1", ",", "ver2", ")", ":", "cmp_res", "=", "compare", "(", "ver1", ",", "ver2", ")", "if", "cmp_res", "==", "0", "or", "cmp_res", "==", "1", ":", "return", "ver1", "else", ":", "return", "ver2" ]
Returns the greater version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the greater version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.max_ver("1.0.0", "2.0.0") '2.0.0'
[ "Returns", "the", "greater", "version", "of", "two", "versions" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L334-L350
train
pypa/pipenv
pipenv/vendor/semver.py
min_ver
def min_ver(ver1, ver2): """Returns the smaller version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the smaller version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.min_ver("1.0.0", "2.0.0") '1.0.0' """ cmp_res = compare(ver1, ver2) if cmp_res == 0 or cmp_res == -1: return ver1 else: return ver2
python
def min_ver(ver1, ver2): """Returns the smaller version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the smaller version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.min_ver("1.0.0", "2.0.0") '1.0.0' """ cmp_res = compare(ver1, ver2) if cmp_res == 0 or cmp_res == -1: return ver1 else: return ver2
[ "def", "min_ver", "(", "ver1", ",", "ver2", ")", ":", "cmp_res", "=", "compare", "(", "ver1", ",", "ver2", ")", "if", "cmp_res", "==", "0", "or", "cmp_res", "==", "-", "1", ":", "return", "ver1", "else", ":", "return", "ver2" ]
Returns the smaller version of two versions :param ver1: version string 1 :param ver2: version string 2 :return: the smaller version of the two :rtype: :class:`VersionInfo` >>> import semver >>> semver.min_ver("1.0.0", "2.0.0") '1.0.0'
[ "Returns", "the", "smaller", "version", "of", "two", "versions" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L353-L369
train
pypa/pipenv
pipenv/vendor/semver.py
format_version
def format_version(major, minor, patch, prerelease=None, build=None): """Format a version according to the Semantic Versioning specification :param str major: the required major part of a version :param str minor: the required minor part of a version :param str patch: the required patch part of a version :param str prerelease: the optional prerelease part of a version :param str build: the optional build part of a version :return: the formatted string :rtype: str >>> import semver >>> semver.format_version(3, 4, 5, 'pre.2', 'build.4') '3.4.5-pre.2+build.4' """ version = "%d.%d.%d" % (major, minor, patch) if prerelease is not None: version = version + "-%s" % prerelease if build is not None: version = version + "+%s" % build return version
python
def format_version(major, minor, patch, prerelease=None, build=None): """Format a version according to the Semantic Versioning specification :param str major: the required major part of a version :param str minor: the required minor part of a version :param str patch: the required patch part of a version :param str prerelease: the optional prerelease part of a version :param str build: the optional build part of a version :return: the formatted string :rtype: str >>> import semver >>> semver.format_version(3, 4, 5, 'pre.2', 'build.4') '3.4.5-pre.2+build.4' """ version = "%d.%d.%d" % (major, minor, patch) if prerelease is not None: version = version + "-%s" % prerelease if build is not None: version = version + "+%s" % build return version
[ "def", "format_version", "(", "major", ",", "minor", ",", "patch", ",", "prerelease", "=", "None", ",", "build", "=", "None", ")", ":", "version", "=", "\"%d.%d.%d\"", "%", "(", "major", ",", "minor", ",", "patch", ")", "if", "prerelease", "is", "not", "None", ":", "version", "=", "version", "+", "\"-%s\"", "%", "prerelease", "if", "build", "is", "not", "None", ":", "version", "=", "version", "+", "\"+%s\"", "%", "build", "return", "version" ]
Format a version according to the Semantic Versioning specification :param str major: the required major part of a version :param str minor: the required minor part of a version :param str patch: the required patch part of a version :param str prerelease: the optional prerelease part of a version :param str build: the optional build part of a version :return: the formatted string :rtype: str >>> import semver >>> semver.format_version(3, 4, 5, 'pre.2', 'build.4') '3.4.5-pre.2+build.4'
[ "Format", "a", "version", "according", "to", "the", "Semantic", "Versioning", "specification" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/semver.py#L372-L394
train
pypa/pipenv
pipenv/vendor/ptyprocess/ptyprocess.py
_make_eof_intr
def _make_eof_intr(): """Set constants _EOF and _INTR. This avoids doing potentially costly operations on module load. """ global _EOF, _INTR if (_EOF is not None) and (_INTR is not None): return # inherit EOF and INTR definitions from controlling process. try: from termios import VEOF, VINTR fd = None for name in 'stdin', 'stdout': stream = getattr(sys, '__%s__' % name, None) if stream is None or not hasattr(stream, 'fileno'): continue try: fd = stream.fileno() except ValueError: continue if fd is None: # no fd, raise ValueError to fallback on CEOF, CINTR raise ValueError("No stream has a fileno") intr = ord(termios.tcgetattr(fd)[6][VINTR]) eof = ord(termios.tcgetattr(fd)[6][VEOF]) except (ImportError, OSError, IOError, ValueError, termios.error): # unless the controlling process is also not a terminal, # such as cron(1), or when stdin and stdout are both closed. # Fall-back to using CEOF and CINTR. There try: from termios import CEOF, CINTR (intr, eof) = (CINTR, CEOF) except ImportError: # ^C, ^D (intr, eof) = (3, 4) _INTR = _byte(intr) _EOF = _byte(eof)
python
def _make_eof_intr(): """Set constants _EOF and _INTR. This avoids doing potentially costly operations on module load. """ global _EOF, _INTR if (_EOF is not None) and (_INTR is not None): return # inherit EOF and INTR definitions from controlling process. try: from termios import VEOF, VINTR fd = None for name in 'stdin', 'stdout': stream = getattr(sys, '__%s__' % name, None) if stream is None or not hasattr(stream, 'fileno'): continue try: fd = stream.fileno() except ValueError: continue if fd is None: # no fd, raise ValueError to fallback on CEOF, CINTR raise ValueError("No stream has a fileno") intr = ord(termios.tcgetattr(fd)[6][VINTR]) eof = ord(termios.tcgetattr(fd)[6][VEOF]) except (ImportError, OSError, IOError, ValueError, termios.error): # unless the controlling process is also not a terminal, # such as cron(1), or when stdin and stdout are both closed. # Fall-back to using CEOF and CINTR. There try: from termios import CEOF, CINTR (intr, eof) = (CINTR, CEOF) except ImportError: # ^C, ^D (intr, eof) = (3, 4) _INTR = _byte(intr) _EOF = _byte(eof)
[ "def", "_make_eof_intr", "(", ")", ":", "global", "_EOF", ",", "_INTR", "if", "(", "_EOF", "is", "not", "None", ")", "and", "(", "_INTR", "is", "not", "None", ")", ":", "return", "# inherit EOF and INTR definitions from controlling process.", "try", ":", "from", "termios", "import", "VEOF", ",", "VINTR", "fd", "=", "None", "for", "name", "in", "'stdin'", ",", "'stdout'", ":", "stream", "=", "getattr", "(", "sys", ",", "'__%s__'", "%", "name", ",", "None", ")", "if", "stream", "is", "None", "or", "not", "hasattr", "(", "stream", ",", "'fileno'", ")", ":", "continue", "try", ":", "fd", "=", "stream", ".", "fileno", "(", ")", "except", "ValueError", ":", "continue", "if", "fd", "is", "None", ":", "# no fd, raise ValueError to fallback on CEOF, CINTR", "raise", "ValueError", "(", "\"No stream has a fileno\"", ")", "intr", "=", "ord", "(", "termios", ".", "tcgetattr", "(", "fd", ")", "[", "6", "]", "[", "VINTR", "]", ")", "eof", "=", "ord", "(", "termios", ".", "tcgetattr", "(", "fd", ")", "[", "6", "]", "[", "VEOF", "]", ")", "except", "(", "ImportError", ",", "OSError", ",", "IOError", ",", "ValueError", ",", "termios", ".", "error", ")", ":", "# unless the controlling process is also not a terminal,", "# such as cron(1), or when stdin and stdout are both closed.", "# Fall-back to using CEOF and CINTR. There", "try", ":", "from", "termios", "import", "CEOF", ",", "CINTR", "(", "intr", ",", "eof", ")", "=", "(", "CINTR", ",", "CEOF", ")", "except", "ImportError", ":", "# ^C, ^D", "(", "intr", ",", "eof", ")", "=", "(", "3", ",", "4", ")", "_INTR", "=", "_byte", "(", "intr", ")", "_EOF", "=", "_byte", "(", "eof", ")" ]
Set constants _EOF and _INTR. This avoids doing potentially costly operations on module load.
[ "Set", "constants", "_EOF", "and", "_INTR", ".", "This", "avoids", "doing", "potentially", "costly", "operations", "on", "module", "load", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L51-L89
train
pypa/pipenv
pipenv/vendor/ptyprocess/ptyprocess.py
PtyProcess.spawn
def spawn( cls, argv, cwd=None, env=None, echo=True, preexec_fn=None, dimensions=(24, 80)): '''Start the given command in a child process in a pseudo terminal. This does all the fork/exec type of stuff for a pty, and returns an instance of PtyProcess. If preexec_fn is supplied, it will be called with no arguments in the child process before exec-ing the specified command. It may, for instance, set signal handlers to SIG_DFL or SIG_IGN. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used. ''' # Note that it is difficult for this method to fail. # You cannot detect if the child process cannot start. # So the only way you can tell if the child process started # or not is to try to read from the file descriptor. If you get # EOF immediately then it means that the child is already dead. # That may not necessarily be bad because you may have spawned a child # that performs some task; creates no stdout output; and then dies. if not isinstance(argv, (list, tuple)): raise TypeError("Expected a list or tuple for argv, got %r" % argv) # Shallow copy of argv so we can modify it argv = argv[:] command = argv[0] command_with_path = which(command) if command_with_path is None: raise FileNotFoundError('The command was not found or was not ' + 'executable: %s.' % command) command = command_with_path argv[0] = command # [issue #119] To prevent the case where exec fails and the user is # stuck interacting with a python child process instead of whatever # was expected, we implement the solution from # http://stackoverflow.com/a/3703179 to pass the exception to the # parent process # [issue #119] 1. Before forking, open a pipe in the parent process. exec_err_pipe_read, exec_err_pipe_write = os.pipe() if use_native_pty_fork: pid, fd = pty.fork() else: # Use internal fork_pty, for Solaris pid, fd = _fork_pty.fork_pty() # Some platforms must call setwinsize() and setecho() from the # child process, and others from the master process. We do both, # allowing IOError for either. if pid == CHILD: # set window size try: _setwinsize(STDIN_FILENO, *dimensions) except IOError as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY): raise # disable echo if spawn argument echo was unset if not echo: try: _setecho(STDIN_FILENO, False) except (IOError, termios.error) as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY): raise # [issue #119] 3. The child closes the reading end and sets the # close-on-exec flag for the writing end. os.close(exec_err_pipe_read) fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC) # Do not allow child to inherit open file descriptors from parent, # with the exception of the exec_err_pipe_write of the pipe # Impose ceiling on max_fd: AIX bugfix for users with unlimited # nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange() # occasionally raises out of range error max_fd = min(1048576, resource.getrlimit(resource.RLIMIT_NOFILE)[0]) os.closerange(3, exec_err_pipe_write) os.closerange(exec_err_pipe_write+1, max_fd) if cwd is not None: os.chdir(cwd) if preexec_fn is not None: try: preexec_fn() except Exception as e: ename = type(e).__name__ tosend = '{}:0:{}'.format(ename, str(e)) if PY3: tosend = tosend.encode('utf-8') os.write(exec_err_pipe_write, tosend) os.close(exec_err_pipe_write) os._exit(1) try: if env is None: os.execv(command, argv) else: os.execvpe(command, argv, env) except OSError as err: # [issue #119] 5. If exec fails, the child writes the error # code back to the parent using the pipe, then exits. tosend = 'OSError:{}:{}'.format(err.errno, str(err)) if PY3: tosend = tosend.encode('utf-8') os.write(exec_err_pipe_write, tosend) os.close(exec_err_pipe_write) os._exit(os.EX_OSERR) # Parent inst = cls(pid, fd) # Set some informational attributes inst.argv = argv if env is not None: inst.env = env if cwd is not None: inst.launch_dir = cwd # [issue #119] 2. After forking, the parent closes the writing end # of the pipe and reads from the reading end. os.close(exec_err_pipe_write) exec_err_data = os.read(exec_err_pipe_read, 4096) os.close(exec_err_pipe_read) # [issue #119] 6. The parent reads eof (a zero-length read) if the # child successfully performed exec, since close-on-exec made # successful exec close the writing end of the pipe. Or, if exec # failed, the parent reads the error code and can proceed # accordingly. Either way, the parent blocks until the child calls # exec. if len(exec_err_data) != 0: try: errclass, errno_s, errmsg = exec_err_data.split(b':', 2) exctype = getattr(builtins, errclass.decode('ascii'), Exception) exception = exctype(errmsg.decode('utf-8', 'replace')) if exctype is OSError: exception.errno = int(errno_s) except: raise Exception('Subprocess failed, got bad error data: %r' % exec_err_data) else: raise exception try: inst.setwinsize(*dimensions) except IOError as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO): raise return inst
python
def spawn( cls, argv, cwd=None, env=None, echo=True, preexec_fn=None, dimensions=(24, 80)): '''Start the given command in a child process in a pseudo terminal. This does all the fork/exec type of stuff for a pty, and returns an instance of PtyProcess. If preexec_fn is supplied, it will be called with no arguments in the child process before exec-ing the specified command. It may, for instance, set signal handlers to SIG_DFL or SIG_IGN. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used. ''' # Note that it is difficult for this method to fail. # You cannot detect if the child process cannot start. # So the only way you can tell if the child process started # or not is to try to read from the file descriptor. If you get # EOF immediately then it means that the child is already dead. # That may not necessarily be bad because you may have spawned a child # that performs some task; creates no stdout output; and then dies. if not isinstance(argv, (list, tuple)): raise TypeError("Expected a list or tuple for argv, got %r" % argv) # Shallow copy of argv so we can modify it argv = argv[:] command = argv[0] command_with_path = which(command) if command_with_path is None: raise FileNotFoundError('The command was not found or was not ' + 'executable: %s.' % command) command = command_with_path argv[0] = command # [issue #119] To prevent the case where exec fails and the user is # stuck interacting with a python child process instead of whatever # was expected, we implement the solution from # http://stackoverflow.com/a/3703179 to pass the exception to the # parent process # [issue #119] 1. Before forking, open a pipe in the parent process. exec_err_pipe_read, exec_err_pipe_write = os.pipe() if use_native_pty_fork: pid, fd = pty.fork() else: # Use internal fork_pty, for Solaris pid, fd = _fork_pty.fork_pty() # Some platforms must call setwinsize() and setecho() from the # child process, and others from the master process. We do both, # allowing IOError for either. if pid == CHILD: # set window size try: _setwinsize(STDIN_FILENO, *dimensions) except IOError as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY): raise # disable echo if spawn argument echo was unset if not echo: try: _setecho(STDIN_FILENO, False) except (IOError, termios.error) as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY): raise # [issue #119] 3. The child closes the reading end and sets the # close-on-exec flag for the writing end. os.close(exec_err_pipe_read) fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC) # Do not allow child to inherit open file descriptors from parent, # with the exception of the exec_err_pipe_write of the pipe # Impose ceiling on max_fd: AIX bugfix for users with unlimited # nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange() # occasionally raises out of range error max_fd = min(1048576, resource.getrlimit(resource.RLIMIT_NOFILE)[0]) os.closerange(3, exec_err_pipe_write) os.closerange(exec_err_pipe_write+1, max_fd) if cwd is not None: os.chdir(cwd) if preexec_fn is not None: try: preexec_fn() except Exception as e: ename = type(e).__name__ tosend = '{}:0:{}'.format(ename, str(e)) if PY3: tosend = tosend.encode('utf-8') os.write(exec_err_pipe_write, tosend) os.close(exec_err_pipe_write) os._exit(1) try: if env is None: os.execv(command, argv) else: os.execvpe(command, argv, env) except OSError as err: # [issue #119] 5. If exec fails, the child writes the error # code back to the parent using the pipe, then exits. tosend = 'OSError:{}:{}'.format(err.errno, str(err)) if PY3: tosend = tosend.encode('utf-8') os.write(exec_err_pipe_write, tosend) os.close(exec_err_pipe_write) os._exit(os.EX_OSERR) # Parent inst = cls(pid, fd) # Set some informational attributes inst.argv = argv if env is not None: inst.env = env if cwd is not None: inst.launch_dir = cwd # [issue #119] 2. After forking, the parent closes the writing end # of the pipe and reads from the reading end. os.close(exec_err_pipe_write) exec_err_data = os.read(exec_err_pipe_read, 4096) os.close(exec_err_pipe_read) # [issue #119] 6. The parent reads eof (a zero-length read) if the # child successfully performed exec, since close-on-exec made # successful exec close the writing end of the pipe. Or, if exec # failed, the parent reads the error code and can proceed # accordingly. Either way, the parent blocks until the child calls # exec. if len(exec_err_data) != 0: try: errclass, errno_s, errmsg = exec_err_data.split(b':', 2) exctype = getattr(builtins, errclass.decode('ascii'), Exception) exception = exctype(errmsg.decode('utf-8', 'replace')) if exctype is OSError: exception.errno = int(errno_s) except: raise Exception('Subprocess failed, got bad error data: %r' % exec_err_data) else: raise exception try: inst.setwinsize(*dimensions) except IOError as err: if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO): raise return inst
[ "def", "spawn", "(", "cls", ",", "argv", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "echo", "=", "True", ",", "preexec_fn", "=", "None", ",", "dimensions", "=", "(", "24", ",", "80", ")", ")", ":", "# Note that it is difficult for this method to fail.", "# You cannot detect if the child process cannot start.", "# So the only way you can tell if the child process started", "# or not is to try to read from the file descriptor. If you get", "# EOF immediately then it means that the child is already dead.", "# That may not necessarily be bad because you may have spawned a child", "# that performs some task; creates no stdout output; and then dies.", "if", "not", "isinstance", "(", "argv", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Expected a list or tuple for argv, got %r\"", "%", "argv", ")", "# Shallow copy of argv so we can modify it", "argv", "=", "argv", "[", ":", "]", "command", "=", "argv", "[", "0", "]", "command_with_path", "=", "which", "(", "command", ")", "if", "command_with_path", "is", "None", ":", "raise", "FileNotFoundError", "(", "'The command was not found or was not '", "+", "'executable: %s.'", "%", "command", ")", "command", "=", "command_with_path", "argv", "[", "0", "]", "=", "command", "# [issue #119] To prevent the case where exec fails and the user is", "# stuck interacting with a python child process instead of whatever", "# was expected, we implement the solution from", "# http://stackoverflow.com/a/3703179 to pass the exception to the", "# parent process", "# [issue #119] 1. Before forking, open a pipe in the parent process.", "exec_err_pipe_read", ",", "exec_err_pipe_write", "=", "os", ".", "pipe", "(", ")", "if", "use_native_pty_fork", ":", "pid", ",", "fd", "=", "pty", ".", "fork", "(", ")", "else", ":", "# Use internal fork_pty, for Solaris", "pid", ",", "fd", "=", "_fork_pty", ".", "fork_pty", "(", ")", "# Some platforms must call setwinsize() and setecho() from the", "# child process, and others from the master process. We do both,", "# allowing IOError for either.", "if", "pid", "==", "CHILD", ":", "# set window size", "try", ":", "_setwinsize", "(", "STDIN_FILENO", ",", "*", "dimensions", ")", "except", "IOError", "as", "err", ":", "if", "err", ".", "args", "[", "0", "]", "not", "in", "(", "errno", ".", "EINVAL", ",", "errno", ".", "ENOTTY", ")", ":", "raise", "# disable echo if spawn argument echo was unset", "if", "not", "echo", ":", "try", ":", "_setecho", "(", "STDIN_FILENO", ",", "False", ")", "except", "(", "IOError", ",", "termios", ".", "error", ")", "as", "err", ":", "if", "err", ".", "args", "[", "0", "]", "not", "in", "(", "errno", ".", "EINVAL", ",", "errno", ".", "ENOTTY", ")", ":", "raise", "# [issue #119] 3. The child closes the reading end and sets the", "# close-on-exec flag for the writing end.", "os", ".", "close", "(", "exec_err_pipe_read", ")", "fcntl", ".", "fcntl", "(", "exec_err_pipe_write", ",", "fcntl", ".", "F_SETFD", ",", "fcntl", ".", "FD_CLOEXEC", ")", "# Do not allow child to inherit open file descriptors from parent,", "# with the exception of the exec_err_pipe_write of the pipe", "# Impose ceiling on max_fd: AIX bugfix for users with unlimited", "# nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()", "# occasionally raises out of range error", "max_fd", "=", "min", "(", "1048576", ",", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "0", "]", ")", "os", ".", "closerange", "(", "3", ",", "exec_err_pipe_write", ")", "os", ".", "closerange", "(", "exec_err_pipe_write", "+", "1", ",", "max_fd", ")", "if", "cwd", "is", "not", "None", ":", "os", ".", "chdir", "(", "cwd", ")", "if", "preexec_fn", "is", "not", "None", ":", "try", ":", "preexec_fn", "(", ")", "except", "Exception", "as", "e", ":", "ename", "=", "type", "(", "e", ")", ".", "__name__", "tosend", "=", "'{}:0:{}'", ".", "format", "(", "ename", ",", "str", "(", "e", ")", ")", "if", "PY3", ":", "tosend", "=", "tosend", ".", "encode", "(", "'utf-8'", ")", "os", ".", "write", "(", "exec_err_pipe_write", ",", "tosend", ")", "os", ".", "close", "(", "exec_err_pipe_write", ")", "os", ".", "_exit", "(", "1", ")", "try", ":", "if", "env", "is", "None", ":", "os", ".", "execv", "(", "command", ",", "argv", ")", "else", ":", "os", ".", "execvpe", "(", "command", ",", "argv", ",", "env", ")", "except", "OSError", "as", "err", ":", "# [issue #119] 5. If exec fails, the child writes the error", "# code back to the parent using the pipe, then exits.", "tosend", "=", "'OSError:{}:{}'", ".", "format", "(", "err", ".", "errno", ",", "str", "(", "err", ")", ")", "if", "PY3", ":", "tosend", "=", "tosend", ".", "encode", "(", "'utf-8'", ")", "os", ".", "write", "(", "exec_err_pipe_write", ",", "tosend", ")", "os", ".", "close", "(", "exec_err_pipe_write", ")", "os", ".", "_exit", "(", "os", ".", "EX_OSERR", ")", "# Parent", "inst", "=", "cls", "(", "pid", ",", "fd", ")", "# Set some informational attributes", "inst", ".", "argv", "=", "argv", "if", "env", "is", "not", "None", ":", "inst", ".", "env", "=", "env", "if", "cwd", "is", "not", "None", ":", "inst", ".", "launch_dir", "=", "cwd", "# [issue #119] 2. After forking, the parent closes the writing end", "# of the pipe and reads from the reading end.", "os", ".", "close", "(", "exec_err_pipe_write", ")", "exec_err_data", "=", "os", ".", "read", "(", "exec_err_pipe_read", ",", "4096", ")", "os", ".", "close", "(", "exec_err_pipe_read", ")", "# [issue #119] 6. The parent reads eof (a zero-length read) if the", "# child successfully performed exec, since close-on-exec made", "# successful exec close the writing end of the pipe. Or, if exec", "# failed, the parent reads the error code and can proceed", "# accordingly. Either way, the parent blocks until the child calls", "# exec.", "if", "len", "(", "exec_err_data", ")", "!=", "0", ":", "try", ":", "errclass", ",", "errno_s", ",", "errmsg", "=", "exec_err_data", ".", "split", "(", "b':'", ",", "2", ")", "exctype", "=", "getattr", "(", "builtins", ",", "errclass", ".", "decode", "(", "'ascii'", ")", ",", "Exception", ")", "exception", "=", "exctype", "(", "errmsg", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", ")", "if", "exctype", "is", "OSError", ":", "exception", ".", "errno", "=", "int", "(", "errno_s", ")", "except", ":", "raise", "Exception", "(", "'Subprocess failed, got bad error data: %r'", "%", "exec_err_data", ")", "else", ":", "raise", "exception", "try", ":", "inst", ".", "setwinsize", "(", "*", "dimensions", ")", "except", "IOError", "as", "err", ":", "if", "err", ".", "args", "[", "0", "]", "not", "in", "(", "errno", ".", "EINVAL", ",", "errno", ".", "ENOTTY", ",", "errno", ".", "ENXIO", ")", ":", "raise", "return", "inst" ]
Start the given command in a child process in a pseudo terminal. This does all the fork/exec type of stuff for a pty, and returns an instance of PtyProcess. If preexec_fn is supplied, it will be called with no arguments in the child process before exec-ing the specified command. It may, for instance, set signal handlers to SIG_DFL or SIG_IGN. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used.
[ "Start", "the", "given", "command", "in", "a", "child", "process", "in", "a", "pseudo", "terminal", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L179-L338
train