text
stringlengths
81
112k
:param current_params: the current params and values for this argument as already entered :param cmd_param: the current command parameter :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In other words whether or not the this cmd_param argument can still accept valu...
:param ctx: context associated with the parsed command :param args: full list of args :param incomplete: the incomplete text to autocomplete :param cmd_param: command definition :return: all the possible user-specified completions for the param def get_user_autocompletions(ctx, args, incomplete, cmd_pa...
:param ctx: context associated with the parsed command :starts_with: string that visible commands must start with. :return: all visible (not hidden) commands that start with starts_with. def get_visible_commands_starting_with(ctx, starts_with): """ :param ctx: context associated with the parsed command...
:param cli: command definition :param prog_name: the program that is running :param args: full list of args :param incomplete: the incomplete text to autocomplete :return: all the possible completions for the incomplete def get_choices(cli, prog_name, args, incomplete): """ :param cli: command ...
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping def interpret(marker, execution_context=None): """ Interpret a marker and retu...
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(ex...
Colorize text using a reimplementation of the colorizer from https://github.com/pavdmyt/yaspin so that it works on windows. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white....
Increments the parser by n characters if the end of the input has not been reached. def inc_n(self, n, exception=None): # type: (int, Optional[ParseError]) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ return self._s...
Consume chars until min/max is satisfied is valid. def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ return self._src.consume(chars=chars, min=min, max=max)
Creates a generic "parse error" at the current position. def parse_error(self, exception=ParseError, *args): """ Creates a generic "parse error" at the current position. """ return self._src.parse_error(exception, *args)
Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged. def _merge_ws(self, item, container): # type: (Item, Container) -> bool """ Merges the given Item with the last one currently in the given Cont...
Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another. def _is_child(self, parent, child): # type: (str, str) -> bool """ Returns whether a key is strictly a child of another key. AoT siblings are not considered children of on...
Attempts to parse the next item and returns it, along with its key if the item is value-like. def _parse_item(self): # type: () -> Optional[Tuple[Optional[Key], Item]] """ Attempts to parse the next item and returns it, along with its key if the item is value-like. """ ...
Returns (comment_ws, comment, trail) If there is no comment, comment_ws and comment will simply be empty. def _parse_comment_trail(self): # type: () -> Tuple[str, str, str] """ Returns (comment_ws, comment, trail) If there is no comment, comment_ws and comment will simp...
Parses a key enclosed in either single or double quotes. def _parse_quoted_key(self): # type: () -> Key """ Parses a key enclosed in either single or double quotes. """ quote_style = self._current key_type = None dotted = False for t in KeyType: if t...
Parses a bare key. def _parse_bare_key(self): # type: () -> Key """ Parses a bare key. """ key_type = None dotted = False self.mark() while self._current.is_bare_key_char() and self.inc(): pass key = self.extract() if self._current...
Attempts to parse a value at the current position. def _parse_value(self): # type: () -> Item """ Attempts to parse a value at the current position. """ self.mark() c = self._current trivia = Trivia() if c == StringType.SLB.value: return self._parse...
Parses a table element. def _parse_table( self, parent_name=None ): # type: (Optional[str]) -> Tuple[Key, Union[Table, AoT]] """ Parses a table element. """ if self._current != "[": raise self.parse_error( InternalParserError, "_parse_table() cal...
Peeks ahead non-intrusively by cloning then restoring the initial state of the parser. Returns the name of the table about to be parsed, as well as whether it is part of an AoT. def _peek_table(self): # type: () -> Tuple[bool, str] """ Peeks ahead non-intrusively by cloning th...
Parses all siblings of the provided table first and bundles them into an AoT. def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT """ Parses all siblings of the provided table first and bundles them into an AoT. """ payload = [first] self._aot_s...
Peeks ahead n characters. n is the max number of characters that will be peeked. def _peek(self, n): # type: (int) -> str """ Peeks ahead n characters. n is the max number of characters that will be peeked. """ # we always want to restore after exiting this scope ...
Peeks ahead non-intrusively by cloning then restoring the initial state of the parser. Returns the unicode value is it's a valid one else None. def _peek_unicode( self, is_long ): # type: (bool) -> Tuple[Optional[str], Optional[str]] """ Peeks ahead non-intrusively by clon...
Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('...
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None,...
Deprecated. Use :func:`parse_url` instead. def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or 'http', p.hostname, p.port
Absolute path including the query string. def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
Network location including host and port def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Examp...
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. def split_template_path(template): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ ...
Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned t...
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method ...
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str def description_of(lines, name='stdin'): """ Return a string descri...
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes ...
Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If...
Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file. ...
Display the difference between modules in a file and imported modules. def diff(file_, imports): """Display the difference between modules in a file and imported modules.""" modules_not_imported = compare_modules(file_, imports) logging.info("The following modules are in {} but do not seem to be imported:...
Remove modules that aren't imported in project from file. def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_fun...
Reads requirements from a file like object and (optionally) from referenced files. :param fh: file like object to read from :param resolve: boolean. resolves referenced files. :return: generator def read_requirements(fh, resolve=False): """ Reads requirements from a file like object and (optionally...
Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip doe...
Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). def _ipaddress_match(ipname, host_ip): """Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ ...
Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `tr...
Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally. def _walk(top, topdown=True, onerror=None, followlinks=False): """Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally....
Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` wi...
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropria...
Marks a callback as wanting to receive the current context object as first argument. def pass_context(f): """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return up...
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). Th...
Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import upd...
Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` l...
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. ...
Shortcut for confirmation prompts that can be ignored by passing ``--yes`` as parameter. This is equivalent to decorating a function with :func:`option` with the following parameters:: def callback(ctx, param, value): if not value: ctx.abort() @click.command() ...
Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): ...
Adds a ``--help`` option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed. Like :func:`version_option`, this is implemented as eager option that prints in the callback and exits. All arg...
Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the u...
Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check ...
Return abbreviated implementation name. def get_abbr_impl(): # type: () -> str """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' ...
Return implementation version. def get_impl_ver(): # type: () -> str """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver
Return sys.version_info-like tuple for use in decrementing the minor version. def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issue...
Return our platform name 'win32', 'linux_x86_64 def get_platform(): # type: () -> str """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was ...
Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If Non...
Returns the Requests tuple auth for a given url from netrc. def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: ...
Tries to guess the filename of the given object. def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive wit...
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode...
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It ba...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it wi...
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} ...
Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing...
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = he...
Iterate over slices of a string. def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str def get_unicode_from_response(r): """Returns the requested content back in unicode. :par...
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fu...
This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool def address_in_network(ip, net): """This function allows you to check if an IP b...
Very simple check of the cidr format in no_proxy variable. :rtype: bool def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) ...
Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous v...
Returns whether we should bypass proxies or not. :rtype: bool def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projec...
Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A...
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a pre...
Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: ...
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). def check_header_validity(header): """Verifies that header value is a string which doesn't contain lea...
Given a url remove the fragment and the authentication part. :rtype: str def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not...
Move file pointer back to its recorded starting position so it can be read again on redirect. def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_...
This is very similar to Version.__str__, but has one subtle differences with the way it handles the release segment. def canonicalize_version(version): """ This is very similar to Version.__str__, but has one subtle differences with the way it handles the release segment. """ try: vers...
Generate the python source for a node tree. def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') ge...
Does the node have a safe representation? def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True ...
Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of na...
Create a copy of the current one. def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
Return an inner frame. def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
Fail with a :exc:`TemplateAssertionError`. def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename)
Enable buffering for the frame from that point onwards. def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
Return the buffer contents of the frame. def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self....
Yield or write into the frame buffer. def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
Simple shortcut for start_write + write + end_write. def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
Write a string into the output stream. def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_...
Combination of newline and write. def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
Add one or more newlines before the next write. def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno...
Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. def signature(self, node, f...
Pull all the dependencies. def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for na...
Dump the function def of a macro or call block. def macro_body(self, node, frame): """Dump the function def of a macro or call block.""" frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() ...
Dump the macro definition for the def created by macro_body. def macro_def(self, macro_ref, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, 'name', None) if len(mac...
Return a human readable position for the node. def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv