Let us walk on the 3-isogeny graph
Loading...
Searching...
No Matches
pip._vendor.distlib.util Namespace Reference

Data Structures

class  Cache
 
class  cached_property
 
class  Configurator
 
class  CSVBase
 
class  CSVReader
 
class  CSVWriter
 
class  EventMixin
 
class  ExportEntry
 
class  FileOperator
 
class  HTTPSConnection
 
class  HTTPSHandler
 
class  HTTPSOnlyHandler
 
class  Progress
 
class  PyPIRCFile
 
class  SafeTransport
 
class  Sequencer
 
class  ServerProxy
 
class  SubprocessMixin
 
class  Transport
 

Functions

 parse_marker (marker_string)
 
 parse_requirement (req)
 
 get_resources_dests (resources_root, rules)
 
 in_venv ()
 
 get_executable ()
 
 proceed (prompt, allowed_chars, error_prompt=None, default=None)
 
 extract_by_key (d, keys)
 
 read_exports (stream)
 
 write_exports (exports, stream)
 
 tempdir ()
 
 chdir (d)
 
 socket_timeout (seconds=15)
 
 convert_path (pathname)
 
 resolve (module_name, dotted_path)
 
 get_export_entry (specification)
 
 get_cache_base (suffix=None)
 
 path_to_cache_dir (path)
 
 ensure_slash (s)
 
 parse_credentials (netloc)
 
 get_process_umask ()
 
 is_string_sequence (seq)
 
 split_filename (filename, project_name=None)
 
 parse_name_and_version (p)
 
 get_extras (requested, available)
 
 _get_external_data (url)
 
 get_project_data (name)
 
 get_package_data (name, version)
 
 unarchive (archive_filename, dest_dir, format=None, check=True)
 
 zip_dir (directory)
 
 iglob (path_glob)
 
 _iglob (path_glob)
 
 _csv_open (fn, mode, **kwargs)
 
 normalize_name (name)
 
 _load_pypirc (index)
 
 _store_pypirc (index)
 
 get_host_platform ()
 
 get_platform ()
 

Variables

 ssl = None
 
 logger = logging.getLogger(__name__)
 
 IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
 
 VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
 
 COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
 
 MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
 
 OR = re.compile(r'^or\b\s*')
 
 AND = re.compile(r'^and\b\s*')
 
 NON_SPACE = re.compile(r'(\S+)\s*')
 
 STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
 
 ENTRY_RE = re.compile(, re.VERBOSE)
 
 PROJECT_NAME_AND_VERSION
 
 PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
 
 NAME_VERSION_RE
 
str _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
 
tuple ARCHIVE_EXTENSIONS
 
tuple UNITS = ('', 'K', 'M', 'G','T','P')
 
 RICH_GLOB = re.compile(r'\{([^}]*)\}')
 
 _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
 
 _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
 
dict _TARGET_TO_PLAT
 

Function Documentation

◆ _csv_open()

_csv_open (   fn,
  mode,
**  kwargs 
)
protected

Definition at line 1558 of file util.py.

1558def _csv_open(fn, mode, **kwargs):
1559 if sys.version_info[0] < 3:
1560 mode += 'b'
1561 else:
1562 kwargs['newline'] = ''
1563 # Python 3 determines encoding from locale. Force 'utf-8'
1564 # file encoding to match other forced utf-8 encoding
1565 kwargs['encoding'] = 'utf-8'
1566 return open(fn, mode, **kwargs)
1567
1568
for i

References i.

◆ _get_external_data()

_get_external_data (   url)
protected

Definition at line 913 of file util.py.

913def _get_external_data(url):
914 result = {}
915 try:
916 # urlopen might fail if it runs into redirections,
917 # because of Python issue #13696. Fixed in locators
918 # using a custom redirect handler.
919 resp = urlopen(url)
920 headers = resp.info()
921 ct = headers.get('Content-Type')
922 if not ct.startswith('application/json'):
923 logger.debug('Unexpected response for JSON request: %s', ct)
924 else:
925 reader = codecs.getreader('utf-8')(resp)
926 #data = reader.read().decode('utf-8')
927 #result = json.loads(data)
928 result = json.load(reader)
929 except Exception as e:
930 logger.exception('Failed to get external data for %s: %s', url, e)
931 return result
932

References i.

Referenced by pip._vendor.distlib.util.get_package_data(), and pip._vendor.distlib.util.get_project_data().

Here is the caller graph for this function:

◆ _iglob()

_iglob (   path_glob)
protected

Definition at line 1388 of file util.py.

