Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper
|
[
"\n Patch two bugs in functools.update_wrapper.\n "
] |
Please provide a description of the function:def lru_cache(maxsize=100, typed=False):
# Users should only access the lru_cache through its public API:
# cache_info, cache_clear, and f.__wrapped__
# The internals of the lru_cache are encapsulated for thread safety and
# to allow the implementation to change (including a possible C version).
def decorating_function(user_function):
cache = dict()
stats = [0, 0] # make statistics updateable non-locally
HITS, MISSES = 0, 1 # names for the stats fields
make_key = _make_key
cache_get = cache.get # bound method to lookup key or return None
_len = len # localize the global len() function
lock = RLock() # because linkedlist updates aren't threadsafe
root = [] # root of the circular doubly linked list
root[:] = [root, root, None, None] # initialize by pointing to self
nonlocal_root = [root] # make updateable non-locally
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
if maxsize == 0:
def wrapper(*args, **kwds):
# no caching, just do a statistics update after a successful call
result = user_function(*args, **kwds)
stats[MISSES] += 1
return result
elif maxsize is None:
def wrapper(*args, **kwds):
# simple caching without ordering or size limit
key = make_key(args, kwds, typed)
result = cache_get(key, root) # root used here as a unique not-found sentinel
if result is not root:
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
cache[key] = result
stats[MISSES] += 1
return result
else:
def wrapper(*args, **kwds):
# size limited caching that tracks accesses by recency
key = make_key(args, kwds, typed) if kwds or typed else args
with lock:
link = cache_get(key)
if link is not None:
# record recent use of the key by moving it to the front of the list
root, = nonlocal_root
link_prev, link_next, key, result = link
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
last = root[PREV]
last[NEXT] = root[PREV] = link
link[PREV] = last
link[NEXT] = root
stats[HITS] += 1
return result
result = user_function(*args, **kwds)
with lock:
root, = nonlocal_root
if key in cache:
# getting here means that this same key was added to the
# cache while the lock was released. since the link
# update is already done, we need only return the
# computed result and update the count of misses.
pass
elif _len(cache) >= maxsize:
# use the old root to store the new key and result
oldroot = root
oldroot[KEY] = key
oldroot[RESULT] = result
# empty the oldest link and make it the new root
root = nonlocal_root[0] = oldroot[NEXT]
oldkey = root[KEY]
root[KEY] = root[RESULT] = None
# now update the cache dictionary for the new links
del cache[oldkey]
cache[key] = oldroot
else:
# put result in a new link at the front of the list
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
return result
def cache_info():
with lock:
return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))
def cache_clear():
with lock:
cache.clear()
root = nonlocal_root[0]
root[:] = [root, root, None, None]
stats[:] = [0, 0]
wrapper.__wrapped__ = user_function
wrapper.cache_info = cache_info
wrapper.cache_clear = cache_clear
return update_wrapper(wrapper, user_function)
return decorating_function
|
[
"Least-recently-used cache decorator.\n\n If *maxsize* is set to None, the LRU features are disabled and the cache\n can grow without bound.\n\n If *typed* is True, arguments of different types will be cached separately.\n For example, f(3.0) and f(3) will be treated as distinct calls with\n distinct results.\n\n Arguments to the cached function must be hashable.\n\n View the cache statistics named tuple (hits, misses, maxsize, currsize) with\n f.cache_info(). Clear the cache and statistics with f.cache_clear().\n Access the underlying function with f.__wrapped__.\n\n See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used\n\n ",
"Report cache statistics",
"Clear the cache and cache statistics"
] |
Please provide a description of the function:def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(el):
return el
return default
|
[
"\n Return first element of `iterable` that evaluates true, else return None\n (or an optional default value).\n\n >>> first([0, False, None, [], (), 42])\n 42\n\n >>> first([0, False, None, [], ()]) is None\n True\n\n >>> first([0, False, None, [], ()], default='ohai')\n 'ohai'\n\n >>> import re\n >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])\n >>> m.group(1)\n 'bc'\n\n The optional `key` argument specifies a one-argument predicate function\n like that used for `filter()`. The `key` argument, if supplied, must be\n in keyword form. For example:\n\n >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)\n 4\n\n "
] |
Please provide a description of the function:def get_process_mapping():
try:
output = subprocess.check_output([
'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=',
])
except OSError as e: # Python 2-compatible FileNotFoundError.
if e.errno != errno.ENOENT:
raise
raise PsNotAvailable('ps not found')
except subprocess.CalledProcessError as e:
# `ps` can return 1 if the process list is completely empty.
# (sarugaku/shellingham#15)
if not e.output.strip():
return {}
raise
if not isinstance(output, str):
encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
output = output.decode(encoding)
processes = {}
for line in output.split('\n'):
try:
pid, ppid, args = line.strip().split(None, 2)
# XXX: This is not right, but we are really out of options.
# ps does not offer a sane way to decode the argument display,
# and this is "Good Enough" for obtaining shell names. Hopefully
# people don't name their shell with a space, or have something
# like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14)
args = tuple(a.strip() for a in args.split(' '))
except ValueError:
continue
processes[pid] = Process(args=args, pid=pid, ppid=ppid)
return processes
|
[
"Try to look up the process tree via the output of `ps`.\n "
] |
Please provide a description of the function:def visit_Name(self, node, store_as_param=False, **kwargs):
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name)
|
[
"All assignments to names go through this function."
] |
Please provide a description of the function:def visit_Assign(self, node, **kwargs):
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs)
|
[
"Visit assignments in the correct order."
] |
Please provide a description of the function:def make_set_closure_cell():
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell
|
[
"\n Moved into a function for testability.\n "
] |
Please provide a description of the function:def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). '''
self.flush()
with _wrap_ptyprocess_err():
# PtyProcessError may be raised if it is not possible to terminate
# the child.
self.ptyproc.close(force=force)
self.isalive() # Update exit status from ptyproc
self.child_fd = -1
self.closed = True
|
[] |
Please provide a description of the function:def waitnoecho(self, timeout=-1):
'''This waits until the terminal ECHO flag is set False. This returns
True if the echo mode is off. This returns False if the ECHO flag was
not set False before the timeout. This can be used to detect when the
child is waiting for a password. Usually a child application will turn
off echo mode when it is waiting for the user to enter a password. For
example, instead of expecting the "password:" prompt you can wait for
the child to set ECHO off::
p = pexpect.spawn('ssh [email protected]')
p.waitnoecho()
p.sendline(mypassword)
If timeout==-1 then this method will use the value in self.timeout.
If timeout==None then this method to block until ECHO flag is False.
'''
if timeout == -1:
timeout = self.timeout
if timeout is not None:
end_time = time.time() + timeout
while True:
if not self.getecho():
return True
if timeout < 0 and timeout is not None:
return False
if timeout is not None:
timeout = end_time - time.time()
time.sleep(0.1)
|
[] |
Please provide a description of the function:def read_nonblocking(self, size=1, timeout=-1):
'''This reads at most size characters from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a logfile is specified, a
copy is written to that log.
If timeout is None then the read may block indefinitely.
If timeout is -1 then the self.timeout value is used. If timeout is 0
then the child is polled and if there is no data immediately ready
then this will raise a TIMEOUT exception.
The timeout refers only to the amount of time to read at least one
character. This is not affected by the 'size' parameter, so if you call
read_nonblocking(size=100, timeout=30) and only one character is
available right away then one character will be returned immediately.
It will not wait for 30 seconds for another 99 characters to come in.
This is a wrapper around os.read(). It uses select.select() to
implement the timeout. '''
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was terminated.
# FIXME So does this mean Irix systems are forced to always have
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
if not r and not self.isalive():
self.flag_eof = True
raise EOF('End Of File (EOF). Slow platform.')
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd], timeout)
else:
r, w, e = select_ignore_interrupts(
[self.child_fd], [], [], timeout
)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.child_fd in r:
return super(spawn, self).read_nonblocking(size)
raise ExceptionPexpect('Reached an unexpected state.')
|
[] |
Please provide a description of the function:def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspace and other line
processing to be performed prior to transmitting to the receiving
program. As this is buffered, there is a limited size of such buffer.
On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
This value may be discovered using fpathconf(3)::
>>> from os import fpathconf
>>> print(fpathconf(0, 'PC_MAX_CANON'))
256
On such a system, only 256 bytes may be received per line. Any
subsequent bytes received will be discarded. BEL (``'\a'``) is then
sent to output if IMAXBEL (termios.h) is set by the tty driver.
This is usually enabled by default. Linux does not honor this as
an option -- it behaves as though it is always set on.
Canonical input processing may be disabled altogether by executing
a shell, then stty(1), before executing the final program::
>>> bash = pexpect.spawn('/bin/bash', echo=False)
>>> bash.sendline('stty -icanon')
>>> bash.sendline('base64')
>>> bash.sendline('x' * 5000)
'''
if self.delaybeforesend is not None:
time.sleep(self.delaybeforesend)
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b)
|
[] |
Please provide a description of the function:def sendline(self, s=''):
'''Wraps send(), sending string ``s`` to child process, with
``os.linesep`` automatically appended. Returns number of bytes
written. Only a limited number of bytes may be sent for each
line in the default terminal mode, see docstring of :meth:`send`.
'''
s = self._coerce_send_string(s)
return self.send(s + self.linesep)
|
[] |
Please provide a description of the function:def _log_control(self, s):
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send')
|
[
"Write control characters to the appropriate log files"
] |
Please provide a description of the function:def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
'''
n, byte = self.ptyproc.sendcontrol(char)
self._log_control(byte)
return n
|
[] |
Please provide a description of the function:def sendintr(self):
'''This sends a SIGINT to the child. It does not require
the SIGINT to be the first character on a line. '''
n, byte = self.ptyproc.sendintr()
self._log_control(byte)
|
[] |
Please provide a description of the function:def wait(self):
'''This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
technically still alive until its output is read by the parent.
This method is non-blocking if :meth:`wait` has already been called
previously or :meth:`isalive` method returns False. It simply returns
the previously determined exit status.
'''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
# exception may occur if "Is some other process attempting
# "job control with our child pid?"
exitstatus = ptyproc.wait()
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return exitstatus
|
[] |
Please provide a description of the function:def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. '''
ptyproc = self.ptyproc
with _wrap_ptyprocess_err():
alive = ptyproc.isalive()
if not alive:
self.status = ptyproc.status
self.exitstatus = ptyproc.exitstatus
self.signalstatus = ptyproc.signalstatus
self.terminated = True
return alive
|
[] |
Please provide a description of the function:def interact(self, escape_character=chr(29),
input_filter=None, output_filter=None):
'''This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is printed. This
simply echos the child stdout and child stderr to the real stdout and
it echos the real stdin to the child stdin. When the user types the
escape_character this method will return None. The escape_character
will not be transmitted. The default for escape_character is
entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
escaping, escape_character may be set to None.
If a logfile is specified, then the data sent and received from the
child process in interact mode is duplicated to the given log.
You may pass in optional input and output filter functions. These
functions should take a string and return a string. The output_filter
will be passed all the output from the child process. The input_filter
will be passed all the keyboard input from the user. The input_filter
is run BEFORE the check for the escape_character.
Note that if you change the window size of the parent the SIGWINCH
signal will not be passed through to the child. If you want the child
window size to change when the parent's window size changes then do
something like the following example::
import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
s = struct.pack("HHHH", 0, 0, 0, 0)
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
termios.TIOCGWINSZ , s))
if not p.closed:
p.setwinsize(a[0],a[1])
# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()
'''
# Flush the buffer.
self.write_to_stdout(self.buffer)
self.stdout.flush()
self._buffer = self.buffer_type()
mode = tty.tcgetattr(self.STDIN_FILENO)
tty.setraw(self.STDIN_FILENO)
if escape_character is not None and PY3:
escape_character = escape_character.encode('latin-1')
try:
self.__interact_copy(escape_character, input_filter, output_filter)
finally:
tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
|
[] |
Please provide a description of the function:def __interact_writen(self, fd, data):
'''This is used by the interact() method.
'''
while data != b'' and self.isalive():
n = os.write(fd, data)
data = data[n:]
|
[] |
Please provide a description of the function:def __interact_copy(
self, escape_character=None, input_filter=None, output_filter=None
):
'''This is used by the interact() method.
'''
while self.isalive():
if self.use_poll:
r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
else:
r, w, e = select_ignore_interrupts(
[self.child_fd, self.STDIN_FILENO], [], []
)
if self.child_fd in r:
try:
data = self.__interact_read(self.child_fd)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
break
raise
if data == b'':
# BSD-style EOF
break
if output_filter:
data = output_filter(data)
self._log(data, 'read')
os.write(self.STDOUT_FILENO, data)
if self.STDIN_FILENO in r:
data = self.__interact_read(self.STDIN_FILENO)
if input_filter:
data = input_filter(data)
i = -1
if escape_character is not None:
i = data.rfind(escape_character)
if i != -1:
data = data[:i]
if data:
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
break
self._log(data, 'send')
self.__interact_writen(self.child_fd, data)
|
[] |
Please provide a description of the function:def extras_to_string(extras):
# type: (Iterable[S]) -> S
if isinstance(extras, six.string_types):
if extras.startswith("["):
return extras
else:
extras = [extras]
if not extras:
return ""
return "[{0}]".format(",".join(sorted(set(extras))))
|
[
"Turn a list of extras into a string"
] |
Please provide a description of the function:def parse_extras(extras_str):
# type: (AnyStr) -> List[AnyStr]
from pkg_resources import Requirement
extras = Requirement.parse("fakepkg{0}".format(extras_to_string(extras_str))).extras
return sorted(dedup([extra.lower() for extra in extras]))
|
[
"\n Turn a string of extras into a parsed extras list\n "
] |
Please provide a description of the function:def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return ""
|
[
"\n Turn a list of specifier tuples into a string\n "
] |
Please provide a description of the function:def convert_direct_url_to_url(direct_url):
# type: (AnyStr) -> AnyStr
direct_match = DIRECT_URL_RE.match(direct_url) # type: Optional[Match]
if direct_match is None:
url_match = URL_RE.match(direct_url)
if url_match or is_valid_url(direct_url):
return direct_url
match_dict = (
{}
) # type: Dict[STRING_TYPE, Union[Tuple[STRING_TYPE, ...], STRING_TYPE]]
if direct_match is not None:
match_dict = direct_match.groupdict() # type: ignore
if not match_dict:
raise ValueError(
"Failed converting value to normal URL, is it a direct URL? {0!r}".format(
direct_url
)
)
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
url = "" # type: STRING_TYPE
url = "".join([s for s in url_segments if s is not None]) # type: ignore
new_url = build_vcs_uri(
None,
url,
ref=match_dict.get("ref"),
name=match_dict.get("name"),
extras=match_dict.get("extras"),
subdirectory=match_dict.get("subdirectory"),
)
return new_url
|
[
"\n Given a direct url as defined by *PEP 508*, convert to a :class:`~pip_shims.shims.Link`\n compatible URL by moving the name and extras into an **egg_fragment**.\n\n :param str direct_url: A pep-508 compliant direct url.\n :return: A reformatted URL for use with Link objects and :class:`~pip_shims.shims.InstallRequirement` objects.\n :rtype: AnyStr\n "
] |
Please provide a description of the function:def convert_url_to_direct_url(url, name=None):
# type: (AnyStr, Optional[AnyStr]) -> AnyStr
if not isinstance(url, six.string_types):
raise TypeError(
"Expected a string to convert to a direct url, got {0!r}".format(url)
)
direct_match = DIRECT_URL_RE.match(url)
if direct_match:
return url
url_match = URL_RE.match(url)
if url_match is None or not url_match.groupdict():
raise ValueError("Failed parse a valid URL from {0!r}".format(url))
match_dict = url_match.groupdict()
url_segments = [match_dict.get(s) for s in ("scheme", "host", "path", "pathsep")]
name = match_dict.get("name", name)
extras = match_dict.get("extras")
new_url = ""
if extras and not name:
url_segments.append(extras)
elif extras and name:
new_url = "{0}{1}@ ".format(name, extras)
else:
if name is not None:
new_url = "{0}@ ".format(name)
else:
raise ValueError(
"Failed to construct direct url: "
"No name could be parsed from {0!r}".format(url)
)
if match_dict.get("ref"):
url_segments.append("@{0}".format(match_dict.get("ref")))
url = "".join([s for s in url if s is not None])
url = "{0}{1}".format(new_url, url)
return url
|
[
"\n Given a :class:`~pip_shims.shims.Link` compatible URL, convert to a direct url as\n defined by *PEP 508* by extracting the name and extras from the **egg_fragment**.\n\n :param AnyStr url: A :class:`~pip_shims.shims.InstallRequirement` compliant URL.\n :param Optiona[AnyStr] name: A name to use in case the supplied URL doesn't provide one.\n :return: A pep-508 compliant direct url.\n :rtype: AnyStr\n\n :raises ValueError: Raised when the URL can't be parsed or a name can't be found.\n :raises TypeError: When a non-string input is provided.\n "
] |
Please provide a description of the function:def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
if req is None:
raise TypeError("Must pass in a valid requirement, received {0!r}".format(req))
if getattr(req, "marker", None) is not None:
marker = req.marker # type: TMarker
marker._markers = _strip_extras_markers(marker._markers)
if not marker._markers:
req.marker = None
else:
req.marker = marker
return req
|
[
"\n Given a :class:`~packaging.requirements.Requirement` instance with markers defining\n *extra == 'name'*, strip out the extras from the markers and return the cleaned\n requirement\n\n :param PackagingRequirement req: A packaging requirement to clean\n :return: A cleaned requirement\n :rtype: PackagingRequirement\n "
] |
Please provide a description of the function:def get_pyproject(path):
# type: (Union[STRING_TYPE, Path]) -> Optional[Tuple[List[STRING_TYPE], STRING_TYPE]]
if not path:
return
from vistir.compat import Path
if not isinstance(path, Path):
path = Path(path)
if not path.is_dir():
path = path.parent
pp_toml = path.joinpath("pyproject.toml")
setup_py = path.joinpath("setup.py")
if not pp_toml.exists():
if not setup_py.exists():
return None
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
pyproject_data = {}
with io.open(pp_toml.as_posix(), encoding="utf-8") as fh:
pyproject_data = tomlkit.loads(fh.read())
build_system = pyproject_data.get("build-system", None)
if build_system is None:
if setup_py.exists():
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
else:
requires = ["setuptools>=40.8", "wheel"]
backend = get_default_pyproject_backend()
build_system = {"requires": requires, "build-backend": backend}
pyproject_data["build_system"] = build_system
else:
requires = build_system.get("requires", ["setuptools>=40.8", "wheel"])
backend = build_system.get("build-backend", get_default_pyproject_backend())
return requires, backend
|
[
"\n Given a base path, look for the corresponding ``pyproject.toml`` file and return its\n build_requires and build_backend.\n\n :param AnyStr path: The root path of the project, should be a directory (will be truncated)\n :return: A 2 tuple of build requirements and the build backend\n :rtype: Optional[Tuple[List[AnyStr], AnyStr]]\n "
] |
Please provide a description of the function:def split_markers_from_line(line):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):
marker_sep = ";"
else:
marker_sep = "; "
markers = None
if marker_sep in line:
line, markers = line.split(marker_sep, 1)
markers = markers.strip() if markers else None
return line, markers
|
[
"Split markers from a dependency"
] |
Please provide a description of the function:def split_vcs_method_from_uri(uri):
# type: (AnyStr) -> Tuple[Optional[STRING_TYPE], STRING_TYPE]
vcs_start = "{0}+"
vcs = None # type: Optional[STRING_TYPE]
vcs = first([vcs for vcs in VCS_LIST if uri.startswith(vcs_start.format(vcs))])
if vcs:
vcs, uri = uri.split("+", 1)
return vcs, uri
|
[
"Split a vcs+uri formatted uri into (vcs, uri)"
] |
Please provide a description of the function:def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
if not isinstance(uri, six.string_types):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = urllib_parse.urlparse(uri)
path = parsed.path
ref = None
if "@" in path:
path, _, ref = path.rpartition("@")
parsed = parsed._replace(path=path)
return (urllib_parse.urlunparse(parsed), ref)
|
[
"\n Given a path or URI, check for a ref and split it from the path if it is present,\n returning a tuple of the original input and the ref or None.\n\n :param AnyStr uri: The path or URI to split\n :returns: A 2-tuple of the path or URI and the ref\n :rtype: Tuple[AnyStr, Optional[AnyStr]]\n "
] |
Please provide a description of the function:def key_from_ireq(ireq):
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req)
|
[
"Get a standardized key for an InstallRequirement."
] |
Please provide a description of the function:def key_from_req(req):
if hasattr(req, "key"):
# from pkg_resources, such as installed dists for pip-sync
key = req.key
else:
# from packaging, such as install requirements from requirements.txt
key = req.name
key = key.replace("_", "-").lower()
return key
|
[
"Get an all-lowercase version of the requirement's name."
] |
Please provide a description of the function:def _requirement_to_str_lowercase_name(requirement):
parts = [requirement.name.lower()]
if requirement.extras:
parts.append("[{0}]".format(",".join(sorted(requirement.extras))))
if requirement.specifier:
parts.append(str(requirement.specifier))
if requirement.url:
parts.append("@ {0}".format(requirement.url))
if requirement.marker:
parts.append("; {0}".format(requirement.marker))
return "".join(parts)
|
[
"\n Formats a packaging.requirements.Requirement with a lowercase name.\n\n This is simply a copy of\n https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124\n modified to lowercase the dependency name.\n\n Previously, we were invoking the original Requirement.__str__ method and\n lower-casing the entire result, which would lowercase the name, *and* other,\n important stuff that should not be lower-cased (such as the marker). See\n this issue for more information: https://github.com/pypa/pipenv/issues/2113.\n "
] |
Please provide a description of the function:def format_requirement(ireq):
if ireq.editable:
line = "-e {}".format(ireq.link)
else:
line = _requirement_to_str_lowercase_name(ireq.req)
if str(ireq.req.marker) != str(ireq.markers):
if not ireq.req.marker:
line = "{}; {}".format(line, ireq.markers)
else:
name, markers = line.split(";", 1)
markers = markers.strip()
line = "{}; ({}) and ({})".format(name, markers, ireq.markers)
return line
|
[
"\n Generic formatter for pretty printing InstallRequirements to the terminal\n in a less verbose way than using its `__str__` method.\n "
] |
Please provide a description of the function:def format_specifier(ireq):
# TODO: Ideally, this is carried over to the pip library itself
specs = ireq.specifier._specs if ireq.req is not None else []
specs = sorted(specs, key=lambda x: x._spec[1])
return ",".join(str(s) for s in specs) or "<any>"
|
[
"\n Generic formatter for pretty printing the specifier part of\n InstallRequirements to the terminal.\n "
] |
Please provide a description of the function:def as_tuple(ireq):
if not is_pinned_requirement(ireq):
raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))
name = key_from_req(ireq.req)
version = first(ireq.specifier._specs)._spec[1]
extras = tuple(sorted(ireq.extras))
return name, version, extras
|
[
"\n Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.\n "
] |
Please provide a description of the function:def full_groupby(iterable, key=None):
return groupby(sorted(iterable, key=key), key=key)
|
[
"\n Like groupby(), but sorts the input on the group key first.\n "
] |
Please provide a description of the function:def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False):
if keyval is None:
if key is None:
keyval = lambda v: v
else:
keyval = lambda v: (key(v), v)
if unique:
return dict(keyval(v) for v in values)
lut = {}
for value in values:
k, v = keyval(value)
try:
s = lut[k]
except KeyError:
if use_lists:
s = lut[k] = list()
else:
s = lut[k] = set()
if use_lists:
s.append(v)
else:
s.add(v)
return dict(lut)
|
[
"\n Builds a dict-based lookup table (index) elegantly.\n\n Supports building normal and unique lookup tables. For example:\n\n >>> assert lookup_table(\n ... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {\n ... 'b': {'bar', 'baz'},\n ... 'f': {'foo'},\n ... 'q': {'quux', 'qux'}\n ... }\n\n For key functions that uniquely identify values, set unique=True:\n\n >>> assert lookup_table(\n ... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0], unique=True) == {\n ... 'b': 'baz',\n ... 'f': 'foo',\n ... 'q': 'quux'\n ... }\n\n The values of the resulting lookup table will be values, not sets.\n\n For extra power, you can even change the values while building up the LUT.\n To do so, use the `keyval` function instead of the `key` arg:\n\n >>> assert lookup_table(\n ... ['foo', 'bar', 'baz', 'qux', 'quux'],\n ... keyval=lambda s: (s[0], s[1:])) == {\n ... 'b': {'ar', 'az'},\n ... 'f': {'oo'},\n ... 'q': {'uux', 'ux'}\n ... }\n "
] |
Please provide a description of the function:def make_install_requirement(name, version, extras, markers, constraint=False):
# If no extras are specified, the extras string is blank
from pip_shims.shims import install_req_from_line
extras_string = ""
if extras:
# Sort extras for stability
extras_string = "[{}]".format(",".join(sorted(extras)))
if not markers:
return install_req_from_line(
str("{}{}=={}".format(name, extras_string, version)), constraint=constraint
)
else:
return install_req_from_line(
str("{}{}=={}; {}".format(name, extras_string, version, str(markers))),
constraint=constraint,
)
|
[
"\n Generates an :class:`~pip._internal.req.req_install.InstallRequirement`.\n\n Create an InstallRequirement from the supplied metadata.\n\n :param name: The requirement's name.\n :type name: str\n :param version: The requirement version (must be pinned).\n :type version: str.\n :param extras: The desired extras.\n :type extras: list[str]\n :param markers: The desired markers, without a preceding semicolon.\n :type markers: str\n :param constraint: Whether to flag the requirement as a constraint, defaults to False.\n :param constraint: bool, optional\n :return: A generated InstallRequirement\n :rtype: :class:`~pip._internal.req.req_install.InstallRequirement`\n "
] |
Please provide a description of the function:def clean_requires_python(candidates):
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
from_location = attrgetter("location.requires_python")
requires_python = getattr(c, "requires_python", from_location(c))
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates
|
[
"Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."
] |
Please provide a description of the function:def get_name_variants(pkg):
# type: (STRING_TYPE) -> Set[STRING_TYPE]
if not isinstance(pkg, six.string_types):
raise TypeError("must provide a string to derive package names")
from pkg_resources import safe_name
from packaging.utils import canonicalize_name
pkg = pkg.lower()
names = {safe_name(pkg), canonicalize_name(pkg), pkg.replace("-", "_")}
return names
|
[
"\n Given a packager name, get the variants of its name for both the canonicalized\n and \"safe\" forms.\n\n :param AnyStr pkg: The package to lookup\n :returns: A list of names.\n :rtype: Set\n "
] |
Please provide a description of the function:def _best_version(fields):
def _has_marker(keys, markers):
for marker in markers:
if marker in keys:
return True
return False
keys = []
for key, value in fields.items():
if value in ([], 'UNKNOWN', None):
continue
keys.append(key)
possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.0', '2.1']
# first let's try to see if a field is not part of one of the version
for key in keys:
if key not in _241_FIELDS and '1.0' in possible_versions:
possible_versions.remove('1.0')
logger.debug('Removed 1.0 due to %s', key)
if key not in _314_FIELDS and '1.1' in possible_versions:
possible_versions.remove('1.1')
logger.debug('Removed 1.1 due to %s', key)
if key not in _345_FIELDS and '1.2' in possible_versions:
possible_versions.remove('1.2')
logger.debug('Removed 1.2 due to %s', key)
if key not in _566_FIELDS and '1.3' in possible_versions:
possible_versions.remove('1.3')
logger.debug('Removed 1.3 due to %s', key)
if key not in _566_FIELDS and '2.1' in possible_versions:
if key != 'Description': # In 2.1, description allowed after headers
possible_versions.remove('2.1')
logger.debug('Removed 2.1 due to %s', key)
if key not in _426_FIELDS and '2.0' in possible_versions:
possible_versions.remove('2.0')
logger.debug('Removed 2.0 due to %s', key)
# possible_version contains qualified versions
if len(possible_versions) == 1:
return possible_versions[0] # found !
elif len(possible_versions) == 0:
logger.debug('Out of options - unknown metadata set: %s', fields)
raise MetadataConflictError('Unknown metadata set')
# let's see if one unique marker is found
is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)
is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)
is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)
is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)
if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_0) > 1:
raise MetadataConflictError('You used incompatible 1.1/1.2/2.0/2.1 fields')
# we have the choice, 1.0, or 1.2, or 2.0
# - 1.0 has a broken Summary field but works with all tools
# - 1.1 is to avoid
# - 1.2 fixes Summary but has little adoption
# - 2.0 adds more features and is very new
if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_0:
# we couldn't find any specific marker
if PKG_INFO_PREFERRED_VERSION in possible_versions:
return PKG_INFO_PREFERRED_VERSION
if is_1_1:
return '1.1'
if is_1_2:
return '1.2'
if is_2_1:
return '2.1'
return '2.0'
|
[
"Detect the best version depending on the fields used."
] |
Please provide a description of the function:def _get_name_and_version(name, version, for_filename=False):
if for_filename:
# For both name and version any runs of non-alphanumeric or '.'
# characters are replaced with a single '-'. Additionally any
# spaces in the version string become '.'
name = _FILESAFE.sub('-', name)
version = _FILESAFE.sub('-', version.replace(' ', '.'))
return '%s-%s' % (name, version)
|
[
"Return the distribution name with version.\n\n If for_filename is true, return a filename-escaped form."
] |
Please provide a description of the function:def read(self, filepath):
fp = codecs.open(filepath, 'r', encoding='utf-8')
try:
self.read_file(fp)
finally:
fp.close()
|
[
"Read the metadata values from a file path."
] |
Please provide a description of the function:def write(self, filepath, skip_unknown=False):
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close()
|
[
"Write the metadata fields to filepath."
] |
Please provide a description of the function:def write_file(self, fileobject, skip_unknown=False):
self.set_metadata_version()
for field in _version2fieldlist(self['Metadata-Version']):
values = self.get(field)
if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
continue
if field in _ELEMENTSFIELD:
self._write_field(fileobject, field, ','.join(values))
continue
if field not in _LISTFIELDS:
if field == 'Description':
if self.metadata_version in ('1.0', '1.1'):
values = values.replace('\n', '\n ')
else:
values = values.replace('\n', '\n |')
values = [values]
if field in _LISTTUPLEFIELDS:
values = [','.join(value) for value in values]
for value in values:
self._write_field(fileobject, field, value)
|
[
"Write the PKG-INFO format data to a file object."
] |
Please provide a description of the function:def update(self, other=None, **kwargs):
def _set(key, value):
if key in _ATTR2FIELD and value:
self.set(self._convert_name(key), value)
if not other:
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
_set(k, v)
|
[
"Set metadata values from the given iterable `other` and kwargs.\n\n Behavior is like `dict.update`: If `other` has a ``keys`` method,\n they are looped over and ``self[key]`` is assigned ``other[key]``.\n Else, ``other`` is an iterable of ``(key, value)`` iterables.\n\n Keys that don't match a metadata field or that have an empty value are\n dropped.\n "
] |
Please provide a description of the function:def set(self, name, value):
name = self._convert_name(name)
if ((name in _ELEMENTSFIELD or name == 'Platform') and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [v.strip() for v in value.split(',')]
else:
value = []
elif (name in _LISTFIELDS and
not isinstance(value, (list, tuple))):
if isinstance(value, string_types):
value = [value]
else:
value = []
if logger.isEnabledFor(logging.WARNING):
project_name = self['Name']
scheme = get_scheme(self.scheme)
if name in _PREDICATE_FIELDS and value is not None:
for v in value:
# check that the values are valid
if not scheme.is_valid_matcher(v.split(';')[0]):
logger.warning(
"'%s': '%s' is not valid (field '%s')",
project_name, v, name)
# FIXME this rejects UNKNOWN, is that right?
elif name in _VERSIONS_FIELDS and value is not None:
if not scheme.is_valid_constraint_list(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
elif name in _VERSION_FIELDS and value is not None:
if not scheme.is_valid_version(value):
logger.warning("'%s': '%s' is not a valid version (field '%s')",
project_name, value, name)
if name in _UNICODEFIELDS:
if name == 'Description':
value = self._remove_line_prefix(value)
self._fields[name] = value
|
[
"Control then set a metadata field."
] |
Please provide a description of the function:def get(self, name, default=_MISSING):
name = self._convert_name(name)
if name not in self._fields:
if default is _MISSING:
default = self._default_value(name)
return default
if name in _UNICODEFIELDS:
value = self._fields[name]
return value
elif name in _LISTFIELDS:
value = self._fields[name]
if value is None:
return []
res = []
for val in value:
if name not in _LISTTUPLEFIELDS:
res.append(val)
else:
# That's for Project-URL
res.append((val[0], val[1]))
return res
elif name in _ELEMENTSFIELD:
value = self._fields[name]
if isinstance(value, string_types):
return value.split(',')
return self._fields[name]
|
[
"Get a metadata field."
] |
Please provide a description of the function:def todict(self, skip_missing=False):
self.set_metadata_version()
mapping_1_0 = (
('metadata_version', 'Metadata-Version'),
('name', 'Name'),
('version', 'Version'),
('summary', 'Summary'),
('home_page', 'Home-page'),
('author', 'Author'),
('author_email', 'Author-email'),
('license', 'License'),
('description', 'Description'),
('keywords', 'Keywords'),
('platform', 'Platform'),
('classifiers', 'Classifier'),
('download_url', 'Download-URL'),
)
data = {}
for key, field_name in mapping_1_0:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
if self['Metadata-Version'] == '1.2':
mapping_1_2 = (
('requires_dist', 'Requires-Dist'),
('requires_python', 'Requires-Python'),
('requires_external', 'Requires-External'),
('provides_dist', 'Provides-Dist'),
('obsoletes_dist', 'Obsoletes-Dist'),
('project_url', 'Project-URL'),
('maintainer', 'Maintainer'),
('maintainer_email', 'Maintainer-email'),
)
for key, field_name in mapping_1_2:
if not skip_missing or field_name in self._fields:
if key != 'project_url':
data[key] = self[field_name]
else:
data[key] = [','.join(u) for u in self[field_name]]
elif self['Metadata-Version'] == '1.1':
mapping_1_1 = (
('provides', 'Provides'),
('requires', 'Requires'),
('obsoletes', 'Obsoletes'),
)
for key, field_name in mapping_1_1:
if not skip_missing or field_name in self._fields:
data[key] = self[field_name]
return data
|
[
"Return fields as a dict.\n\n Field names will be converted to use the underscore-lowercase style\n instead of hyphen-mixed case (i.e. home_page instead of Home-page).\n "
] |
Please provide a description of the function:def get_requirements(self, reqts, extras=None, env=None):
if self._legacy:
result = reqts
else:
result = []
extras = get_extras(extras or [], self.extras)
for d in reqts:
if 'extra' not in d and 'environment' not in d:
# unconditional
include = True
else:
if 'extra' not in d:
# Not extra-dependent - only environment-dependent
include = True
else:
include = d.get('extra') in extras
if include:
# Not excluded because of extras, check environment
marker = d.get('environment')
if marker:
include = interpret(marker, env)
if include:
result.extend(d['requires'])
for key in ('build', 'dev', 'test'):
e = ':%s:' % key
if e in extras:
extras.remove(e)
# A recursive call, but it should terminate since 'test'
# has been removed from the extras
reqts = self._data.get('%s_requires' % key, [])
result.extend(self.get_requirements(reqts, extras=extras,
env=env))
return result
|
[
"\n Base method to get dependencies, given a set of extras\n to satisfy and an optional environment context.\n :param reqts: A list of sometimes-wanted dependencies,\n perhaps dependent on extras and environment.\n :param extras: A list of optional components being requested.\n :param env: An optional environment for marker evaluation.\n "
] |
Please provide a description of the function:def remove_move(name):
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
|
[
"Remove item from six.moves."
] |
Please provide a description of the function:def ensure_binary(s, encoding='utf-8', errors='strict'):
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
[
"Coerce **s** to six.binary_type.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> encoded to `bytes`\n - `bytes` -> `bytes`\n "
] |
Please provide a description of the function:def ensure_str(s, encoding='utf-8', errors='strict'):
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
|
[
"Coerce *s* to `str`.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n "
] |
Please provide a description of the function:def ensure_text(s, encoding='utf-8', errors='strict'):
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
|
[
"Coerce *s* to six.text_type.\n\n For Python 2:\n - `unicode` -> `unicode`\n - `str` -> `unicode`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n "
] |
Please provide a description of the function:def python_2_unicode_compatible(klass):
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
|
[
"\n A decorator that defines __unicode__ and __str__ methods under Python 2.\n Under Python 3 it does nothing.\n\n To support Python 2 and 3 with a single code base, define a __str__ method\n returning text and apply this decorator to the class.\n "
] |
Please provide a description of the function:def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req
|
[
"Parse a requirements file and yield InstallRequirement instances.\n\n :param filename: Path or url of requirements file.\n :param finder: Instance of pip.index.PackageFinder.\n :param comes_from: Origin description of requirements.\n :param options: cli options.\n :param session: Instance of pip.download.PipSession.\n :param constraint: If true, parsing a constraint file rather than\n requirements file.\n :param wheel_cache: Instance of pip.wheel.WheelCache\n :param use_pep517: Value of the --use-pep517 option.\n "
] |
Please provide a description of the function:def preprocess(content, options):
# type: (Text, Optional[optparse.Values]) -> ReqFileLines
lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = skip_regex(lines_enum, options)
lines_enum = expand_env_variables(lines_enum)
return lines_enum
|
[
"Split, filter, and join lines, and return a line iterator\n\n :param content: the content of the requirements file\n :param options: cli options\n "
] |
Please provide a description of the function:def process_line(
line, # type: Text
filename, # type: str
line_number, # type: int
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None, # type: Optional[bool]
constraint=False # type: bool
):
# type: (...) -> Iterator[InstallRequirement]
parser = build_parser(line)
defaults = parser.get_default_values()
defaults.index_url = None
if finder:
defaults.format_control = finder.format_control
args_str, options_str = break_args_options(line)
# Prior to 2.7.3, shlex cannot deal with unicode entries
if sys.version_info < (2, 7, 3):
# https://github.com/python/mypy/issues/1174
options_str = options_str.encode('utf8') # type: ignore
# https://github.com/python/mypy/issues/1174
opts, _ = parser.parse_args(
shlex.split(options_str), defaults) # type: ignore
# preserve for the nested code path
line_comes_from = '%s %s (line %s)' % (
'-c' if constraint else '-r', filename, line_number,
)
# yield a line requirement
if args_str:
isolated = options.isolated_mode if options else False
if options:
cmdoptions.check_install_build_global(options, opts)
# get the options that apply to requirements
req_options = {}
for dest in SUPPORTED_OPTIONS_REQ_DEST:
if dest in opts.__dict__ and opts.__dict__[dest]:
req_options[dest] = opts.__dict__[dest]
yield install_req_from_line(
args_str, line_comes_from, constraint=constraint,
use_pep517=use_pep517,
isolated=isolated, options=req_options, wheel_cache=wheel_cache
)
# yield an editable requirement
elif opts.editables:
isolated = options.isolated_mode if options else False
yield install_req_from_editable(
opts.editables[0], comes_from=line_comes_from,
use_pep517=use_pep517,
constraint=constraint, isolated=isolated, wheel_cache=wheel_cache
)
# parse a nested requirements file
elif opts.requirements or opts.constraints:
if opts.requirements:
req_path = opts.requirements[0]
nested_constraint = False
else:
req_path = opts.constraints[0]
nested_constraint = True
# original file is over http
if SCHEME_RE.search(filename):
# do a url join so relative paths work
req_path = urllib_parse.urljoin(filename, req_path)
# original file and nested file are paths
elif not SCHEME_RE.search(req_path):
# do a join so relative paths work
req_path = os.path.join(os.path.dirname(filename), req_path)
# TODO: Why not use `comes_from='-r {} (line {})'` here as well?
parsed_reqs = parse_requirements(
req_path, finder, comes_from, options, session,
constraint=nested_constraint, wheel_cache=wheel_cache
)
for req in parsed_reqs:
yield req
# percolate hash-checking option upward
elif opts.require_hashes:
options.require_hashes = opts.require_hashes
# set finder options
elif finder:
if opts.index_url:
finder.index_urls = [opts.index_url]
if opts.no_index is True:
finder.index_urls = []
if opts.extra_index_urls:
finder.index_urls.extend(opts.extra_index_urls)
if opts.find_links:
# FIXME: it would be nice to keep track of the source
# of the find_links: support a find-links local path
# relative to a requirements file.
value = opts.find_links[0]
req_dir = os.path.dirname(os.path.abspath(filename))
relative_to_reqs_file = os.path.join(req_dir, value)
if os.path.exists(relative_to_reqs_file):
value = relative_to_reqs_file
finder.find_links.append(value)
if opts.pre:
finder.allow_all_prereleases = True
if opts.trusted_hosts:
finder.secure_origins.extend(
("*", host, "*") for host in opts.trusted_hosts)
|
[
"Process a single requirements line; This can result in creating/yielding\n requirements, or updating the finder.\n\n For lines that contain requirements, the only options that have an effect\n are from SUPPORTED_OPTIONS_REQ, and they are scoped to the\n requirement. Other options from SUPPORTED_OPTIONS may be present, but are\n ignored.\n\n For lines that do not contain requirements, the only options that have an\n effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may\n be present, but are ignored. These lines may contain multiple options\n (although our docs imply only one is supported), and all our parsed and\n affect the finder.\n\n :param constraint: If True, parsing a constraints file.\n :param options: OptionParser options that we may update\n "
] |
Please provide a description of the function:def break_args_options(line):
# type: (Text) -> Tuple[str, Text]
tokens = line.split(' ')
args = []
options = tokens[:]
for token in tokens:
if token.startswith('-') or token.startswith('--'):
break
else:
args.append(token)
options.pop(0)
return ' '.join(args), ' '.join(options)
|
[
"Break up the line into an args and options string. We only want to shlex\n (and then optparse) the options, not the args. args can contain markers\n which are corrupted by shlex.\n "
] |
Please provide a description of the function:def build_parser(line):
# type: (Text) -> optparse.OptionParser
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
# By default optparse sys.exits on parsing errors. We want to wrap
# that in our own exception.
def parser_exit(self, msg):
# add offending line
msg = 'Invalid requirement: %s\n%s' % (line, msg)
raise RequirementsFileParseError(msg)
# NOTE: mypy disallows assigning to a method
# https://github.com/python/mypy/issues/2427
parser.exit = parser_exit # type: ignore
return parser
|
[
"\n Return a parser for parsing requirement lines\n "
] |
Please provide a description of the function:def join_lines(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
primary_line_number = None
new_line = [] # type: List[Text]
for line_number, line in lines_enum:
if not line.endswith('\\') or COMMENT_RE.match(line):
if COMMENT_RE.match(line):
# this ensures comments are always matched later
line = ' ' + line
if new_line:
new_line.append(line)
yield primary_line_number, ''.join(new_line)
new_line = []
else:
yield line_number, line
else:
if not new_line:
primary_line_number = line_number
new_line.append(line.strip('\\'))
# last line contains \
if new_line:
yield primary_line_number, ''.join(new_line)
|
[
"Joins a line ending in '\\' with the previous line (except when following\n comments). The joined line takes on the index of the first line.\n "
] |
Please provide a description of the function:def ignore_comments(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line
|
[
"\n Strips comments and filter empty lines.\n "
] |
Please provide a description of the function:def skip_regex(lines_enum, options):
# type: (ReqFileLines, Optional[optparse.Values]) -> ReqFileLines
skip_regex = options.skip_requirements_regex if options else None
if skip_regex:
pattern = re.compile(skip_regex)
lines_enum = filterfalse(lambda e: pattern.search(e[1]), lines_enum)
return lines_enum
|
[
"\n Skip lines that match '--skip-requirements-regex' pattern\n\n Note: the regex pattern is only built once\n "
] |
Please provide a description of the function:def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
for line_number, line in lines_enum:
for env_var, var_name in ENV_VAR_RE.findall(line):
value = os.getenv(var_name)
if not value:
continue
line = line.replace(env_var, value)
yield line_number, line
|
[
"Replace all environment variables that can be retrieved via `os.getenv`.\n\n The only allowed format for environment variables defined in the\n requirement file is `${MY_VARIABLE_1}` to ensure two things:\n\n 1. Strings that contain a `$` aren't accidentally (partially) expanded.\n 2. Ensure consistency across platforms for requirement files.\n\n These points are the result of a discusssion on the `github pull\n request #3514 <https://github.com/pypa/pip/pull/3514>`_.\n\n Valid characters in variable names follow the `POSIX standard\n <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited\n to uppercase letter, digits and the `_` (underscore).\n "
] |
Please provide a description of the function:def finish(self):
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler)
|
[
"\n Restore the original SIGINT handler after finishing.\n\n This should happen regardless of whether the progress display finishes\n normally, or gets interrupted.\n "
] |
Please provide a description of the function:def handle_sigint(self, signum, frame):
self.finish()
self.original_handler(signum, frame)
|
[
"\n Call self.finish() before delegating to the original SIGINT handler.\n\n This handler should only be in place while the progress display is\n active.\n "
] |
Please provide a description of the function:def iter_fields(self, exclude=None, only=None):
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
|
[
"This method iterates over all fields that are defined and yields\n ``(key, value)`` tuples. Per default all fields are returned, but\n it's possible to limit that to some fields by providing the `only`\n parameter or to exclude some using the `exclude` parameter. Both\n should be sets or tuples of field names.\n "
] |
Please provide a description of the function:def iter_child_nodes(self, exclude=None, only=None):
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
|
[
"Iterates over all direct child nodes of the node. This iterates\n over all fields and yields the values of they are nodes. If the value\n of a field is a list all the nodes in that list are returned.\n "
] |
Please provide a description of the function:def find_all(self, node_type):
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result
|
[
"Find all the nodes of a given type. If the type is a tuple,\n the check is performed for any of the tuple items.\n "
] |
Please provide a description of the function:def set_ctx(self, ctx):
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self
|
[
"Reset the context of a node and all child nodes. Per default the\n parser will all generate nodes that have a 'load' context as it's the\n most common one. This method is used in the parser to set assignment\n targets and other nodes to a store context.\n "
] |
Please provide a description of the function:def set_lineno(self, lineno, override=False):
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
|
[
"Set the line numbers of the node and children."
] |
Please provide a description of the function:def set_environment(self, environment):
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
|
[
"Set the environment for all nodes."
] |
Please provide a description of the function:def from_untrusted(cls, value, lineno=None, environment=None):
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
|
[
"Return a const object if the value is representable as\n constant value in the generated code, otherwise it will raise\n an `Impossible` exception.\n "
] |
Please provide a description of the function:def build_wheel(source_dir, wheel_dir, config_settings=None):
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_wheel(config_settings)
env.pip_install(reqs)
return hooks.build_wheel(wheel_dir, config_settings)
|
[
"Build a wheel from a source directory using PEP 517 hooks.\n\n :param str source_dir: Source directory containing pyproject.toml\n :param str wheel_dir: Target directory to create wheel in\n :param dict config_settings: Options to pass to build backend\n\n This is a blocking function which will run pip in a subprocess to install\n build requirements.\n "
] |
Please provide a description of the function:def build_sdist(source_dir, sdist_dir, config_settings=None):
if config_settings is None:
config_settings = {}
requires, backend = _load_pyproject(source_dir)
hooks = Pep517HookCaller(source_dir, backend)
with BuildEnvironment() as env:
env.pip_install(requires)
reqs = hooks.get_requires_for_build_sdist(config_settings)
env.pip_install(reqs)
return hooks.build_sdist(sdist_dir, config_settings)
|
[
"Build an sdist from a source directory using PEP 517 hooks.\n\n :param str source_dir: Source directory containing pyproject.toml\n :param str sdist_dir: Target directory to place sdist in\n :param dict config_settings: Options to pass to build backend\n\n This is a blocking function which will run pip in a subprocess to install\n build requirements.\n "
] |
Please provide a description of the function:def pip_install(self, reqs):
if not reqs:
return
log.info('Calling pip to install %s', reqs)
check_call([
sys.executable, '-m', 'pip', 'install', '--ignore-installed',
'--prefix', self.path] + list(reqs))
|
[
"Install dependencies into this env by calling pip in a subprocess"
] |
Please provide a description of the function:def reparentChildren(self, newParent):
# XXX - should this method be made more general?
for child in self.childNodes:
newParent.appendChild(child)
self.childNodes = []
|
[
"Move all the children of the current node to newParent.\n This is needed so that trees that don't store text as nodes move the\n text in the correct way\n\n :arg newParent: the node to move all this node's children to\n\n "
] |
Please provide a description of the function:def elementInActiveFormattingElements(self, name):
for item in self.activeFormattingElements[::-1]:
# Check for Marker first because if it's a Marker it doesn't have a
# name attribute.
if item == Marker:
break
elif item.name == name:
return item
return False
|
[
"Check if an element exists between the end of the active\n formatting elements and the last marker. If it does, return it, else\n return false"
] |
Please provide a description of the function:def createElement(self, token):
name = token["name"]
namespace = token.get("namespace", self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token["data"]
return element
|
[
"Create an element but don't insert it anywhere"
] |
Please provide a description of the function:def _setInsertFromTable(self, value):
self._insertFromTable = value
if value:
self.insertElement = self.insertElementTable
else:
self.insertElement = self.insertElementNormal
|
[
"Switch the function used to insert an element from the\n normal one to the misnested table one and back again"
] |
Please provide a description of the function:def insertElementTable(self, token):
element = self.createElement(token)
if self.openElements[-1].name not in tableInsertModeElements:
return self.insertElementNormal(token)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
if insertBefore is None:
parent.appendChild(element)
else:
parent.insertBefore(element, insertBefore)
self.openElements.append(element)
return element
|
[
"Create an element and insert it into the tree"
] |
Please provide a description of the function:def insertText(self, data, parent=None):
if parent is None:
parent = self.openElements[-1]
if (not self.insertFromTable or (self.insertFromTable and
self.openElements[-1].name
not in tableInsertModeElements)):
parent.insertText(data)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
parent.insertText(data, insertBefore)
|
[
"Insert text data."
] |
Please provide a description of the function:def getTableMisnestedNodePosition(self):
# The foster parent element is the one which comes before the most
# recently opened table element
# XXX - this is really inelegant
lastTable = None
fosterParent = None
insertBefore = None
for elm in self.openElements[::-1]:
if elm.name == "table":
lastTable = elm
break
if lastTable:
# XXX - we should really check that this parent is actually a
# node here
if lastTable.parent:
fosterParent = lastTable.parent
insertBefore = lastTable
else:
fosterParent = self.openElements[
self.openElements.index(lastTable) - 1]
else:
fosterParent = self.openElements[0]
return fosterParent, insertBefore
|
[
"Get the foster parent element, and sibling to insert before\n (or None) when inserting a misnested table node"
] |
Please provide a description of the function:def getFragment(self):
# assert self.innerHTML
fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment
|
[
"Return the final fragment"
] |
Please provide a description of the function:def evaluate(self, environment=None):
current_environment = default_environment()
if environment is not None:
current_environment.update(environment)
return _evaluate_markers(self._markers, current_environment)
|
[
"Evaluate a marker.\n\n Return the boolean from evaluating the given marker against the\n environment. environment is an optional argument to override all or\n part of the determined environment.\n\n The environment is determined from the current Python process.\n "
] |
Please provide a description of the function:def _allow_all_wheels():
original_wheel_supported = Wheel.supported
original_support_index_min = Wheel.support_index_min
Wheel.supported = _wheel_supported
Wheel.support_index_min = _wheel_support_index_min
yield
Wheel.supported = original_wheel_supported
Wheel.support_index_min = original_support_index_min
|
[
"Monkey patch pip.Wheel to allow all wheels\n\n The usual checks against platforms and Python versions are ignored to allow\n fetching all available entries in PyPI. This also saves the candidate cache\n and set a new one, or else the results from the previous non-patched calls\n will interfere.\n "
] |
Please provide a description of the function:def create(self):
if self.path is not None:
logger.debug(
"Skipped creation of temporary directory: {}".format(self.path)
)
return
# We realpath here because some systems have their default tmpdir
# symlinked to another directory. This tends to confuse build
# scripts, so we canonicalize the path by traversing potential
# symlinks here.
self.path = os.path.realpath(
tempfile.mkdtemp(prefix="pip-{}-".format(self.kind))
)
self._register_finalizer()
logger.debug("Created temporary directory: {}".format(self.path))
|
[
"Create a temporary directory and store its path in self.path\n "
] |
Please provide a description of the function:def cleanup(self):
if getattr(self._finalizer, "detach", None) and self._finalizer.detach():
if os.path.exists(self.path):
try:
rmtree(self.path)
except OSError:
pass
else:
self.path = None
|
[
"Remove the temporary directory created and reset state\n "
] |
Please provide a description of the function:def _generate_names(cls, name):
for i in range(1, len(name)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i - 1):
new_name = '~' + ''.join(candidate) + name[i:]
if new_name != name:
yield new_name
# If we make it this far, we will have to make a longer name
for i in range(len(cls.LEADING_CHARS)):
for candidate in itertools.combinations_with_replacement(
cls.LEADING_CHARS, i):
new_name = '~' + ''.join(candidate) + name
if new_name != name:
yield new_name
|
[
"Generates a series of temporary names.\n\n The algorithm replaces the leading characters in the name\n with ones that are valid filesystem characters, but are not\n valid package names (for both Python and pip definitions of\n package).\n "
] |
Please provide a description of the function:def detect(byte_str):
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
return detector.close()
|
[
"\n Detect the encoding of the given byte string.\n\n :param byte_str: The byte sequence to examine.\n :type byte_str: ``bytes`` or ``bytearray``\n "
] |
Please provide a description of the function:def unescape(self):
from ._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ("#x", "#X"):
return unichr(int(name[2:], 16))
elif name.startswith("#"):
return unichr(int(name[1:]))
except ValueError:
pass
# Don't modify unexpected input.
return m.group()
return _entity_re.sub(handle_match, text_type(self))
|
[
"Convert escaped markup back into a text string. This replaces\n HTML entities with the characters they represent.\n\n >>> Markup('Main » <em>About</em>').unescape()\n 'Main » <em>About</em>'\n "
] |
Please provide a description of the function:def escape(cls, s):
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
|
[
"Escape a string. Calls :func:`escape` and ensures that for\n subclasses the correct type is returned.\n "
] |
Please provide a description of the function:def populate_link(self, finder, upgrade, require_hashes):
# type: (PackageFinder, bool, bool) -> None
if self.link is None:
self.link = finder.find_requirement(self, upgrade)
if self._wheel_cache is not None and not require_hashes:
old_link = self.link
self.link = self._wheel_cache.get(self.link, self.name)
if old_link != self.link:
logger.debug('Using cached wheel link: %s', self.link)
|
[
"Ensure that if a link can be found for this, that it is found.\n\n Note that self.link may still be None - if Upgrade is False and the\n requirement is already installed.\n\n If require_hashes is True, don't use the wheel cache, because cached\n wheels, always built locally, have different hashes than the files\n downloaded from the index server and thus throw false hash mismatches.\n Furthermore, cached wheels at present have undeterministic contents due\n to file modification times.\n "
] |
Please provide a description of the function:def is_pinned(self):
# type: () -> bool
specifiers = self.specifier
return (len(specifiers) == 1 and
next(iter(specifiers)).operator in {'==', '==='})
|
[
"Return whether I am pinned to an exact version.\n\n For example, some-package==1.2 is pinned; some-package>1.2 is not.\n "
] |
Please provide a description of the function:def hashes(self, trust_internet=True):
# type: (bool) -> Hashes
good_hashes = self.options.get('hashes', {}).copy()
link = self.link if trust_internet else self.original_link
if link and link.hash:
good_hashes.setdefault(link.hash_name, []).append(link.hash)
return Hashes(good_hashes)
|
[
"Return a hash-comparer that considers my option- and URL-based\n hashes to be known-good.\n\n Hashes in URLs--ones embedded in the requirements file, not ones\n downloaded from an index server--are almost peers with ones from\n flags. They satisfy --require-hashes (whether it was implicitly or\n explicitly activated) but do not activate it. md5 and sha224 are not\n allowed in flags, which should nudge people toward good algos. We\n always OR all hashes together, even ones from URLs.\n\n :param trust_internet: Whether to trust URL-based (#md5=...) hashes\n downloaded from the internet, as by populate_link()\n\n "
] |
Please provide a description of the function:def _correct_build_location(self):
# type: () -> None
if self.source_dir is not None:
return
assert self.req is not None
assert self._temp_build_dir.path
assert (self._ideal_build_dir is not None and
self._ideal_build_dir.path) # type: ignore
old_location = self._temp_build_dir.path
self._temp_build_dir.path = None
new_location = self.build_location(self._ideal_build_dir)
if os.path.exists(new_location):
raise InstallationError(
'A package already exists in %s; please remove it to continue'
% display_path(new_location))
logger.debug(
'Moving package %s from %s to new location %s',
self, display_path(old_location), display_path(new_location),
)
shutil.move(old_location, new_location)
self._temp_build_dir.path = new_location
self._ideal_build_dir = None
self.source_dir = os.path.normpath(os.path.abspath(new_location))
self._egg_info_path = None
# Correct the metadata directory, if it exists
if self.metadata_directory:
old_meta = self.metadata_directory
rel = os.path.relpath(old_meta, start=old_location)
new_meta = os.path.join(new_location, rel)
new_meta = os.path.normpath(os.path.abspath(new_meta))
self.metadata_directory = new_meta
|
[
"Move self._temp_build_dir to self._ideal_build_dir/self.req.name\n\n For some requirements (e.g. a path to a directory), the name of the\n package is not available until we run egg_info, so the build_location\n will return a temporary directory and store the _ideal_build_dir.\n\n This is only called by self.run_egg_info to fix the temporary build\n directory.\n "
] |
Please provide a description of the function:def remove_temporary_source(self):
# type: () -> None
if self.source_dir and os.path.exists(
os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
logger.debug('Removing source in %s', self.source_dir)
rmtree(self.source_dir)
self.source_dir = None
self._temp_build_dir.cleanup()
self.build_env.cleanup()
|
[
"Remove the source files from this requirement, if they are marked\n for deletion"
] |
Please provide a description of the function:def load_pyproject_toml(self):
# type: () -> None
pep517_data = load_pyproject_toml(
self.use_pep517,
self.pyproject_toml,
self.setup_py,
str(self)
)
if pep517_data is None:
self.use_pep517 = False
else:
self.use_pep517 = True
requires, backend, check = pep517_data
self.requirements_to_check = check
self.pyproject_requires = requires
self.pep517_backend = Pep517HookCaller(self.setup_py_dir, backend)
# Use a custom function to call subprocesses
self.spin_message = ""
def runner(cmd, cwd=None, extra_environ=None):
with open_spinner(self.spin_message) as spinner:
call_subprocess(
cmd,
cwd=cwd,
extra_environ=extra_environ,
show_stdout=False,
spinner=spinner
)
self.spin_message = ""
self.pep517_backend._subprocess_runner = runner
|
[
"Load the pyproject.toml file.\n\n After calling this routine, all of the attributes related to PEP 517\n processing for this requirement have been set. In particular, the\n use_pep517 attribute can be used to determine whether we should\n follow the PEP 517 or legacy (setup.py) code path.\n "
] |
Please provide a description of the function:def prepare_metadata(self):
# type: () -> None
assert self.source_dir
with indent_log():
if self.use_pep517:
self.prepare_pep517_metadata()
else:
self.run_egg_info()
if not self.req:
if isinstance(parse_version(self.metadata["Version"]), Version):
op = "=="
else:
op = "==="
self.req = Requirement(
"".join([
self.metadata["Name"],
op,
self.metadata["Version"],
])
)
self._correct_build_location()
else:
metadata_name = canonicalize_name(self.metadata["Name"])
if canonicalize_name(self.req.name) != metadata_name:
logger.warning(
'Generating metadata for package %s '
'produced metadata for project name %s. Fix your '
'#egg=%s fragments.',
self.name, metadata_name, self.name
)
self.req = Requirement(metadata_name)
|
[
"Ensure that project metadata is available.\n\n Under PEP 517, call the backend hook to prepare the metadata.\n Under legacy processing, call setup.py egg-info.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.