Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[Tuple[List[str], str, List[str]]]
has_pyproject = os.path.isfile(pyproject_toml)
... | [
"Load the pyproject.toml file.\n\n Parameters:\n use_pep517 - Has the user requested PEP 517 processing? None\n means the user hasn't explicitly specified.\n pyproject_toml - Location of the project's pyproject.toml file\n setup_py - Location of the project's setup.py fil... |
Please provide a description of the function:def iter_installable_versions(self):
for name in self._pyenv('install', '--list').out.splitlines():
try:
version = Version.parse(name.strip())
except ValueError:
continue
yield version | [
"Iterate through CPython versions available for Pipenv to install.\n "
] |
Please provide a description of the function:def find_version_to_install(self, name):
version = Version.parse(name)
if version.patch is not None:
return name
try:
best_match = max((
inst_version
for inst_version in self.iter_instal... | [
"Find a version in pyenv from the version supplied.\n\n A ValueError is raised if a matching version cannot be found.\n "
] |
Please provide a description of the function:def install(self, version):
c = self._pyenv(
'install', '-s', str(version),
timeout=PIPENV_INSTALL_TIMEOUT,
)
return c | [
"Install the given version with pyenv.\n\n The version must be a ``Version`` instance representing a version\n found in pyenv.\n\n A ValueError is raised if the given version does not have a match in\n pyenv. A PyenvError is raised if the pyenv command fails.\n "
] |
Please provide a description of the function:def parse_editable(editable_req):
# type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]]
url = editable_req
# If a file path is specified with extras, strip off the extras.
url_no_extras, extras = _strip_extras(url)
if os.path.isdir(url_no... | [
"Parses an editable requirement into:\n - a requirement name\n - an URL\n - extras\n - editable options\n Accepted requirements:\n svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir\n .[some_extra]\n "
] |
Please provide a description of the function:def deduce_helpful_msg(req):
# type: (str) -> str
msg = ""
if os.path.exists(req):
msg = " It does exist."
# Try to parse and check if it is a requirements file.
try:
with open(req, 'r') as fp:
# parse firs... | [
"Returns helpful msg in case requirements file does not exist,\n or cannot be parsed.\n\n :params req: Requirements file path\n "
] |
Please provide a description of the function:def install_req_from_line(
name, # type: str
comes_from=None, # type: Optional[Union[str, InstallRequirement]]
use_pep517=None, # type: Optional[bool]
isolated=False, # type: bool
options=None, # type: Optional[Dict[str, Any]]
wheel_cache=None, ... | [
"Creates an InstallRequirement from a name, which might be a\n requirement, directory containing 'setup.py', filename, or URL.\n "
] |
Please provide a description of the function:def url_to_file_path(url, filecache):
key = CacheController.cache_url(url)
return filecache._fn(key) | [
"Return the file cache path based on the URL.\n\n This does not ensure the file exists!\n "
] |
Please provide a description of the function:def write_pid_to_pidfile(pidfile_path):
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID fi... | [
" Write the PID in the named PID file.\n\n Get the numeric process ID (“PID”) of the current process\n and write it to the named file as a line of text.\n\n "
] |
Please provide a description of the function:def remove_existing_pidfile(pidfile_path):
try:
os.remove(pidfile_path)
except OSError as exc:
if exc.errno == errno.ENOENT:
pass
else:
raise | [
" Remove the named PID file if it exists.\n\n Removing a PID file that doesn't already exist puts us in the\n desired state, so we ignore the condition if the file does not\n exist.\n\n "
] |
Please provide a description of the function:def release(self):
if not self.is_locked():
raise NotLocked("%s is not locked" % self.path)
if not self.i_am_locking():
raise NotMyLock("%s is locked, but not by me" % self.path)
remove_existing_pidfile(self.path) | [
" Release the lock.\n\n Removes the PID file to release the lock, or raises an\n error if the current process does not hold the lock.\n\n "
] |
Please provide a description of the function:def export(self, location):
# Remove the location to make sure Bazaar can export it correctly
if os.path.exists(location):
rmtree(location)
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.path)
... | [
"\n Export the Bazaar repository at the url to the destination location\n "
] |
Please provide a description of the function:def search_packages_info(query):
installed = {}
for p in pkg_resources.working_set:
installed[canonicalize_name(p.project_name)] = p
query_names = [canonicalize_name(name) for name in query]
for dist in [installed[pkg] for pkg in query_names if... | [
"\n Gather details from installed distributions. Print distribution name,\n version, location, and installed files. Installed files requires a\n pip generated 'installed-files.txt' in the distributions '.egg-info'\n directory.\n "
] |
Please provide a description of the function:def print_results(distributions, list_files=False, verbose=False):
results_printed = False
for i, dist in enumerate(distributions):
results_printed = True
if i > 0:
logger.info("---")
name = dist.get('name', '')
requi... | [
"\n Print the informations from installed distributions found.\n "
] |
Please provide a description of the function:def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename) | [
"Convenience method that raises `exc` with the message, passed\n line number or last line number as well as the current name and\n filename.\n "
] |
Please provide a description of the function:def fail_unknown_tag(self, name, lineno=None):
return self._fail_ut_eof(name, self._end_token_stack, lineno) | [
"Called if the parser encounters an unknown tag. Tries to fail\n with a human readable error message that could help to identify\n the problem.\n "
] |
Please provide a description of the function:def fail_eof(self, end_tokens=None, lineno=None):
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno) | [
"Like fail_unknown_tag but for end of template situations."
] |
Please provide a description of the function:def is_tuple_end(self, extra_end_rules=None):
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
r... | [
"Are we at the end of a tuple?"
] |
Please provide a description of the function:def free_identifier(self, lineno=None):
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv | [
"Return a new free identifier as :class:`~jinja2.nodes.InternalName`."
] |
Please provide a description of the function:def parse_statement(self):
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _st... | [
"Parse a single statement."
] |
Please provide a description of the function:def parse_statements(self, end_tokens, drop_needle=False):
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort o... | [
"Parse multiple statements into a list until one of the end tokens\n is reached. This is used to parse the body of statements as it also\n parses template data if appropriate. The parser checks first if the\n current token is a colon and skips it if there is one. Then it checks\n for ... |
Please provide a description of the function:def parse_set(self):
lineno = next(self.stream).lineno
target = self.parse_assign_target(with_namespace=True)
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)... | [
"Parse an assign statement."
] |
Please provide a description of the function:def parse_for(self):
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
... | [
"Parse a for loop."
] |
Please provide a description of the function:def parse_if(self):
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
... | [
"Parse an if construct."
] |
Please provide a description of the function:def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None, with_namespace=False):
if with_namespace and self.stream.look().type == 'dot':
token = self.stream.expect('name')
next(s... | [
"Parse an assignment target. As Jinja2 allows assignments to\n tuples, this function can parse all allowed assignment targets. Per\n default assignments to tuples are parsed, that can be disable however\n by setting `with_tuple` to `False`. If only assignments to names are\n wanted `n... |
Please provide a description of the function:def parse(self):
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result | [
"Parse the whole template into a `Template` node."
] |
Please provide a description of the function:def get_trace(self):
'''This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. '''
tblist = traceback.extract_tb(sys.exc_info()[2])
t... | [] |
Please provide a description of the function:def parse_uri(uri):
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8]) | [
"Parses a URI using the regex given in Appendix B of RFC 3986.\n\n (scheme, authority, path, query, fragment) = parse_uri(uri)\n "
] |
Please provide a description of the function:def _urlnorm(cls, uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise Exception("Only absolute URIs are allowed. uri = %s" % uri)
scheme = scheme.lower()
authority = aut... | [
"Normalize the URL to create a safe key for the cache"
] |
Please provide a description of the function:def cached_request(self, request):
cache_url = self.cache_url(request.url)
logger.debug('Looking up "%s" in the cache', cache_url)
cc = self.parse_cache_control(request.headers)
# Bail out if the request insists on fresh data
... | [
"\n Return a cached response if it exists in the cache, otherwise\n return False.\n "
] |
Please provide a description of the function:def cache_response(self, request, response, body=None, status_codes=None):
# From httplib2: Don't cache 206's since we aren't going to
# handle byte range requests
cacheable_status_codes = status_codes or self.cacheable_status_... | [
"\n Algorithm for caching requests.\n\n This assumes a requests Response object.\n "
] |
Please provide a description of the function:def update_cached_response(self, request, response):
cache_url = self.cache_url(request.url)
cached_response = self.serializer.loads(request, self.cache.get(cache_url))
if not cached_response:
# we didn't have a cached response
... | [
"On a 304 we will get a new set of headers that we want to\n update our cached value with, assuming we have one.\n\n This should only ever be called when we've sent an ETag and\n gotten a 304 as the response.\n "
] |
Please provide a description of the function:def close (self):
if self.child_fd == -1:
return
self.flush()
os.close(self.child_fd)
self.child_fd = -1
self.closed = True | [
"Close the file descriptor.\n\n Calling this method a second time does nothing, but if the file\n descriptor was closed elsewhere, :class:`OSError` will be raised.\n "
] |
Please provide a description of the function:def isalive (self):
'''This checks if the file descriptor is still valid. If :func:`os.fstat`
does not raise an exception then we assume it is alive. '''
if self.child_fd == -1:
return False
try:
os.fstat(self.child_fd... | [] |
Please provide a description of the function:def read_nonblocking(self, size=1, timeout=-1):
if os.name == 'posix':
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
if self.use_poll:
... | [
"\n Read from the file descriptor and return the result as a string.\n\n The read_nonblocking method of :class:`SpawnBase` assumes that a call\n to os.read will not block (timeout parameter is ignored). This is not\n the case for POSIX file-like objects such as sockets and serial ports.\... |
Please provide a description of the function:def clear_caches():
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear() | [
"Jinja2 keeps internal caches for environments and lexers. These are\n used so that Jinja2 doesn't have to recreate environments and lexers all\n the time. Normally you don't have to care about that but if you are\n measuring memory consumption you may want to clean the caches.\n "
] |
Please provide a description of the function:def import_string(import_name, silent=False):
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
ob... | [
"Imports an object based on a string. This is useful if you want to\n use import paths as endpoints or something similar. An import path can\n be specified either in dotted notation (``xml.sax.saxutils.escape``)\n or with a colon as object delimiter (``xml.sax.saxutils:escape``).\n\n If the `silent` i... |
Please provide a description of the function:def pformat(obj, verbose=False):
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj) | [
"Prettyprint an object. Either use the `pretty` library or the\n builtin `pprint`.\n "
] |
Please provide a description of the function:def unicode_urlencode(obj, charset='utf-8', for_qs=False):
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = not for_qs and b'/' or b''
rv = text_type(url_quote(obj,... | [
"URL escapes a single bytestring or unicode string with the\n given charset if applicable to URL safe quoting under all rules\n that need to be considered under all supported Python versions.\n\n If non strings are provided they are converted to their unicode\n representation first.\n "
] |
Please provide a description of the function:def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
disabled_extensions=(),
default_for_string=True,
default=False):
enabled_patterns = tuple('.' + x.lstrip('.').lower()
... | [
"Intelligently sets the initial value of autoescaping based on the\n filename of the template. This is the recommended way to configure\n autoescaping if you do not want to write a custom function yourself.\n\n If you want to enable it for all templates created from strings or\n for all templates with ... |
Please provide a description of the function:def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'",... | [
"Works exactly like :func:`dumps` but is safe for use in ``<script>``\n tags. It accepts the same arguments and returns a JSON string. Note that\n this is available in templates through the ``|tojson`` filter which will\n also mark the result as safe. Due to how this function escapes certain\n charac... |
Please provide a description of the function:def copy(self):
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv | [
"Return a shallow copy of the instance."
] |
Please provide a description of the function:def setdefault(self, key, default=None):
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._w... | [
"Set `default` if the key is not in the cache otherwise\n leave unchanged. Return the value of this key.\n "
] |
Please provide a description of the function:def clear(self):
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release() | [
"Clear the cache."
] |
Please provide a description of the function:def items(self):
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result | [
"Return a list of items."
] |
Please provide a description of the function:def license_fallback(vendor_dir, sdist_name):
libname = libname_from_dir(sdist_name)
if libname not in HARDCODED_LICENSE_URLS:
raise ValueError('No hardcoded URL for {} license'.format(libname))
url = HARDCODED_LICENSE_URLS[libname]
_, _, name =... | [
"Hardcoded license URLs. Check when updating if those are still needed"
] |
Please provide a description of the function:def libname_from_dir(dirname):
parts = []
for part in dirname.split('-'):
if part[0].isdigit():
break
parts.append(part)
return '-'.join(parts) | [
"Reconstruct the library name without it's version"
] |
Please provide a description of the function:def license_destination(vendor_dir, libname, filename):
normal = vendor_dir / libname
if normal.is_dir():
return normal / filename
lowercase = vendor_dir / libname.lower().replace('-', '_')
if lowercase.is_dir():
return lowercase / filena... | [
"Given the (reconstructed) library name, find appropriate destination"
] |
Please provide a description of the function:def _convert_hashes(values):
hashes = {}
if not values:
return hashes
for value in values:
try:
name, value = value.split(":", 1)
except ValueError:
name = "sha256"
if name not in hashes:
ha... | [
"Convert Pipfile.lock hash lines into InstallRequirement option format.\n\n The option format uses a str-list mapping. Keys are hash algorithms, and\n the list contains all values of that algorithm.\n "
] |
Please provide a description of the function:def _suppress_distutils_logs():
f = distutils.log.Log._log
def _log(log, level, msg, args):
if level >= distutils.log.ERROR:
f(log, level, msg, args)
distutils.log.Log._log = _log
yield
distutils.log.Log._log = f | [
"Hack to hide noise generated by `setup.py develop`.\n\n There isn't a good way to suppress them now, so let's monky-patch.\n See https://bugs.python.org/issue25392.\n "
] |
Please provide a description of the function:def _find_egg_info(ireq):
root = ireq.setup_py_dir
directory_iterator = _iter_egg_info_directories(root, ireq.name)
try:
top_egg_info = next(directory_iterator)
except StopIteration: # No egg-info found. Wat.
return None
directory_... | [
"Find this package's .egg-info directory.\n\n Due to how sdists are designed, the .egg-info directory cannot be reliably\n found without running setup.py to aggregate all configurations. This\n function instead uses some heuristics to locate the egg-info directory\n that most likely represents this pack... |
Please provide a description of the function:def fs_str(string):
if isinstance(string, str):
return string
assert not isinstance(string, bytes)
return string.encode(_fs_encoding) | [
"Encodes a string into the proper filesystem encoding\n\n Borrowed from pip-tools\n "
] |
Please provide a description of the function:def _get_path(path):
if isinstance(path, (six.string_types, bytes)):
return path
path_type = type(path)
try:
path_repr = path_type.__fspath__(path)
except AttributeError:
return
if isinstance(path_repr, (six.string_types, byt... | [
"\n Fetch the string value from a path-like object\n\n Returns **None** if there is no string value.\n "
] |
Please provide a description of the function:def fs_encode(path):
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to encode")
if isinstance(path, six.text_type):
path = path.encode(_fs_encoding, _fs_encode_errors)
return path | [
"\n Encode a filesystem path to the proper filesystem encoding\n\n :param Union[str, bytes] path: A string-like path\n :returns: A bytes-encoded filesystem path representation\n "
] |
Please provide a description of the function:def fs_decode(path):
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to decode")
if isinstance(path, six.binary_type):
path = path.decode(_fs_encoding, _fs_decode_errors)
return path | [
"\n Decode a filesystem path using the proper filesystem encoding\n\n :param path: The filesystem path to decode from bytes or string\n :return: [description]\n :rtype: [type]\n "
] |
Please provide a description of the function:def trace_graph(graph):
result = {None: []}
for vertex in graph:
result[vertex] = []
for root in graph.iter_children(None):
paths = []
_trace_visit_vertex(graph, root, vertex, {None}, [None], paths)
result[vert... | [
"Build a collection of \"traces\" for each package.\n\n A trace is a list of names that eventually leads to the package. For\n example, if A and B are root dependencies, A depends on C and D, B\n depends on C, and C depends on D, the return value would be like::\n\n {\n None: [],\n ... |
Please provide a description of the function:def _validate_timeout(cls, value, name):
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
if isinstance(value, bool):
raise ValueError("Timeo... | [
" Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises Value... |
Please provide a description of the function:def clone(self):
# We can't use copy.deepcopy because that will also create a new object
# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
# detect the user default.
return Timeout(connect=self._connect, read=self._... | [
" Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n "
] |
Please provide a description of the function:def start_connect(self):
if self._start_connect is not None:
raise TimeoutStateError("Timeout timer has already been started.")
self._start_connect = current_time()
return self._start_connect | [
" Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n "
] |
Please provide a description of the function:def connect_timeout(self):
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total) | [
" Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n "
] |
Please provide a description of the function:def read_timeout(self):
if (self.total is not None and
self.total is not self.DEFAULT_TIMEOUT and
self._read is not None and
self._read is not self.DEFAULT_TIMEOUT):
# In case the connect timeout ha... | [
" Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has n... |
Please provide a description of the function:def _new_conn(self):
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
conn = soc... | [
"\n Establish a new connection via the SOCKS proxy.\n "
] |
Please provide a description of the function:def get_requirement_info(dist):
# type: (Distribution) -> RequirementInfo
if not dist_is_editable(dist):
return (None, False, [])
location = os.path.normcase(os.path.abspath(dist.location))
from pipenv.patched.notpip._internal.vcs import vcs, R... | [
"\n Compute and return values (req, editable, comments) for use in\n FrozenRequirement.from_dist().\n "
] |
Please provide a description of the function:def detect_proc():
pid = os.getpid()
for name in ('stat', 'status'):
if os.path.exists(os.path.join('/proc', str(pid), name)):
return name
raise ProcFormatError('unsupported proc format') | [
"Detect /proc filesystem style.\n\n This checks the /proc/{pid} directory for possible formats. Returns one of\n the followings as str:\n\n * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.\n * `status`: BSD-style, i.e. ``/proc/{pid}/status``.\n "
] |
Please provide a description of the function:def get_process_mapping():
stat_name = detect_proc()
self_tty = _get_stat(os.getpid(), stat_name)[0]
processes = {}
for pid in os.listdir('/proc'):
if not pid.isdigit():
continue
try:
tty, ppid = _get_stat(pid, sta... | [
"Try to look up the process tree via the /proc interface.\n "
] |
Please provide a description of the function:def NamedTemporaryFile(
mode="w+b",
buffering=-1,
encoding=None,
newline=None,
suffix=None,
prefix=None,
dir=None,
delete=True,
wrapper_class_override=None,
):
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, di... | [
"Create and return a temporary file.\n Arguments:\n 'prefix', 'suffix', 'dir' -- as for mkstemp.\n 'mode' -- the mode argument to io.open (default \"w+b\").\n 'buffering' -- the buffer size argument to io.open (default -1).\n 'encoding' -- the encoding argument to io.open (default None)\n 'newline... |
Please provide a description of the function:def fast_exit(code):
sys.stdout.flush()
sys.stderr.flush()
os._exit(code) | [
"Exit without garbage collection, this speeds up exit by about 10ms for\n things like bash completion.\n "
] |
Please provide a description of the function:def _bashcomplete(cmd, prog_name, complete_var=None):
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
from ._bashc... | [
"Internal handler for the bash completion support."
] |
Please provide a description of the function:def augment_usage_errors(ctx, param=None):
try:
yield
except BadParameter as e:
if e.ctx is None:
e.ctx = ctx
if param is not None and e.param is None:
e.param = param
raise
except UsageError as e:
... | [
"Context manager that attaches extra information to exceptions that\n fly.\n "
] |
Please provide a description of the function:def iter_params_for_processing(invocation_order, declaration_order):
def sort_key(item):
try:
idx = invocation_order.index(item)
except ValueError:
idx = float('inf')
return (not item.is_eager, idx)
return sorted(... | [
"Given a sequence of parameters in the order as should be considered\n for processing and an iterable of parameters that exist, this returns\n a list in the correct order as they should be processed.\n "
] |
Please provide a description of the function:def scope(self, cleanup=True):
if not cleanup:
self._depth += 1
try:
with self as rv:
yield rv
finally:
if not cleanup:
self._depth -= 1 | [
"This helper method can be used with the context object to promote\n it to the current thread local (see :func:`get_current_context`).\n The default behavior of this is to invoke the cleanup functions which\n can be disabled by setting `cleanup` to `False`. The cleanup\n functions are t... |
Please provide a description of the function:def command_path(self):
rv = ''
if self.info_name is not None:
rv = self.info_name
if self.parent is not None:
rv = self.parent.command_path + ' ' + rv
return rv.lstrip() | [
"The computed command path. This is used for the ``usage``\n information on the help page. It's automatically created by\n combining the info names of the chain of contexts to the root.\n "
] |
Please provide a description of the function:def find_root(self):
node = self
while node.parent is not None:
node = node.parent
return node | [
"Finds the outermost context."
] |
Please provide a description of the function:def find_object(self, object_type):
node = self
while node is not None:
if isinstance(node.obj, object_type):
return node.obj
node = node.parent | [
"Finds the closest object of a given type."
] |
Please provide a description of the function:def ensure_object(self, object_type):
rv = self.find_object(object_type)
if rv is None:
self.obj = rv = object_type()
return rv | [
"Like :meth:`find_object` but sets the innermost object to a\n new instance of `object_type` if it does not exist.\n "
] |
Please provide a description of the function:def lookup_default(self, name):
if self.default_map is not None:
rv = self.default_map.get(name)
if callable(rv):
rv = rv()
return rv | [
"Looks up the default for a parameter name. This by default\n looks into the :attr:`default_map` if available.\n "
] |
Please provide a description of the function:def invoke(*args, **kwargs):
self, callback = args[:2]
ctx = self
# It's also possible to invoke another command which might or
# might not have a callback. In that case we also fill
# in defaults and make a new context for ... | [
"Invokes a command callback in exactly the way it expects. There\n are two ways to invoke this method:\n\n 1. the first argument can be a callback and all other arguments and\n keyword arguments are forwarded directly to the function.\n 2. the first argument is a click command obj... |
Please provide a description of the function:def forward(*args, **kwargs):
self, cmd = args[:2]
# It's also possible to invoke another command which might or
# might not have a callback.
if not isinstance(cmd, Command):
raise TypeError('Callback is not a command.')
... | [
"Similar to :meth:`invoke` but fills in default keyword\n arguments from the current context if the other command expects\n it. This cannot invoke callbacks directly, only other commands.\n "
] |
Please provide a description of the function:def main(self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra):
# If we are in Python 3, we will verify that the environment is
# sane at this point or reject further execution to avoid a
# broken scr... | [
"This is the way to invoke a script with all the bells and\n whistles as a command line application. This will always terminate\n the application after a call. If this is not wanted, ``SystemExit``\n needs to be caught.\n\n This method is also available by directly calling the instance... |
Please provide a description of the function:def format_usage(self, ctx, formatter):
pieces = self.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces)) | [
"Writes the usage line into the formatter."
] |
Please provide a description of the function:def collect_usage_pieces(self, ctx):
rv = [self.options_metavar]
for param in self.get_params(ctx):
rv.extend(param.get_usage_pieces(ctx))
return rv | [
"Returns all the pieces that go into the usage line and returns\n it as a list of strings.\n "
] |
Please provide a description of the function:def get_help_option_names(self, ctx):
all_names = set(ctx.help_option_names)
for param in self.params:
all_names.difference_update(param.opts)
all_names.difference_update(param.secondary_opts)
return all_names | [
"Returns the names for the help option."
] |
Please provide a description of the function:def get_help_option(self, ctx):
help_options = self.get_help_option_names(ctx)
if not help_options or not self.add_help_option:
return
def show_help(ctx, param, value):
if value and not ctx.resilient_parsing:
... | [
"Returns the help option object."
] |
Please provide a description of the function:def make_parser(self, ctx):
parser = OptionParser(ctx)
for param in self.get_params(ctx):
param.add_to_parser(parser, ctx)
return parser | [
"Creates the underlying option parser for this command."
] |
Please provide a description of the function:def get_help(self, ctx):
formatter = ctx.make_formatter()
self.format_help(ctx, formatter)
return formatter.getvalue().rstrip('\n') | [
"Formats the help into a string and returns it. This creates a\n formatter and will call into the following formatting methods:\n "
] |
Please provide a description of the function:def get_short_help_str(self, limit=45):
return self.short_help or self.help and make_default_short_help(self.help, limit) or '' | [
"Gets short help for the command or makes it by shortening the long help string."
] |
Please provide a description of the function:def format_help(self, ctx, formatter):
self.format_usage(ctx, formatter)
self.format_help_text(ctx, formatter)
self.format_options(ctx, formatter)
self.format_epilog(ctx, formatter) | [
"Writes the help into the formatter if it exists.\n\n This calls into the following methods:\n\n - :meth:`format_usage`\n - :meth:`format_help_text`\n - :meth:`format_options`\n - :meth:`format_epilog`\n "
] |
Please provide a description of the function:def format_help_text(self, ctx, formatter):
if self.help:
formatter.write_paragraph()
with formatter.indentation():
help_text = self.help
if self.deprecated:
help_text += DEPRECATED_... | [
"Writes the help text to the formatter if it exists."
] |
Please provide a description of the function:def format_options(self, ctx, formatter):
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
opts.append(rv)
if opts:
with formatter.section('Op... | [
"Writes all the options into the formatter if they exist."
] |
Please provide a description of the function:def format_epilog(self, ctx, formatter):
if self.epilog:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.epilog) | [
"Writes the epilog into the formatter if it exists."
] |
Please provide a description of the function:def invoke(self, ctx):
_maybe_show_deprecated_notice(self)
if self.callback is not None:
return ctx.invoke(self.callback, **ctx.params) | [
"Given a context, this invokes the attached callback (if it exists)\n in the right way.\n "
] |
Please provide a description of the function:def resultcallback(self, replace=False):
def decorator(f):
old_callback = self.result_callback
if old_callback is None or replace:
self.result_callback = f
return f
def function(__value, *ar... | [
"Adds a result callback to the chain command. By default if a\n result callback is already registered this will chain them but\n this can be disabled with the `replace` parameter. The result\n callback is invoked with the return value of the subcommand\n (or the list of return values f... |
Please provide a description of the function:def format_commands(self, ctx, formatter):
commands = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
# What is this, the tool lied about a command. Ignore it
if cmd is None:
... | [
"Extra format methods for multi methods that adds all the commands\n after the options.\n "
] |
Please provide a description of the function:def add_command(self, cmd, name=None):
name = name or cmd.name
if name is None:
raise TypeError('Command has no name.')
_check_multicommand(self, name, cmd, register=True)
self.commands[name] = cmd | [
"Registers another :class:`Command` with this group. If the name\n is not provided, the name of the command is used.\n "
] |
Please provide a description of the function:def command(self, *args, **kwargs):
def decorator(f):
cmd = command(*args, **kwargs)(f)
self.add_command(cmd)
return cmd
return decorator | [
"A shortcut decorator for declaring and attaching a command to\n the group. This takes the same arguments as :func:`command` but\n immediately registers the created command with this instance by\n calling into :meth:`add_command`.\n "
] |
Please provide a description of the function:def group(self, *args, **kwargs):
def decorator(f):
cmd = group(*args, **kwargs)(f)
self.add_command(cmd)
return cmd
return decorator | [
"A shortcut decorator for declaring and attaching a group to\n the group. This takes the same arguments as :func:`group` but\n immediately registers the created command with this instance by\n calling into :meth:`add_command`.\n "
] |
Please provide a description of the function:def get_default(self, ctx):
# Otherwise go with the regular default.
if callable(self.default):
rv = self.default()
else:
rv = self.default
return self.type_cast_value(ctx, rv) | [
"Given a context variable this calculates the default value."
] |
Please provide a description of the function:def type_cast_value(self, ctx, value):
if self.type.is_composite:
if self.nargs <= 1:
raise TypeError('Attempted to invoke composite type '
'but nargs has been set to %s. This is '
... | [
"Given a value this runs it properly through the type system.\n This automatically handles things like `nargs` and `multiple` as\n well as composite types.\n "
] |
Please provide a description of the function:def get_error_hint(self, ctx):
hint_list = self.opts or [self.human_readable_name]
return ' / '.join('"%s"' % x for x in hint_list) | [
"Get a stringified version of the param for use in error messages to\n indicate which param caused the error.\n "
] |
Please provide a description of the function:def prompt_for_value(self, ctx):
# Calculate the default before prompting anything to be stable.
default = self.get_default(ctx)
# If this is a prompt for a flag we need to handle this
# differently.
if self.is_bool_flag:
... | [
"This is an alternative flow that can be activated in the full\n value processing if a value does not exist. It will prompt the\n user until a valid value exists and then returns the processed\n value as result.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.