1388def _iglob(path_glob):
1389 rich_path_glob = RICH_GLOB.split(path_glob, 1)
1390 if len(rich_path_glob) > 1:
1391 assert len(rich_path_glob) == 3, rich_path_glob
1392 prefix, set, suffix = rich_path_glob
1393 for item in set.split(','):
1394 for path in _iglob(''.join((prefix, item, suffix))):
1395 yield path
1396 else:
1397 if '**' not in path_glob:
1398 for item in std_iglob(path_glob):
1399 yield item
1400 else:
1401 prefix, radical = path_glob.split('**', 1)
1402 if prefix == '':
1403 prefix = '.'
1404 if radical == '':
1405 radical = '*'
1406 else:
1407 # we support both
1408 radical = radical.lstrip('/')
1409 radical = radical.lstrip('\\')
1410 for path, dir, files in os.walk(prefix):
1411 path = os.path.normpath(path)
1412 for fn in _iglob(os.path.join(path, radical)):
1413 yield fn
1414

References pip._vendor.distlib.util._iglob(), and i.

Referenced by pip._vendor.distlib.util._iglob(), and pip._vendor.distlib.util.iglob().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _load_pypirc()

_load_pypirc (   index)
protected
Read the PyPI access configuration as supported by distutils.

Definition at line 1824 of file util.py.

1824def _load_pypirc(index):
1825 """
1826 Read the PyPI access configuration as supported by distutils.
1827 """
1828 return PyPIRCFile(url=index.url).read()
1829

References i.

◆ _store_pypirc()

_store_pypirc (   index)
protected

Definition at line 1830 of file util.py.

1830def _store_pypirc(index):
1831 PyPIRCFile().update(index.username, index.password)
1832
1833#
1834# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
1835# tweaks
1836#
1837

References i.

◆ chdir()

chdir (   d)

Definition at line 424 of file util.py.

424def chdir(d):
425 cwd = os.getcwd()
426 try:
427 os.chdir(d)
428 yield
429 finally:
430 os.chdir(cwd)
431
432
433@contextlib.contextmanager

References i.

◆ convert_path()

convert_path (   pathname)
Return 'pathname' as a name that will work on the native filesystem.

The path is split on '/' and put back together again using the current
directory separator.  Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem.  Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.

Definition at line 457 of file util.py.

457def convert_path(pathname):
458 """Return 'pathname' as a name that will work on the native filesystem.
459
460 The path is split on '/' and put back together again using the current
461 directory separator. Needed because filenames in the setup script are
462 always supplied in Unix style, and have to be converted to the local
463 convention before we can actually use them in the filesystem. Raises
464 ValueError on non-Unix-ish systems if 'pathname' either starts or
465 ends with a slash.
466 """
467 if os.sep == '/':
468 return pathname
469 if not pathname:
470 return pathname
471 if pathname[0] == '/':
472 raise ValueError("path '%s' cannot be absolute" % pathname)
473 if pathname[-1] == '/':
474 raise ValueError("path '%s' cannot end with '/'" % pathname)
475
476 paths = pathname.split('/')
477 while os.curdir in paths:
479 if not paths:
480 return os.curdir
481 return os.path.join(*paths)
482
483

References i.

◆ ensure_slash()

ensure_slash (   s)

Definition at line 804 of file util.py.

804def ensure_slash(s):
805 if not s.endswith('/'):
806 return s + '/'
807 return s
808
809

References i.

◆ extract_by_key()

extract_by_key (   d,
  keys 
)

Definition at line 340 of file util.py.

340def extract_by_key(d, keys):
341 if isinstance(keys, string_types):
342 keys = keys.split()
343 result = {}
344 for key in keys:
345 if key in d:
346 result[key] = d[key]
347 return result
348

References i.

◆ get_cache_base()

get_cache_base (   suffix = None)
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.

On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.

The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.

Definition at line 746 of file util.py.

746def get_cache_base(suffix=None):
747 """
748 Return the default base location for distlib caches. If the directory does
749 not exist, it is created. Use the suffix provided for the base directory,
750 and default to '.distlib' if it isn't provided.
751
752 On Windows, if LOCALAPPDATA is defined in the environment, then it is
753 assumed to be a directory, and will be the parent directory of the result.
754 On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
755 directory - using os.expanduser('~') - will be the parent directory of
756 the result.
757
758 The result is just the directory '.distlib' in the parent directory as
759 determined above, or with the name specified with ``suffix``.
760 """
761 if suffix is None:
762 suffix = '.distlib'
763 if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
764 result = os.path.expandvars('$localappdata')
765 else:
766 # Assume posix, or old Windows
767 result = os.path.expanduser('~')
768 # we use 'isdir' instead of 'exists', because we want to
769 # fail if there's a file with that name
770 if os.path.isdir(result):
771 usable = os.access(result, os.W_OK)
772 if not usable:
773 logger.warning('Directory exists but is not writable: %s', result)
774 else:
775 try:
776 os.makedirs(result)
777 usable = True
778 except OSError:
779 logger.warning('Unable to create %s', result, exc_info=True)
780 usable = False
781 if not usable:
782 result = tempfile.mkdtemp()
783 logger.warning('Default location unusable, using %s', result)
784 return os.path.join(result, suffix)
785
786

References i.

◆ get_executable()

get_executable ( )

Definition at line 306 of file util.py.

306def get_executable():
307# The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
308# changes to the stub launcher mean that sys.executable always points
309# to the stub on OS X
310# if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
311# in os.environ):
312# result = os.environ['__PYVENV_LAUNCHER__']
313# else:
314# result = sys.executable
315# return result
316 # Avoid normcasing: see issue #143
317 # result = os.path.normcase(sys.executable)
318 result = sys.executable
319 if not isinstance(result, text_type):
320 result = fsdecode(result)
321 return result
322
323

References i.

◆ get_export_entry()

get_export_entry (   specification)

Definition at line 715 of file util.py.

715def get_export_entry(specification):
716 m = ENTRY_RE.search(specification)
717 if not m:
718 result = None
719 if '[' in specification or ']' in specification:
720 raise DistlibException("Invalid specification "
721 "'%s'" % specification)
722 else:
723 d = m.groupdict()
724 name = d['name']
725 path = d['callable']
726 colons = path.count(':')
727 if colons == 0:
728 prefix, suffix = path, None
729 else:
730 if colons != 1:
731 raise DistlibException("Invalid specification "
732 "'%s'" % specification)
733 prefix, suffix = path.split(':')
734 flags = d['flags']
735 if flags is None:
736 if '[' in specification or ']' in specification:
737 raise DistlibException("Invalid specification "
738 "'%s'" % specification)
739 flags = []
740 else:
741 flags = [f.strip() for f in flags.split(',')]
742 result = ExportEntry(name, prefix, suffix, flags)
743 return result
744
745

References i.

◆ get_extras()

get_extras (   requested,
  available 
)

Definition at line 888 of file util.py.

888def get_extras(requested, available):
889 result = set()
890 requested = set(requested or [])
891 available = set(available or [])
892 if '*' in requested:
894 result |= available
895 for r in requested:
896 if r == '-':
897 result.add(r)
898 elif r.startswith('-'):
899 unwanted = r[1:]
900 if unwanted not in available:
901 logger.warning('undeclared extra: %s' % unwanted)
902 if unwanted in result:
903 result.remove(unwanted)
904 else:
905 if r not in available:
906 logger.warning('undeclared extra: %s' % r)
907 result.add(r)
908 return result
909#
910# Extended metadata functionality
911#
912

References i.

◆ get_host_platform()

get_host_platform ( )
Return a string that identifies the current platform.  This is used mainly to
distinguish platform-specific build directories and platform-specific built
distributions.  Typically includes the OS name and version and the
architecture (as supplied by 'os.uname()'), although the exact information
included depends on the OS; eg. on Linux, the kernel version isn't
particularly important.

Examples of returned values:
   linux-i586
   linux-alpha (?)
   solaris-2.6-sun4u

Windows will return one of:
   win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
   win32 (all others - specifically, sys.platform is returned)

For other non-POSIX platforms, currently just returns 'sys.platform'.

Definition at line 1838 of file util.py.

1838def get_host_platform():
1839 """Return a string that identifies the current platform. This is used mainly to
1840 distinguish platform-specific build directories and platform-specific built
1841 distributions. Typically includes the OS name and version and the
1842 architecture (as supplied by 'os.uname()'), although the exact information
1843 included depends on the OS; eg. on Linux, the kernel version isn't
1844 particularly important.
1845
1846 Examples of returned values:
1847 linux-i586
1848 linux-alpha (?)
1849 solaris-2.6-sun4u
1850
1851 Windows will return one of:
1852 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
1853 win32 (all others - specifically, sys.platform is returned)
1854
1855 For other non-POSIX platforms, currently just returns 'sys.platform'.
1856
1857 """
1858 if os.name == 'nt':
1859 if 'amd64' in sys.version.lower():
1860 return 'win-amd64'
1861 if '(arm)' in sys.version.lower():
1862 return 'win-arm32'
1863 if '(arm64)' in sys.version.lower():
1864 return 'win-arm64'
1865 return sys.platform
1866
1867 # Set for cross builds explicitly
1868 if "_PYTHON_HOST_PLATFORM" in os.environ:
1869 return os.environ["_PYTHON_HOST_PLATFORM"]
1870
1871 if os.name != 'posix' or not hasattr(os, 'uname'):
1872 # XXX what about the architecture? NT is Intel or Alpha,
1873 # Mac OS is M68k or PPC, etc.
1874 return sys.platform
1875
1876 # Try to distinguish various flavours of Unix
1877
1878 (osname, host, release, version, machine) = os.uname()
1879
1880 # Convert the OS name to lowercase, remove '/' characters, and translate
1881 # spaces (for "Power Macintosh")
1882 osname = osname.lower().replace('/', '')
1883 machine = machine.replace(' ', '_').replace('/', '-')
1884
1885 if osname[:5] == 'linux':
1886 # At least on Linux/Intel, 'machine' is the processor --
1887 # i386, etc.
1888 # XXX what about Alpha, SPARC, etc?
1889 return "%s-%s" % (osname, machine)
1890
1891 elif osname[:5] == 'sunos':
1892 if release[0] >= '5': # SunOS 5 == Solaris 2
1893 osname = 'solaris'
1894 release = '%d.%s' % (int(release[0]) - 3, release[2:])
1895 # We can't use 'platform.architecture()[0]' because a
1896 # bootstrap problem. We use a dict to get an error
1897 # if some suspicious happens.
1898 bitness = {2147483647:'32bit', 9223372036854775807:'64bit'}
1899 machine += '.%s' % bitness[sys.maxsize]
1900 # fall through to standard osname-release-machine representation
1901 elif osname[:3] == 'aix':
1902 from _aix_support import aix_platform
1903 return aix_platform()
1904 elif osname[:6] == 'cygwin':
1905 osname = 'cygwin'
1906 rel_re = re.compile (r'[\d.]+', re.ASCII)
1907 m = rel_re.match(release)
1908 if m:
1909 release = m.group()
1910 elif osname[:6] == 'darwin':
1911 import _osx_support, distutils.sysconfig
1912 osname, release, machine = _osx_support.get_platform_osx(
1914 osname, release, machine)
1915
1916 return '%s-%s-%s' % (osname, release, machine)
1917
1918

References i.

Referenced by pip._vendor.distlib.util.get_platform().

Here is the caller graph for this function:

◆ get_package_data()

get_package_data (   name,
  version 
)

Definition at line 941 of file util.py.

941def get_package_data(name, version):
942 url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
943 url = urljoin(_external_data_base_url, url)
944 return _get_external_data(url)
945
946

References pip._vendor.distlib.util._get_external_data(), and i.

Here is the call graph for this function:

◆ get_platform()

get_platform ( )

Definition at line 1926 of file util.py.

1926def get_platform():
1927 if os.name != 'nt':
1928 return get_host_platform()
1929 cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
1930 if cross_compilation_target not in _TARGET_TO_PLAT:
1931 return get_host_platform()
1932 return _TARGET_TO_PLAT[cross_compilation_target]

References pip._vendor.distlib.util.get_host_platform(), and i.

Here is the call graph for this function:

◆ get_process_umask()

get_process_umask ( )

Definition at line 825 of file util.py.

825def get_process_umask():
826 result = os.umask(0o22)
827 os.umask(result)
828 return result
829

References i.

◆ get_project_data()

get_project_data (   name)

Definition at line 935 of file util.py.

935def get_project_data(name):
936 url = '%s/%s/project.json' % (name[0].upper(), name)
937 url = urljoin(_external_data_base_url, url)
938 result = _get_external_data(url)
939 return result
940

References pip._vendor.distlib.util._get_external_data(), and i.

Here is the call graph for this function:

◆ get_resources_dests()

get_resources_dests (   resources_root,
  rules 
)
Find destinations for resources files

Definition at line 270 of file util.py.

270def get_resources_dests(resources_root, rules):
271 """Find destinations for resources files"""
272
273 def get_rel_path(root, path):
274 # normalizes and returns a lstripped-/-separated path
275 root = root.replace(os.path.sep, '/')
276 path = path.replace(os.path.sep, '/')
277 assert path.startswith(root)
278 return path[len(root):].lstrip('/')
279
280 destinations = {}
281 for base, suffix, dest in rules:
282 prefix = os.path.join(resources_root, base)
283 for abs_base in iglob(prefix):
284 abs_glob = os.path.join(abs_base, suffix)
285 for abs_path in iglob(abs_glob):
286 resource_file = get_rel_path(resources_root, abs_path)
287 if dest is None: # remove the entry if it was here
288 destinations.pop(resource_file, None)
289 else:
290 rel_path = get_rel_path(abs_base, abs_path)
291 rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
292 destinations[resource_file] = rel_dest + '/' + rel_path
293 return destinations
294
295

References i.

◆ iglob()

iglob (   path_glob)
Extended globbing function that supports ** and {opt1,opt2,opt3}.

Definition at line 1377 of file util.py.

1377def iglob(path_glob):
1378 """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
1379 if _CHECK_RECURSIVE_GLOB.search(path_glob):
1380 msg = """invalid glob %r: recursive glob "**" must be used alone"""
1381 raise ValueError(msg % path_glob)
1382 if _CHECK_MISMATCH_SET.search(path_glob):
1383 msg = """invalid glob %r: mismatching set marker '{' or '}'"""
1384 raise ValueError(msg % path_glob)
1385 return _iglob(path_glob)
1386
1387

References pip._vendor.distlib.util._iglob(), and i.

Here is the call graph for this function:

◆ in_venv()

in_venv ( )

Definition at line 296 of file util.py.

296def in_venv():
297 if hasattr(sys, 'real_prefix'):
298 # virtualenv venvs
299 result = True
300 else:
301 # PEP 405 venvs
302 result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
303 return result
304
305

References i.

◆ is_string_sequence()

is_string_sequence (   seq)

Definition at line 830 of file util.py.

830def is_string_sequence(seq):
831 result = True
832 i = None
833 for i, s in enumerate(seq):
834 if not isinstance(s, string_types):
835 result = False
836 break
837 assert i is not None
838 return result
839

References i.

◆ normalize_name()

normalize_name (   name)
Normalize a python package name a la PEP 503

Definition at line 1728 of file util.py.

1728def normalize_name(name):
1729 """Normalize a python package name a la PEP 503"""
1730 # https://www.python.org/dev/peps/pep-0503/#normalized-names
1731 return re.sub('[-_.]+', '-', name).lower()
1732
1733# def _get_pypirc_command():
1734 # """
1735 # Get the distutils command for interacting with PyPI configurations.
1736 # :return: the command.
1737 # """
1738 # from distutils.core import Distribution
1739 # from distutils.config import PyPIRCCommand
1740 # d = Distribution()
1741 # return PyPIRCCommand(d)
1742

References i.

◆ parse_credentials()

parse_credentials (   netloc)

Definition at line 810 of file util.py.

810def parse_credentials(netloc):
811 username = password = None
812 if '@' in netloc:
813 prefix, netloc = netloc.rsplit('@', 1)
814 if ':' not in prefix:
815 username = prefix
816 else:
817 username, password = prefix.split(':', 1)
818 if username:
819 username = unquote(username)
820 if password:
821 password = unquote(password)
822 return username, password, netloc
823
824

References i.

◆ parse_marker()

parse_marker (   marker_string)
Parse a marker string and return a dictionary containing a marker expression.

The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).

Definition at line 56 of file util.py.

56def parse_marker(marker_string):
57 """
58 Parse a marker string and return a dictionary containing a marker expression.
59
60 The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
61 the expression grammar, or strings. A string contained in quotes is to be
62 interpreted as a literal string, and a string not contained in quotes is a
63 variable (such as os_name).
64 """
65 def marker_var(remaining):
66 # either identifier, or literal string
67 m = IDENTIFIER.match(remaining)
68 if m:
69 result = m.groups()[0]
70 remaining = remaining[m.end():]
71 elif not remaining:
72 raise SyntaxError('unexpected end of input')
73 else:
74 q = remaining[0]
75 if q not in '\'"':
76 raise SyntaxError('invalid expression: %s' % remaining)
77 oq = '\'"'.replace(q, '')
78 remaining = remaining[1:]
79 parts = [q]
80 while remaining:
81 # either a string chunk, or oq, or q to terminate
82 if remaining[0] == q:
83 break
84 elif remaining[0] == oq:
85 parts.append(oq)
86 remaining = remaining[1:]
87 else:
88 m = STRING_CHUNK.match(remaining)
89 if not m:
90 raise SyntaxError('error in string literal: %s' % remaining)
92 remaining = remaining[m.end():]
93 else:
94 s = ''.join(parts)
95 raise SyntaxError('unterminated string: %s' % s)
97 result = ''.join(parts)
98 remaining = remaining[1:].lstrip() # skip past closing quote
99 return result, remaining
100
101 def marker_expr(remaining):
102 if remaining and remaining[0] == '(':
103 result, remaining = marker(remaining[1:].lstrip())
104 if remaining[0] != ')':
105 raise SyntaxError('unterminated parenthesis: %s' % remaining)
106 remaining = remaining[1:].lstrip()
107 else:
108 lhs, remaining = marker_var(remaining)
109 while remaining:
110 m = MARKER_OP.match(remaining)
111 if not m:
112 break
113 op = m.groups()[0]
114 remaining = remaining[m.end():]
115 rhs, remaining = marker_var(remaining)
116 lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
117 result = lhs
118 return result, remaining
119
120 def marker_and(remaining):
121 lhs, remaining = marker_expr(remaining)
122 while remaining:
123 m = AND.match(remaining)
124 if not m:
125 break
126 remaining = remaining[m.end():]
127 rhs, remaining = marker_expr(remaining)
128 lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
129 return lhs, remaining
130
131 def marker(remaining):
132 lhs, remaining = marker_and(remaining)
133 while remaining:
134 m = OR.match(remaining)
135 if not m:
136 break
137 remaining = remaining[m.end():]
138 rhs, remaining = marker_and(remaining)
139 lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
140 return lhs, remaining
141
142 return marker(marker_string)
143
144

References i.

◆ parse_name_and_version()

parse_name_and_version (   p)
A utility method used to get name and version from a string.

From e.g. a Provides-Dist value.

:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.

Definition at line 873 of file util.py.

873def parse_name_and_version(p):
874 """
875 A utility method used to get name and version from a string.
876
877 From e.g. a Provides-Dist value.
878
879 :param p: A value in a form 'foo (1.0)'
880 :return: The name and version as a tuple.
881 """
883 if not m:
884 raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
885 d = m.groupdict()
886 return d['name'].strip().lower(), d['ver']
887

References i.

◆ parse_requirement()

parse_requirement (   req)
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.

Definition at line 145 of file util.py.

145def parse_requirement(req):
146 """
147 Parse a requirement passed in as a string. Return a Container
148 whose attributes contain the various parts of the requirement.
149 """
150 remaining = req.strip()
151 if not remaining or remaining.startswith('#'):
152 return None
153 m = IDENTIFIER.match(remaining)
154 if not m:
155 raise SyntaxError('name expected: %s' % remaining)
156 distname = m.groups()[0]
157 remaining = remaining[m.end():]
158 extras = mark_expr = versions = uri = None
159 if remaining and remaining[0] == '[':
160 i = remaining.find(']', 1)
161 if i < 0:
162 raise SyntaxError('unterminated extra: %s' % remaining)
163 s = remaining[1:i]
164 remaining = remaining[i + 1:].lstrip()
165 extras = []
166 while s:
167 m = IDENTIFIER.match(s)
168 if not m:
169 raise SyntaxError('malformed extra: %s' % s)
171 s = s[m.end():]
172 if not s:
173 break
174 if s[0] != ',':
175 raise SyntaxError('comma expected in extras: %s' % s)
176 s = s[1:].lstrip()
177 if not extras:
178 extras = None
179 if remaining:
180 if remaining[0] == '@':
181 # it's a URI
182 remaining = remaining[1:].lstrip()
183 m = NON_SPACE.match(remaining)
184 if not m:
185 raise SyntaxError('invalid URI: %s' % remaining)
186 uri = m.groups()[0]
187 t = urlparse(uri)
188 # there are issues with Python and URL parsing, so this test
189 # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
190 # always parse invalid URLs correctly - it should raise
191 # exceptions for malformed URLs
192 if not (t.scheme and t.netloc):
193 raise SyntaxError('Invalid URL: %s' % uri)
194 remaining = remaining[m.end():].lstrip()
195 else:
196
197 def get_versions(ver_remaining):
198 """
199 Return a list of operator, version tuples if any are
200 specified, else None.
201 """
202 m = COMPARE_OP.match(ver_remaining)
203 versions = None
204 if m:
205 versions = []
206 while True:
207 op = m.groups()[0]
208 ver_remaining = ver_remaining[m.end():]
209 m = VERSION_IDENTIFIER.match(ver_remaining)
210 if not m:
211 raise SyntaxError('invalid version: %s' % ver_remaining)
212 v = m.groups()[0]
213 versions.append((op, v))
214 ver_remaining = ver_remaining[m.end():]
215 if not ver_remaining or ver_remaining[0] != ',':
216 break
217 ver_remaining = ver_remaining[1:].lstrip()
218 # Some packages have a trailing comma which would break things
219 # See issue #148
220 if not ver_remaining:
221 break
222 m = COMPARE_OP.match(ver_remaining)
223 if not m:
224 raise SyntaxError('invalid constraint: %s' % ver_remaining)
225 if not versions:
226 versions = None
227 return versions, ver_remaining
228
229 if remaining[0] != '(':
230 versions, remaining = get_versions(remaining)
231 else:
232 i = remaining.find(')', 1)
233 if i < 0:
234 raise SyntaxError('unterminated parenthesis: %s' % remaining)
235 s = remaining[1:i]
236 remaining = remaining[i + 1:].lstrip()
237 # As a special diversion from PEP 508, allow a version number
238 # a.b.c in parentheses as a synonym for ~= a.b.c (because this
239 # is allowed in earlier PEPs)
240 if COMPARE_OP.match(s):
241 versions, _ = get_versions(s)
242 else:
244 if not m:
245 raise SyntaxError('invalid constraint: %s' % s)
246 v = m.groups()[0]
247 s = s[m.end():].lstrip()
248 if s:
249 raise SyntaxError('invalid constraint: %s' % s)
250 versions = [('~=', v)]
251
252 if remaining:
253 if remaining[0] != ';':
254 raise SyntaxError('invalid requirement: %s' % remaining)
255 remaining = remaining[1:].lstrip()
256
257 mark_expr, remaining = parse_marker(remaining)
258
259 if remaining and remaining[0] != '#':
260 raise SyntaxError('unexpected trailing data: %s' % remaining)
261
262 if not versions:
263 rs = distname
264 else:
265 rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
266 return Container(name=distname, extras=extras, constraints=versions,
267 marker=mark_expr, url=uri, requirement=rs)
268
269

References i.

◆ path_to_cache_dir()

path_to_cache_dir (   path)
Convert an absolute path to a directory name for use in a cache.

The algorithm used is:

#. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
#. Any occurrence of ``os.sep`` is replaced with ``'--'``.
#. ``'.cache'`` is appended.

Definition at line 787 of file util.py.

787def path_to_cache_dir(path):
788 """
789 Convert an absolute path to a directory name for use in a cache.
790
791 The algorithm used is:
792
793 #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
794 #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
795 #. ``'.cache'`` is appended.
796 """
798 if d:
799 d = d.replace(':', '---')
800 p = p.replace(os.sep, '--')
801 return d + p + '.cache'
802
803

References i.

Referenced by Cache.prefix_to_dir().

Here is the caller graph for this function:

◆ proceed()

proceed (   prompt,
  allowed_chars,
  error_prompt = None,
  default = None 
)

Definition at line 324 of file util.py.

324def proceed(prompt, allowed_chars, error_prompt=None, default=None):
325 p = prompt
326 while True:
327 s = raw_input(p)
328 p = prompt
329 if not s and default:
330 s = default
331 if s:
332 c = s[0].lower()
333 if c in allowed_chars:
334 break
335 if error_prompt:
336 p = '%c: %s\n%s' % (c, error_prompt, prompt)
337 return c
338
339

References i.

◆ read_exports()

read_exports (   stream)

Definition at line 349 of file util.py.

349def read_exports(stream):
350 if sys.version_info[0] >= 3:
351 # needs to be a text stream
352 stream = codecs.getreader('utf-8')(stream)
353 # Try to load as JSON, falling back on legacy format
354 data = stream.read()
355 stream = StringIO(data)
356 try:
357 jdata = json.load(stream)
358 result = jdata['extensions']['python.exports']['exports']
359 for group, entries in result.items():
360 for k, v in entries.items():
361 s = '%s = %s' % (k, v)
362 entry = get_export_entry(s)
363 assert entry is not None
364 entries[k] = entry
365 return result
366 except Exception:
367 stream.seek(0, 0)
368
369 def read_stream(cp, stream):
370 if hasattr(cp, 'read_file'):
371 cp.read_file(stream)
372 else:
373 cp.readfp(stream)
374
376 try:
377 read_stream(cp, stream)
380 data = textwrap.dedent(data)
381 stream = StringIO(data)
382 read_stream(cp, stream)
383
384 result = {}
385 for key in cp.sections():
386 result[key] = entries = {}
387 for name, value in cp.items(key):
388 s = '%s = %s' % (name, value)
389 entry = get_export_entry(s)
390 assert entry is not None
391 #entry.dist = self
392 entries[name] = entry
393 return result
394
395

References i.

◆ resolve()

resolve (   module_name,
  dotted_path 
)

Definition at line 667 of file util.py.

667def resolve(module_name, dotted_path):
668 if module_name in sys.modules:
669 mod = sys.modules[module_name]
670 else:
671 mod = __import__(module_name)
672 if dotted_path is None:
673 result = mod
674 else:
675 parts = dotted_path.split('.')
676 result = getattr(mod, parts.pop(0))
677 for p in parts:
678 result = getattr(result, p)
679 return result
680
681

References i.

Referenced by ExportEntry.value().

Here is the caller graph for this function:

◆ socket_timeout()

socket_timeout (   seconds = 15)

Definition at line 434 of file util.py.

434def socket_timeout(seconds=15):
436 try:
438 yield
439 finally:
441
442

References i.

◆ split_filename()

split_filename (   filename,
  project_name = None 
)
Extract name, version, python version from a filename (no extension)

Return name, version, pyver or None

Definition at line 845 of file util.py.

845def split_filename(filename, project_name=None):
846 """
847 Extract name, version, python version from a filename (no extension)
848
849 Return name, version, pyver or None
850 """
851 result = None
852 pyver = None
853 filename = unquote(filename).replace(' ', '-')
854 m = PYTHON_VERSION.search(filename)
855 if m:
856 pyver = m.group(1)
857 filename = filename[:m.start()]
858 if project_name and len(filename) > len(project_name) + 1:
859 m = re.match(re.escape(project_name) + r'\b', filename)
860 if m:
861 n = m.end()
862 result = filename[:n], filename[n + 1:], pyver
863 if result is None:
865 if m:
866 result = m.group(1), m.group(3), pyver
867 return result
868
869# Allow spaces in name because of legacy dists like "Twisted Core"

References i.

◆ tempdir()

tempdir ( )

Definition at line 416 of file util.py.

416def tempdir():
417 td = tempfile.mkdtemp()
418 try:
419 yield td
420 finally:
421 shutil.rmtree(td)
422
423@contextlib.contextmanager

References i.

◆ unarchive()

unarchive (   archive_filename,
  dest_dir,
  format = None,
  check = True 
)

Definition at line 1205 of file util.py.

1205def unarchive(archive_filename, dest_dir, format=None, check=True):
1206
1207 def check_path(path):
1208 if not isinstance(path, text_type):
1209 path = path.decode('utf-8')
1210 p = os.path.abspath(os.path.join(dest_dir, path))
1211 if not p.startswith(dest_dir) or p[plen] != os.sep:
1212 raise ValueError('path outside destination: %r' % p)
1213
1214 dest_dir = os.path.abspath(dest_dir)
1215 plen = len(dest_dir)
1216 archive = None
1217 if format is None:
1218 if archive_filename.endswith(('.zip', '.whl')):
1219 format = 'zip'
1220 elif archive_filename.endswith(('.tar.gz', '.tgz')):
1221 format = 'tgz'
1222 mode = 'r:gz'
1223 elif archive_filename.endswith(('.tar.bz2', '.tbz')):
1224 format = 'tbz'
1225 mode = 'r:bz2'
1226 elif archive_filename.endswith('.tar'):
1227 format = 'tar'
1228 mode = 'r'
1229 else: # pragma: no cover
1230 raise ValueError('Unknown format for %r' % archive_filename)
1231 try:
1232 if format == 'zip':
1233 archive = ZipFile(archive_filename, 'r')
1234 if check:
1235 names = archive.namelist()
1236 for name in names:
1237 check_path(name)
1238 else:
1239 archive = tarfile.open(archive_filename, mode)
1240 if check:
1241 names = archive.getnames()
1242 for name in names:
1243 check_path(name)
1244 if format != 'zip' and sys.version_info[0] < 3:
1245 # See Python issue 17153. If the dest path contains Unicode,
1246 # tarfile extraction fails on Python 2.x if a member path name
1247 # contains non-ASCII characters - it leads to an implicit
1248 # bytes -> unicode conversion using ASCII to decode.
1249 for tarinfo in archive.getmembers():
1250 if not isinstance(tarinfo.name, text_type):
1252 archive.extractall(dest_dir)
1253
1254 finally:
1255 if archive:
1257
1258

References i.

◆ write_exports()

write_exports (   exports,
  stream 
)

Definition at line 396 of file util.py.

396def write_exports(exports, stream):
397 if sys.version_info[0] >= 3:
398 # needs to be a text stream
399 stream = codecs.getwriter('utf-8')(stream)
401 for k, v in exports.items():
402 # TODO check k, v for valid values
404 for entry in v.values():
405 if entry.suffix is None:
406 s = entry.prefix
407 else:
408 s = '%s:%s' % (entry.prefix, entry.suffix)
409 if entry.flags:
410 s = '%s [%s]' % (s, ', '.join(entry.flags))
411 cp.set(k, entry.name, s)
412 cp.write(stream)
413
414
415@contextlib.contextmanager

References i.

◆ zip_dir()

zip_dir (   directory)
zip a directory tree into a BytesIO object

Definition at line 1259 of file util.py.

1259def zip_dir(directory):
1260 """zip a directory tree into a BytesIO object"""
1261 result = io.BytesIO()
1262 dlen = len(directory)
1263 with ZipFile(result, "w") as zf:
1264 for root, dirs, files in os.walk(directory):
1265 for name in files:
1266 full = os.path.join(root, name)
1267 rel = root[dlen:]
1268 dest = os.path.join(rel, name)
1269 zf.write(full, dest)
1270 return result
1271
1272#
1273# Simple progress bar
1274#
1275

References i.

Variable Documentation

◆ _CHECK_MISMATCH_SET

_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
protected

Definition at line 1374 of file util.py.

◆ _CHECK_RECURSIVE_GLOB

_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
protected

Definition at line 1373 of file util.py.

◆ _external_data_base_url

str _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
protected

Definition at line 933 of file util.py.

◆ _TARGET_TO_PLAT

dict _TARGET_TO_PLAT
protected
Initial value:
1= {
2 'x86' : 'win32',
3 'x64' : 'win-amd64',
4 'arm' : 'win-arm32',
5}

Definition at line 1919 of file util.py.

◆ AND

AND = re.compile(r'^and\b\s*')

Definition at line 51 of file util.py.

◆ ARCHIVE_EXTENSIONS

tuple ARCHIVE_EXTENSIONS
Initial value:
1= ('.tar.gz', '.tar.bz2', '.tar', '.zip',
2 '.tgz', '.tbz', '.whl')

Definition at line 1202 of file util.py.

◆ COMPARE_OP

COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')

Definition at line 48 of file util.py.

◆ ENTRY_RE

ENTRY_RE = re.compile(, re.VERBOSE)

Definition at line 710 of file util.py.

◆ IDENTIFIER

IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')

Definition at line 46 of file util.py.

◆ logger

logger = logging.getLogger(__name__)

Definition at line 40 of file util.py.

◆ MARKER_OP

MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')

Definition at line 49 of file util.py.

◆ NAME_VERSION_RE

NAME_VERSION_RE
Initial value:
1= re.compile(r'(?P<name>[\w .-]+)\s*'
2 r'\‍(\s*(?P<ver>[^\s)]+)\‍)$')

Definition at line 870 of file util.py.

◆ NON_SPACE

NON_SPACE = re.compile(r'(\S+)\s*')

Definition at line 52 of file util.py.

◆ OR

OR = re.compile(r'^or\b\s*')

Definition at line 50 of file util.py.

◆ PROJECT_NAME_AND_VERSION

PROJECT_NAME_AND_VERSION
Initial value:
1= re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
2 '([a-z0-9_.+-]+)', re.I)

Definition at line 840 of file util.py.

◆ PYTHON_VERSION

PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')

Definition at line 842 of file util.py.

◆ RICH_GLOB

RICH_GLOB = re.compile(r'\{([^}]*)\}')

Definition at line 1372 of file util.py.

◆ ssl

ssl = None

Definition at line 20 of file util.py.

◆ STRING_CHUNK

STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')

Definition at line 53 of file util.py.

◆ UNITS

tuple UNITS = ('', 'K', 'M', 'G','T','P')

Definition at line 1276 of file util.py.

◆ VERSION_IDENTIFIER

VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')

Definition at line 47 of file util.py.