text
stringlengths
81
112k
Return the last item of a sequence. def do_last(environment, seq): """Return the last item of a sequence.""" try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined('No last item, sequence was empty.')
Return a random item from the sequence. def do_random(context, seq): """Return a random item from the sequence.""" try: return random.choice(seq) except IndexError: return context.environment.undefined('No random item, sequence was empty.')
Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). def do_filesizeformat(value, binary=False): """Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). """ bytes = float(value) base = binary and 1024 or 1000 prefixes = [ (binary and 'KiB' or 'kB'), (binary and 'MiB' or 'MB'), (binary and 'GiB' or 'GB'), (binary and 'TiB' or 'TB'), (binary and 'PiB' or 'PB'), (binary and 'EiB' or 'EB'), (binary and 'ZiB' or 'ZB'), (binary and 'YiB' or 'YB') ] if bytes == 1: return '1 Byte' elif bytes < base: return '%d Bytes' % bytes else: for i, prefix in enumerate(prefixes): unit = base ** (i + 2) if bytes < unit: return '%.1f %s' % ((base * bytes / unit), prefix) return '%.1f %s' % ((base * bytes / unit), prefix)
Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ policies = eval_ctx.environment.policies rel = set((rel or '').split() or []) if nofollow: rel.add('nofollow') rel.update((policies['urlize.rel'] or '').split()) if target is None: target = policies['urlize.target'] rel = ' '.join(sorted(rel)) or None rv = urlize(value, trim_url_limit, rel=rel, target=target) if eval_ctx.autoescape: rv = Markup(rv) return rv
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. def do_indent( s, width=4, first=False, blank=False, indentfirst=None ): """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ if indentfirst is not None: warnings.warn(DeprecationWarning( 'The "indentfirst" argument is renamed to "first".' ), stacklevel=2) first = indentfirst s += u'\n' # this quirk is necessary for splitlines method indention = u' ' * width if blank: rv = (u'\n' + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += u'\n' + u'\n'.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally. def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally. """ if leeway is None: leeway = env.policies['truncate.leeway'] assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length) assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway if len(s) <= length + leeway: return s if killwords: return s[:length - len(end)] + end result = s[:length - len(end)].rsplit(' ', 1)[0] return result + end
Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument. .. versionadded:: 2.7 Added support for the `wrapstring` parameter. def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None): """ Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument. .. versionadded:: 2.7 Added support for the `wrapstring` parameter. """ if not wrapstring: wrapstring = environment.newline_sequence import textwrap return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words))
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values. def do_int(value, default=0, base=10): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values. """ try: if isinstance(value, string_types): return int(value, base) return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! def do_format(value, *args, **kwargs): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ if args and kwargs: raise FilterArgumentError('can\'t handle positional and keyword ' 'arguments at the same time') return soft_unicode(value) % (kwargs or args)
Strip SGML/XML tags and replace adjacent whitespace by one space. def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(text_type(value)).striptags()
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. def do_slice(value, slices, fill_with=None): """Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. """ seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> def do_batch(value, linecount, fill_with=None): """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> """ tmp = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 def do_round(value, precision=0, method='common'): """Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 """ if not method in ('common', 'ceil', 'floor'): raise FilterArgumentError('method must be common, ceil or floor') if method == 'common': return round(value, precision) func = getattr(math, method) return func(value * (10 ** precision)) / (10 ** precision)
Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja <ul> {% for group in persons|groupby('gender') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> Additionally it's possible to use tuple unpacking for the grouper and list: .. sourcecode:: html+jinja <ul> {% for grouper, list in persons|groupby('gender') %} ... {% endfor %} </ul> As you can see the item we're grouping by is stored in the `grouper` attribute and the `list` contains all the objects that have this grouper in common. .. versionchanged:: 2.6 It's now possible to use dotted notation to group by the child attribute of another attribute. def do_groupby(environment, value, attribute): """Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja <ul> {% for group in persons|groupby('gender') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> Additionally it's possible to use tuple unpacking for the grouper and list: .. sourcecode:: html+jinja <ul> {% for grouper, list in persons|groupby('gender') %} ... {% endfor %} </ul> As you can see the item we're grouping by is stored in the `grouper` attribute and the `list` contains all the objects that have this grouper in common. .. versionchanged:: 2.6 It's now possible to use dotted notation to group by the child attribute of another attribute. """ expr = make_attrgetter(environment, attribute) return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(value, key=expr), expr)]
Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right. def do_sum(environment, iterable, attribute=None, start=0): """Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right. """ if attribute is not None: iterable = imap(make_attrgetter(environment, attribute), iterable) return sum(iterable, start)
Reverse the object or return an iterator that iterates over it the other way round. def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must be iterable')
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. def do_attr(environment, obj, name): """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed and not \ environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7 def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7 """ seq, func = prepare_map(args, kwargs) if seq: for item in seq: yield func(item)
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 def do_tojson(eval_ctx, value, indent=None): """Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 """ policies = eval_ctx.environment.policies dumper = policies['json.dumps_function'] options = policies['json.dumps_kwargs'] if indent is not None: options = dict(options) options['indent'] = indent return htmlsafe_json_dumps(value, dumper=dumper, **options)
Entry Point for completion of main and subcommand options. def autocomplete(): """Entry Point for completion of main and subcommand options. """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for cmd, summary in get_summaries()] options = [] # subcommand try: subcommand_name = [w for w in cwords if w in subcommands][0] except IndexError: subcommand_name = None parser = create_main_parser() # subcommand options if subcommand_name: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = ( subcommand_name in ['show', 'uninstall'] and not current.startswith('-') ) if should_list_installed: installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = commands_dict[subcommand_name]() for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs)) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: options = auto_complete_paths(current, completion_type) options = ((opt, 0) for opt in options) for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += '=' print(opt_label) else: # show main parser options only when necessary opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) opts = (o for it in opts for o in it) if current.startswith('-'): for opt in opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, opts) if completion_type: subcommands = auto_complete_paths(current, completion_type) print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) def get_path_completion_type(cwords, cword, opts): """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith('-'): return for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split('/'): if cwords[cword - 2].split('=')[0] == o: if not opt.metavar or any( x in ('path', 'file', 'dir') for x in opt.metavar.split('/')): return opt.metavar
If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories def auto_complete_paths(current, completion_type): """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = (x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != 'dir' and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, '')
Build a wheel. * ireq: The InstallRequirement object to build * output_dir: The directory to build the wheel in. * finder: pip's internal Finder object to find the source out of ireq. * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs): """Build a wheel. * ireq: The InstallRequirement object to build * output_dir: The directory to build the wheel in. * finder: pip's internal Finder object to find the source out of ireq. * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. """ kwargs.update({"progress_bar": "off", "build_isolation": False}) with pip_shims.RequirementTracker() as req_tracker: if req_tracker: kwargs["req_tracker"] = req_tracker preparer = pip_shims.RequirementPreparer(**kwargs) builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache) return builder._build_one(ireq, output_dir)
Get python version string using subprocess from a given path. def get_python_version(path): # type: (str) -> str """Get python version string using subprocess from a given path.""" version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"] try: c = vistir.misc.run( version_cmd, block=True, nospin=True, return_object=True, combine_stderr=False, write_to_stdout=False, ) except OSError: raise InvalidPythonVersion("%s is not a valid python path" % path) if not c.out: raise InvalidPythonVersion("%s is not a valid python path" % path) return c.out.strip()
Returns whether a given path is a known executable from known executable extensions or has the executable bit toggled. :param path: The path to the target executable. :type path: :class:`~vistir.compat.Path` :return: True if the path has chmod +x, or is a readable, known executable extension. :rtype: bool def path_is_known_executable(path): # type: (vistir.compat.Path) -> bool """ Returns whether a given path is a known executable from known executable extensions or has the executable bit toggled. :param path: The path to the target executable. :type path: :class:`~vistir.compat.Path` :return: True if the path has chmod +x, or is a readable, known executable extension. :rtype: bool """ return ( path_is_executable(path) or os.access(str(path), os.R_OK) and path.suffix in KNOWN_EXTS )
Determine whether the supplied filename looks like a possible name of python. :param str name: The name of the provided file. :return: Whether the provided name looks like python. :rtype: bool def looks_like_python(name): # type: (str) -> bool """ Determine whether the supplied filename looks like a possible name of python. :param str name: The name of the provided file. :return: Whether the provided name looks like python. :rtype: bool """ if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS): return False match = RE_MATCHER.match(name) if match: return any(fnmatch(name, rule) for rule in MATCH_RULES) return False
Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path` def ensure_path(path): # type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path """ Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path` """ if isinstance(path, vistir.compat.Path): return path path = vistir.compat.Path(os.path.expandvars(path)) return path.absolute()
Return all valid pythons in a given path def filter_pythons(path): # type: (Union[str, vistir.compat.Path]) -> Iterable """Return all valid pythons in a given path""" if not isinstance(path, vistir.compat.Path): path = vistir.compat.Path(str(path)) if not path.is_dir(): return path if path_is_python(path) else None return filter(path_is_python, path.iterdir())
Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance :param Union[Sequence, PathEntry] path: The path or list of paths to expand :param bool only_python: Whether to filter to include only python paths, default True :returns: An iterator over the expanded set of path entries :rtype: Iterator[PathEntry] def expand_paths(path, only_python=True): # type: (Union[Sequence, PathEntry], bool) -> Iterator """ Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance :param Union[Sequence, PathEntry] path: The path or list of paths to expand :param bool only_python: Whether to filter to include only python paths, default True :returns: An iterator over the expanded set of path entries :rtype: Iterator[PathEntry] """ if path is not None and ( isinstance(path, Sequence) and not getattr(path.__class__, "__name__", "") == "PathEntry" ): for p in unnest(path): if p is None: continue for expanded in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield expanded elif path is not None and path.is_dir: for p in path.children.values(): if p is not None and p.is_python and p.as_python is not None: for sub_path in itertools.chain.from_iterable( expand_paths(p, only_python=only_python) ): yield sub_path else: if path is not None and path.is_python and path.as_python is not None: yield path
Get parts of part that must be os.path.joined with cache_dir def _get_cache_path_parts(self, link): # type: (Link) -> List[str] """Get parts of part that must be os.path.joined with cache_dir """ # We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts
Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts)
Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. def is_artifact(self): # type: () -> bool """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pipenv.patched.notpip._internal.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
Retrieves dependencies for the requirement from the dependency cache. def _get_dependencies_from_cache(ireq): """Retrieves dependencies for the requirement from the dependency cache. """ if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"): return if ireq.editable: return try: deps = DEPENDENCY_CACHE[ireq] pyrq = REQUIRES_PYTHON_CACHE[ireq] except KeyError: return # Preserving sanity: Run through the cache and make sure every entry if # valid. If this fails, something is wrong with the cache. Drop it. try: packaging.specifiers.SpecifierSet(pyrq) ireq_name = packaging.utils.canonicalize_name(ireq.name) if any(_is_cache_broken(line, ireq_name) for line in deps): broken = True else: broken = False except Exception: broken = True if broken: print("dropping broken cache for {0}".format(ireq.name)) del DEPENDENCY_CACHE[ireq] del REQUIRES_PYTHON_CACHE[ireq] return return deps, pyrq
Retrieves dependencies for the install requirement from the JSON API. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None def _get_dependencies_from_json(ireq, sources): """Retrieves dependencies for the install requirement from the JSON API. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements. :rtype: set(str) or None """ if os.environ.get("PASSA_IGNORE_JSON_API"): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ireq.extras: return try: version = get_pinned_version(ireq) except ValueError: return url_prefixes = [ proc_url[:-7] # Strip "/simple". for proc_url in ( raw_url.rstrip("/") for raw_url in (source.get("url", "") for source in sources) ) if proc_url.endswith("/simple") ] session = requests.session() for prefix in url_prefixes: url = "{prefix}/pypi/{name}/{version}/json".format( prefix=prefix, name=packaging.utils.canonicalize_name(ireq.name), version=version, ) try: dependencies = _get_dependencies_from_json_url(url, session) if dependencies is not None: return dependencies except Exception as e: print("unable to read dependencies via {0} ({1})".format(url, e)) session.close() return
Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why); some are specified with markers. So we jump though these terrible hoops to know exactly what we need. The extra extraction is not comprehensive. Tt assumes the marker is NEVER something like `extra == "foo" and extra == "bar"`. I guess this never makes sense anyway? Markers are just terrible. def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why); some are specified with markers. So we jump though these terrible hoops to know exactly what we need. The extra extraction is not comprehensive. Tt assumes the marker is NEVER something like `extra == "foo" and extra == "bar"`. I guess this never makes sense anyway? Markers are just terrible. """ extras = extras or () requirements = [] for entry in metadata.run_requires: if isinstance(entry, six.text_type): entry = {"requires": [entry]} extra = None else: extra = entry.get("extra") if extra is not None and extra not in extras: continue for line in entry.get("requires", []): r = requirementslib.Requirement.from_line(line) if r.markers: contained = get_contained_extras(r.markers) if (contained and not any(e in contained for e in extras)): continue marker = get_without_extra(r.markers) r.markers = str(marker) if marker else None line = r.as_line(include_hashes=False) requirements.append(line) return requirements
Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not None * Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN" def _read_requires_python(metadata): """Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not None * Metadata 1.2: metadata._legacy.get("Requires-Python") != "UNKNOWN" """ # TODO: Support more metadata formats. value = metadata.dictionary.get("requires_python") if value is not None: return value if metadata._legacy: value = metadata._legacy.get("Requires-Python") if value is not None and value != "UNKNOWN": return value return ""
Retrieves dependencies for the requirement from pipenv.patched.notpip internals. The current strategy is to try the followings in order, returning the first successful result. 1. Try to build a wheel out of the ireq, and read metadata out of it. 2. Read metadata out of the egg-info directory if it is present. def _get_dependencies_from_pip(ireq, sources): """Retrieves dependencies for the requirement from pipenv.patched.notpip internals. The current strategy is to try the followings in order, returning the first successful result. 1. Try to build a wheel out of the ireq, and read metadata out of it. 2. Read metadata out of the egg-info directory if it is present. """ extras = ireq.extras or () try: wheel = build_wheel(ireq, sources) except WheelBuildError: # XXX: This depends on a side effect of `build_wheel`. This block is # reached when it fails to build an sdist, where the sdist would have # been downloaded, extracted into `ireq.source_dir`, and partially # built (hopefully containing .egg-info). metadata = read_sdist_metadata(ireq) if not metadata: raise else: metadata = wheel.metadata requirements = _read_requirements(metadata, extras) requires_python = _read_requires_python(metadata) return requirements, requires_python
Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict] def get_dependencies(requirement, sources): """Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict] """ getters = [ _get_dependencies_from_cache, _cached(_get_dependencies_from_json, sources=sources), _cached(_get_dependencies_from_pip, sources=sources), ] ireq = requirement.as_ireq() last_exc = None for getter in getters: try: result = getter(ireq) except Exception as e: last_exc = sys.exc_info() continue if result is not None: deps, pyreq = result reqs = [requirementslib.Requirement.from_line(d) for d in deps] return reqs, pyreq if last_exc: six.reraise(*last_exc) raise RuntimeError("failed to get dependencies for {}".format( requirement.as_line(), ))
Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. def format_header_param(name, value): """ Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ if not any(ch in value for ch in '"\\\r\n'): result = '%s="%s"' % (name, value) try: result.encode('ascii') except (UnicodeEncodeError, UnicodeDecodeError): pass else: return result if not six.PY3 and isinstance(value, six.text_type): # Python 2: value = value.encode('utf-8') value = email.utils.encode_rfc2231(value, 'utf-8') value = '%s*=%s' % (name, value) return value
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. def from_tuples(cls, fieldname, value): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls(fieldname, data, filename=filename) request_param.make_multipart(content_type=content_type) return request_param
Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. def _render_parts(self, header_parts): """ Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. """ parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: parts.append(self._render_part(name, value)) return '; '.join(parts)
Renders the headers for this request field. def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append('%s: %s' % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append('%s: %s' % (header_name, header_value)) lines.append('\r\n') return '\r\n'.join(lines)
Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. def make_multipart(self, content_disposition=None, content_type=None, content_location=None): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers['Content-Disposition'] = content_disposition or 'form-data' self.headers['Content-Disposition'] += '; '.join([ '', self._render_parts( (('name', self._name), ('filename', self._filename)) ) ]) self.headers['Content-Type'] = content_type self.headers['Content-Location'] = content_location
Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token def emptyTag(self, namespace, name, attrs, hasChildren=False): """Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token """ yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens def text(self, data): """Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens """ data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spaceCharacters) right = data[len(middle):] if middle: yield {"type": "Characters", "data": middle} if right: yield {"type": "SpaceCharacters", "data": right}
Returns the string to activate a virtualenv. This is POSIX-only at the moment since the compat (pexpect-based) shell does not work elsewhere anyway. def _get_activate_script(cmd, venv): """Returns the string to activate a virtualenv. This is POSIX-only at the moment since the compat (pexpect-based) shell does not work elsewhere anyway. """ # Suffix and source command for other shells. # Support for fish shell. if "fish" in cmd: suffix = ".fish" command = "source" # Support for csh shell. elif "csh" in cmd: suffix = ".csh" command = "source" else: suffix = "" command = "." # Escape any spaces located within the virtualenv path to allow # for proper activation. venv_location = str(venv).replace(" ", r"\ ") # The leading space can make history cleaner in some shells. return " {2} {0}/bin/activate{1}".format(venv_location, suffix, command)
Build and return a filename from the various components. def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a local version separator version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_pyver = [IMPVER] default_abi = [ABI] default_arch = [ARCH] else: is_pure = 'true' default_pyver = [PYVER] default_abi = ['none'] default_arch = ['any'] self.pyver = tags.get('pyver', default_pyver) self.abi = tags.get('abi', default_abi) self.arch = tags.get('arch', default_arch) libdir = paths[libkey] name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver archive_paths = [] # First, stuff which is not in site-packages for key in ('data', 'headers', 'scripts'): if key not in paths: continue path = paths[key] if os.path.isdir(path): for root, dirs, files in os.walk(path): for fn in files: p = fsdecode(os.path.join(root, fn)) rp = os.path.relpath(p, path) ap = to_posix(os.path.join(data_dir, key, rp)) archive_paths.append((ap, p)) if key == 'scripts' and not p.endswith('.exe'): with open(p, 'rb') as f: data = f.read() data = self.process_shebang(data) with open(p, 'wb') as f: f.write(data) # Now, stuff which is in site-packages, other than the # distinfo stuff. path = libdir distinfo = None for root, dirs, files in os.walk(path): if root == path: # At the top level only, save distinfo for later # and skip it for now for i, dn in enumerate(dirs): dn = fsdecode(dn) if dn.endswith('.dist-info'): distinfo = os.path.join(root, dn) del dirs[i] break assert distinfo, '.dist-info directory expected, not found' for fn in files: # comment out next suite to leave .pyc files in if fsdecode(fn).endswith(('.pyc', '.pyo')): continue p = os.path.join(root, fn) rp = to_posix(os.path.relpath(p, path)) archive_paths.append((rp, p)) # Now distinfo. Assumed to be flat, i.e. os.listdir is enough. files = os.listdir(distinfo) for fn in files: if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'): p = fsdecode(os.path.join(distinfo, fn)) ap = to_posix(os.path.join(info_dir, fn)) archive_paths.append((ap, p)) wheel_metadata = [ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version), 'Generator: distlib %s' % __version__, 'Root-Is-Purelib: %s' % is_pure, ] for pyver, abi, arch in self.tags: wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch)) p = os.path.join(distinfo, 'WHEEL') with open(p, 'w') as f: f.write('\n'.join(wheel_metadata)) ap = to_posix(os.path.join(info_dir, 'WHEEL')) archive_paths.append((ap, p)) # Now, at last, RECORD. # Paths in here are archive paths - nothing else makes sense. self.write_records((distinfo, info_dir), libdir, archive_paths) # Now, ready to build the zip file pathname = os.path.join(self.dirname, self.filename) self.build_zip(pathname, archive_paths) return pathname
Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 2.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``. def install(self, paths, maker, **kwargs): """ Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 2.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``. """ dry_run = maker.dry_run warner = kwargs.get('warner') lib_only = kwargs.get('lib_only', False) bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver metadata_name = posixpath.join(info_dir, METADATA_FILENAME) wheel_metadata_name = posixpath.join(info_dir, 'WHEEL') record_name = posixpath.join(info_dir, 'RECORD') wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: with zf.open(wheel_metadata_name) as bwf: wf = wrapper(bwf) message = message_from_file(wf) wv = message['Wheel-Version'].split('.', 1) file_version = tuple([int(i) for i in wv]) if (file_version != self.wheel_version) and warner: warner(self.wheel_version, file_version) if message['Root-Is-Purelib'] == 'true': libdir = paths['purelib'] else: libdir = paths['platlib'] records = {} with zf.open(record_name) as bf: with CSVReader(stream=bf) as reader: for row in reader: p = row[0] records[p] = row data_pfx = posixpath.join(data_dir, '') info_pfx = posixpath.join(info_dir, '') script_pfx = posixpath.join(data_dir, 'scripts', '') # make a new instance rather than a copy of maker's, # as we mutate it fileop = FileOperator(dry_run=dry_run) fileop.record = True # so we can rollback if needed bc = not sys.dont_write_bytecode # Double negatives. Lovely! outfiles = [] # for RECORD writing # for script copying/shebang processing workdir = tempfile.mkdtemp() # set target dir later # we default add_launchers to False, as the # Python Launcher should be used instead maker.source_dir = workdir maker.target_dir = None try: for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') # The signature file won't be in RECORD, # and we don't currently don't do anything with it if u_arcname.endswith('/RECORD.jws'): continue row = records[u_arcname] if row[2] and str(zinfo.file_size) != row[2]: raise DistlibException('size mismatch for ' '%s' % u_arcname) if row[1]: kind, value = row[1].split('=', 1) with zf.open(arcname) as bf: data = bf.read() _, digest = self.get_hash(data, kind) if digest != value: raise DistlibException('digest mismatch for ' '%s' % arcname) if lib_only and u_arcname.startswith((info_pfx, data_pfx)): logger.debug('lib_only: skipping %s', u_arcname) continue is_script = (u_arcname.startswith(script_pfx) and not u_arcname.endswith('.exe')) if u_arcname.startswith(data_pfx): _, where, rp = u_arcname.split('/', 2) outfile = os.path.join(paths[where], convert_path(rp)) else: # meant for site-packages. if u_arcname in (wheel_metadata_name, record_name): continue outfile = os.path.join(libdir, convert_path(u_arcname)) if not is_script: with zf.open(arcname) as bf: fileop.copy_stream(bf, outfile) outfiles.append(outfile) # Double check the digest of the written file if not dry_run and row[1]: with open(outfile, 'rb') as bf: data = bf.read() _, newdigest = self.get_hash(data, kind) if newdigest != digest: raise DistlibException('digest mismatch ' 'on write for ' '%s' % outfile) if bc and outfile.endswith('.py'): try: pyc = fileop.byte_compile(outfile, hashed_invalidation=bc_hashed_invalidation) outfiles.append(pyc) except Exception: # Don't give up if byte-compilation fails, # but log it and perhaps warn the user logger.warning('Byte-compilation failed', exc_info=True) else: fn = os.path.basename(convert_path(arcname)) workname = os.path.join(workdir, fn) with zf.open(arcname) as bf: fileop.copy_stream(bf, workname) dn, fn = os.path.split(outfile) maker.target_dir = dn filenames = maker.make(fn) fileop.set_executable_mode(filenames) outfiles.extend(filenames) if lib_only: logger.debug('lib_only: returning None') dist = None else: # Generate scripts # Try to get pydist.json so we can see if there are # any commands to generate. If this fails (e.g. because # of a legacy wheel), log a warning but don't give up. commands = None file_version = self.info['Wheel-Version'] if file_version == '1.0': # Use legacy info ep = posixpath.join(info_dir, 'entry_points.txt') try: with zf.open(ep) as bwf: epdata = read_exports(bwf) commands = {} for key in ('console', 'gui'): k = '%s_scripts' % key if k in epdata: commands['wrap_%s' % key] = d = {} for v in epdata[k].values(): s = '%s:%s' % (v.prefix, v.suffix) if v.flags: s += ' %s' % v.flags d[v.name] = s except Exception: logger.warning('Unable to read legacy script ' 'metadata, so cannot generate ' 'scripts') else: try: with zf.open(metadata_name) as bwf: wf = wrapper(bwf) commands = json.load(wf).get('extensions') if commands: commands = commands.get('python.commands') except Exception: logger.warning('Unable to read JSON metadata, so ' 'cannot generate scripts') if commands: console_scripts = commands.get('wrap_console', {}) gui_scripts = commands.get('wrap_gui', {}) if console_scripts or gui_scripts: script_dir = paths.get('scripts', '') if not os.path.isdir(script_dir): raise ValueError('Valid script path not ' 'specified') maker.target_dir = script_dir for k, v in console_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script) fileop.set_executable_mode(filenames) if gui_scripts: options = {'gui': True } for k, v in gui_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script, options) fileop.set_executable_mode(filenames) p = os.path.join(libdir, info_dir) dist = InstalledDistribution(p) # Write SHARED paths = dict(paths) # don't change passed in dict del paths['purelib'] del paths['platlib'] paths['lib'] = libdir p = dist.write_shared_locations(paths, dry_run) if p: outfiles.append(p) # Write RECORD dist.write_installed_files(outfiles, paths['prefix'], dry_run) return dist except Exception: # pragma: no cover logger.exception('installation failed.') fileop.rollback() raise finally: shutil.rmtree(workdir)
Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns. def update(self, modifier, dest_dir=None, **kwargs): """ Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns. """ def get_version(path_map, info_dir): version = path = None key = '%s/%s' % (info_dir, METADATA_FILENAME) if key not in path_map: key = '%s/PKG-INFO' % info_dir if key in path_map: path = path_map[key] version = Metadata(path=path).version return version, path def update_version(version, path): updated = None try: v = NormalizedVersion(version) i = version.find('-') if i < 0: updated = '%s+1' % version else: parts = [int(s) for s in version[i + 1:].split('.')] parts[-1] += 1 updated = '%s+%s' % (version[:i], '.'.join(str(i) for i in parts)) except UnsupportedVersionError: logger.debug('Cannot update non-compliant (PEP-440) ' 'version %r', version) if updated: md = Metadata(path=path) md.version = updated legacy = not path.endswith(METADATA_FILENAME) md.write(path=path, legacy=legacy) logger.debug('Version updated from %r to %r', version, updated) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver record_name = posixpath.join(info_dir, 'RECORD') with tempdir() as workdir: with ZipFile(pathname, 'r') as zf: path_map = {} for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') if u_arcname == record_name: continue if '..' in u_arcname: raise DistlibException('invalid entry in ' 'wheel: %r' % u_arcname) zf.extract(zinfo, workdir) path = os.path.join(workdir, convert_path(u_arcname)) path_map[u_arcname] = path # Remember the version. original_version, _ = get_version(path_map, info_dir) # Files extracted. Call the modifier. modified = modifier(path_map, **kwargs) if modified: # Something changed - need to build a new wheel. current_version, path = get_version(path_map, info_dir) if current_version and (current_version == original_version): # Add or update local version to signify changes. update_version(current_version, path) # Decide where the new wheel goes. if dest_dir is None: fd, newpath = tempfile.mkstemp(suffix='.whl', prefix='wheel-update-', dir=workdir) os.close(fd) else: if not os.path.isdir(dest_dir): raise DistlibException('Not a directory: %r' % dest_dir) newpath = os.path.join(dest_dir, self.filename) archive_paths = list(path_map.items()) distinfo = os.path.join(workdir, info_dir) info = distinfo, info_dir self.write_records(info, workdir, archive_paths) self.build_zip(newpath, archive_paths) if dest_dir is None: shutil.copyfile(newpath, pathname) return modified
Loads .env file into sys.environ. def load_dot_env(): """Loads .env file into sys.environ.""" if not environments.PIPENV_DONT_LOAD_ENV: # If the project doesn't exist yet, check current directory for a .env file project_directory = project.project_directory or "." dotenv_file = environments.PIPENV_DOTENV_LOCATION or os.sep.join( [project_directory, ".env"] ) if os.path.isfile(dotenv_file): click.echo( crayons.normal(fix_utf8("Loading .env environment variables…"), bold=True), err=True, ) else: if environments.PIPENV_DOTENV_LOCATION: click.echo( "{0}: file {1}={2} does not exist!!\n{3}".format( crayons.red("Warning", bold=True), crayons.normal("PIPENV_DOTENV_LOCATION", bold=True), crayons.normal(environments.PIPENV_DOTENV_LOCATION, bold=True), crayons.red("Not loading environment variables.", bold=True), ), err=True, ) dotenv.load_dotenv(dotenv_file, override=True)
Adds a given path to the PATH. def add_to_path(p): """Adds a given path to the PATH.""" if p not in os.environ["PATH"]: os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"])
Removes the virtualenv directory from the system. def cleanup_virtualenv(bare=True): """Removes the virtualenv directory from the system.""" if not bare: click.echo(crayons.red("Environment creation aborted.")) try: # Delete the virtualenv. vistir.path.rmtree(project.virtualenv_location) except OSError as e: click.echo( "{0} An error occurred while removing {1}!".format( crayons.red("Error: ", bold=True), crayons.green(project.virtualenv_location), ), err=True, ) click.echo(crayons.blue(e), err=True)
Creates a Pipfile for the project, if it doesn't exist. def ensure_pipfile(validate=True, skip_requirements=False, system=False): """Creates a Pipfile for the project, if it doesn't exist.""" from .environments import PIPENV_VIRTUALENV # Assert Pipfile exists. python = which("python") if not (USING_DEFAULT_PYTHON or system) else None if project.pipfile_is_empty: # Show an error message and exit if system is passed and no pipfile exists if system and not PIPENV_VIRTUALENV: raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for pre-existing Pipfile " "installation, not installation of specific packages. Aborting." ) # If there's a requirements file, but no Pipfile… if project.requirements_exists and not skip_requirements: click.echo( crayons.normal( fix_utf8("requirements.txt found, instead of Pipfile! Converting…"), bold=True, ) ) # Create a Pipfile… project.create_pipfile(python=python) with create_spinner("Importing requirements...") as sp: # Import requirements.txt. try: import_requirements() except Exception: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed...")) else: sp.ok(environments.PIPENV_SPINNER_OK_TEXT.format("Success!")) # Warn the user of side-effects. click.echo( u"{0}: Your {1} now contains pinned versions, if your {2} did. \n" "We recommend updating your {1} to specify the {3} version, instead." "".format( crayons.red("Warning", bold=True), crayons.normal("Pipfile", bold=True), crayons.normal("requirements.txt", bold=True), crayons.normal('"*"', bold=True), ) ) else: click.echo( crayons.normal(fix_utf8("Creating a Pipfile for this project…"), bold=True), err=True, ) # Create the pipfile if it doesn't exist. project.create_pipfile(python=python) # Validate the Pipfile's contents. if validate and project.virtualenv_exists and not PIPENV_SKIP_VALIDATION: # Ensure that Pipfile is using proper casing. p = project.parsed_pipfile changed = project.ensure_proper_casing() # Write changes out to disk. if changed: click.echo( crayons.normal(u"Fixing package names in Pipfile…", bold=True), err=True ) project.write_toml(p)
Find a Python installation from a given line. This tries to parse the line in various of ways: * Looks like an absolute path? Use it directly. * Looks like a py.exe call? Use py.exe to get the executable. * Starts with "py" something? Looks like a python command. Try to find it in PATH, and use it directly. * Search for "python" and "pythonX.Y" executables in PATH to find a match. * Nothing fits, return None. def find_a_system_python(line): """Find a Python installation from a given line. This tries to parse the line in various of ways: * Looks like an absolute path? Use it directly. * Looks like a py.exe call? Use py.exe to get the executable. * Starts with "py" something? Looks like a python command. Try to find it in PATH, and use it directly. * Search for "python" and "pythonX.Y" executables in PATH to find a match. * Nothing fits, return None. """ from .vendor.pythonfinder import Finder finder = Finder(system=False, global_search=True) if not line: return next(iter(finder.find_all_python_versions()), None) # Use the windows finder executable if (line.startswith("py ") or line.startswith("py.exe ")) and os.name == "nt": line = line.split(" ", 1)[1].lstrip("-") python_entry = find_python(finder, line) return python_entry
Creates a virtualenv, if one doesn't exist. def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv, if one doesn't exist.""" from .environments import PIPENV_USE_SYSTEM def abort(): sys.exit(1) global USING_DEFAULT_PYTHON if not project.virtualenv_exists: try: # Ensure environment variables are set properly. ensure_environment() # Ensure Python is available. python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() # Create the virtualenv. # Abort if --system (or running in a virtualenv). if PIPENV_USE_SYSTEM: click.echo( crayons.red( "You are attempting to re–create a virtualenv that " "Pipenv did not create. Aborting." ) ) sys.exit(1) do_create_virtualenv( python=python, site_packages=site_packages, pypi_mirror=pypi_mirror ) except KeyboardInterrupt: # If interrupted, cleanup the virtualenv. cleanup_virtualenv(bare=False) sys.exit(1) # If --three, --two, or --python were passed… elif (python) or (three is not None) or (site_packages is not False): USING_DEFAULT_PYTHON = False # Ensure python is installed before deleting existing virtual env python = ensure_python(three=three, python=python) if python is not None and not isinstance(python, six.string_types): python = python.path.as_posix() click.echo(crayons.red("Virtualenv already exists!"), err=True) # If VIRTUAL_ENV is set, there is a possibility that we are # going to remove the active virtualenv that the user cares # about, so confirm first. if "VIRTUAL_ENV" in os.environ: if not ( PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True) ): abort() click.echo( crayons.normal(fix_utf8("Removing existing virtualenv…"), bold=True), err=True ) # Remove the virtualenv. cleanup_virtualenv(bare=True) # Call this function again. ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, )
Ensures both Pipfile and virtualenv exist for the project. def ensure_project( three=None, python=None, validate=True, system=False, warn=True, site_packages=False, deploy=False, skip_requirements=False, pypi_mirror=None, clear=False, ): """Ensures both Pipfile and virtualenv exist for the project.""" from .environments import PIPENV_USE_SYSTEM # Clear the caches, if appropriate. if clear: print("clearing") sys.exit(1) # Automatically use an activated virtualenv. if PIPENV_USE_SYSTEM: system = True if not project.pipfile_exists and deploy: raise exceptions.PipfileNotFound # Fail if working under / if not project.name: click.echo( "{0}: Pipenv is not intended to work under the root directory, " "please choose another path.".format(crayons.red("ERROR")), err=True ) sys.exit(1) # Skip virtualenv creation when --system was used. if not system: ensure_virtualenv( three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, ) if warn: # Warn users if they are using the wrong version of Python. if project.required_python_version: path_to_python = which("python") or which("py") if path_to_python and project.required_python_version not in ( python_version(path_to_python) or "" ): click.echo( "{0}: Your Pipfile requires {1} {2}, " "but you are using {3} ({4}).".format( crayons.red("Warning", bold=True), crayons.normal("python_version", bold=True), crayons.blue(project.required_python_version), crayons.blue(python_version(path_to_python)), crayons.green(shorten_path(path_to_python)), ), err=True, ) click.echo( " {0} and rebuilding the virtual environment " "may resolve the issue.".format(crayons.green("$ pipenv --rm")), err=True, ) if not deploy: click.echo( " {0} will surely fail." "".format(crayons.red("$ pipenv check")), err=True, ) else: raise exceptions.DeployException # Ensure the Pipfile exists. ensure_pipfile( validate=validate, skip_requirements=skip_requirements, system=system )
Returns a visually shorter representation of a given system path. def shorten_path(location, bold=False): """Returns a visually shorter representation of a given system path.""" original = location short = os.sep.join( [s[0] if len(s) > (len("2long4")) else s for s in location.split(os.sep)] ) short = short.split(os.sep) short[-1] = original.split(os.sep)[-1] if bold: short[-1] = str(crayons.normal(short[-1], bold=True)) return os.sep.join(short)
Executes the where functionality. def do_where(virtualenv=False, bare=True): """Executes the where functionality.""" if not virtualenv: if not project.pipfile_exists: click.echo( "No Pipfile present at project home. Consider running " "{0} first to automatically generate a Pipfile for you." "".format(crayons.green("`pipenv install`")), err=True, ) return location = project.pipfile_location # Shorten the virtual display of the path to the virtualenv. if not bare: location = shorten_path(location) click.echo( "Pipfile found at {0}.\n Considering this to be the project home." "".format(crayons.green(location)), err=True, ) else: click.echo(project.project_directory) else: location = project.virtualenv_location if not bare: click.echo( "Virtualenv location: {0}".format(crayons.green(location)), err=True ) else: click.echo(location)
Executes the install functionality. If requirements is True, simply spits out a requirements format to stdout. def do_install_dependencies( dev=False, only=False, bare=False, requirements=False, allow_global=False, ignore_hashes=False, skip_lock=False, concurrent=True, requirements_dir=None, pypi_mirror=False, ): """" Executes the install functionality. If requirements is True, simply spits out a requirements format to stdout. """ from six.moves import queue if requirements: bare = True blocking = not concurrent # Load the lockfile if it exists, or if only is being used (e.g. lock is being used). if skip_lock or only or not project.lockfile_exists: if not bare: click.echo( crayons.normal(fix_utf8("Installing dependencies from Pipfile…"), bold=True) ) # skip_lock should completely bypass the lockfile (broken in 4dac1676) lockfile = project.get_or_create_lockfile(from_pipfile=True) else: lockfile = project.get_or_create_lockfile() if not bare: click.echo( crayons.normal( fix_utf8("Installing dependencies from Pipfile.lock ({0})…".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] )), bold=True, ) ) # Allow pip to resolve dependencies when in skip-lock mode. no_deps = not skip_lock deps_list = list(lockfile.get_requirements(dev=dev, only=requirements)) if requirements: index_args = prepare_pip_source_args(project.sources) index_args = " ".join(index_args).replace(" -", "\n-") deps = [ req.as_line(sources=False, include_hashes=False) for req in deps_list ] # Output only default dependencies click.echo(index_args) click.echo( "\n".join(sorted(deps)) ) sys.exit(0) procs = queue.Queue(maxsize=PIPENV_MAX_SUBPROCESS) failed_deps_queue = queue.Queue() if skip_lock: ignore_hashes = True install_kwargs = { "no_deps": no_deps, "ignore_hashes": ignore_hashes, "allow_global": allow_global, "blocking": blocking, "pypi_mirror": pypi_mirror } if concurrent: install_kwargs["nprocs"] = PIPENV_MAX_SUBPROCESS else: install_kwargs["nprocs"] = 1 # with project.environment.activated(): batch_install( deps_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, concurrent, failed_deps_queue) # Iterate over the hopefully-poorly-packaged dependencies… if not failed_deps_queue.empty(): click.echo( crayons.normal(fix_utf8("Installing initially failed dependencies…"), bold=True) ) retry_list = [] while not failed_deps_queue.empty(): failed_dep = failed_deps_queue.get() retry_list.append(failed_dep) install_kwargs.update({ "nprocs": 1, "retry": False, "blocking": True, }) batch_install( retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs ) if not procs.empty(): _cleanup_procs(procs, False, failed_deps_queue, retry=False)
Creates a virtualenv. def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv.""" click.echo( crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True ) click.echo( u"Pipfile: {0}".format(crayons.red(project.pipfile_location, bold=True)), err=True, ) # Default to using sys.executable, if Python wasn't provided. if not python: python = sys.executable click.echo( u"{0} {1} {3} {2}".format( crayons.normal("Using", bold=True), crayons.red(python, bold=True), crayons.normal(fix_utf8("to create virtualenv…"), bold=True), crayons.green("({0})".format(python_version(python))), ), err=True, ) cmd = [ vistir.compat.Path(sys.executable).absolute().as_posix(), "-m", "virtualenv", "--prompt=({0}) ".format(project.name), "--python={0}".format(python), project.get_location_for_virtualenv(), ] # Pass site-packages flag to virtualenv, if desired… if site_packages: click.echo( crayons.normal(fix_utf8("Making site-packages available…"), bold=True), err=True ) cmd.append("--system-site-packages") if pypi_mirror: pip_config = {"PIP_INDEX_URL": vistir.misc.fs_str(pypi_mirror)} else: pip_config = {} # Actually create the virtualenv. nospin = environments.PIPENV_NOSPIN with create_spinner("Creating virtual environment...") as sp: c = vistir.misc.run( cmd, verbose=False, return_object=True, write_to_stdout=False, combine_stderr=False, block=True, nospin=True, env=pip_config, ) click.echo(crayons.blue("{0}".format(c.out)), err=True) if c.returncode != 0: sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed creating virtual environment")) error = c.err if environments.is_verbose() else exceptions.prettify_exc(c.err) raise exceptions.VirtualenvCreationException( extra=[crayons.red("{0}".format(error)),] ) else: sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format(u"Successfully created virtual environment!")) # Associate project directory with the environment. # This mimics Pew's "setproject". project_file_name = os.path.join(project.virtualenv_location, ".project") with open(project_file_name, "w") as f: f.write(vistir.misc.fs_str(project.project_directory)) from .environment import Environment sources = project.pipfile_sources project._environment = Environment( prefix=project.get_location_for_virtualenv(), is_venv=True, sources=sources, pipfile=project.parsed_pipfile, project=project ) project._environment.add_dist("pipenv") # Say where the virtualenv is. do_where(virtualenv=True, bare=False)
Executes the freeze functionality. def do_lock( ctx=None, system=False, clear=False, pre=False, keep_outdated=False, write=True, pypi_mirror=None, ): """Executes the freeze functionality.""" cached_lockfile = {} if not pre: pre = project.settings.get("allow_prereleases") if keep_outdated: if not project.lockfile_exists: raise exceptions.PipenvOptionsError( "--keep-outdated", ctx=ctx, message="Pipfile.lock must exist to use --keep-outdated!" ) cached_lockfile = project.lockfile_content # Create the lockfile. lockfile = project._lockfile # Cleanup lockfile. for section in ("default", "develop"): for k, v in lockfile[section].copy().items(): if not hasattr(v, "keys"): del lockfile[section][k] # Ensure that develop inherits from default. dev_packages = project.dev_packages.copy() dev_packages = overwrite_dev(project.packages, dev_packages) # Resolve dev-package dependencies, with pip-tools. for is_dev in [True, False]: pipfile_section = "dev-packages" if is_dev else "packages" lockfile_section = "develop" if is_dev else "default" if project.pipfile_exists: packages = project.parsed_pipfile.get(pipfile_section, {}) else: packages = getattr(project, pipfile_section.replace("-", "_")) if write: # Alert the user of progress. click.echo( u"{0} {1} {2}".format( crayons.normal(u"Locking"), crayons.red(u"[{0}]".format(pipfile_section.replace("_", "-"))), crayons.normal(fix_utf8("dependencies…")), ), err=True, ) # Mutates the lockfile venv_resolve_deps( packages, which=which, project=project, dev=is_dev, clear=clear, pre=pre, allow_global=system, pypi_mirror=pypi_mirror, pipfile=packages, lockfile=lockfile, keep_outdated=keep_outdated ) # Support for --keep-outdated… if keep_outdated: from pipenv.vendor.packaging.utils import canonicalize_name for section_name, section in ( ("default", project.packages), ("develop", project.dev_packages), ): for package_specified in section.keys(): if not is_pinned(section[package_specified]): canonical_name = canonicalize_name(package_specified) if canonical_name in cached_lockfile[section_name]: lockfile[section_name][canonical_name] = cached_lockfile[ section_name ][canonical_name].copy() for key in ["default", "develop"]: packages = set(cached_lockfile[key].keys()) new_lockfile = set(lockfile[key].keys()) missing = packages - new_lockfile for missing_pkg in missing: lockfile[key][missing_pkg] = cached_lockfile[key][missing_pkg].copy() # Overwrite any develop packages with default packages. lockfile["develop"].update(overwrite_dev(lockfile.get("default", {}), lockfile["develop"])) if write: project.write_lockfile(lockfile) click.echo( "{0}".format( crayons.normal( "Updated Pipfile.lock ({0})!".format( lockfile["_meta"].get("hash", {}).get("sha256")[-6:] ), bold=True, ) ), err=True, ) else: return lockfile
Executes the purge functionality. def do_purge(bare=False, downloads=False, allow_global=False): """Executes the purge functionality.""" if downloads: if not bare: click.echo(crayons.normal(fix_utf8("Clearing out downloads directory…"), bold=True)) vistir.path.rmtree(project.download_location) return # Remove comments from the output, if any. installed = set([ pep423_name(pkg.project_name) for pkg in project.environment.get_installed_packages() ]) bad_pkgs = set([pep423_name(pkg) for pkg in BAD_PACKAGES]) # Remove setuptools, pip, etc from targets for removal to_remove = installed - bad_pkgs # Skip purging if there is no packages which needs to be removed if not to_remove: if not bare: click.echo("Found 0 installed package, skip purging.") click.echo(crayons.green("Environment now purged and fresh!")) return installed if not bare: click.echo( fix_utf8("Found {0} installed package(s), purging…".format(len(to_remove))) ) command = "{0} uninstall {1} -y".format( escape_grouped_arguments(which_pip(allow_global=allow_global)), " ".join(to_remove), ) if environments.is_verbose(): click.echo("$ {0}".format(command)) c = delegator.run(command) if c.return_code != 0: raise exceptions.UninstallError(installed, command, c.out + c.err, c.return_code) if not bare: click.echo(crayons.blue(c.out)) click.echo(crayons.green("Environment now purged and fresh!")) return installed
Executes the init functionality. def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" from .environments import ( PIPENV_VIRTUALENV, PIPENV_DEFAULT_PYTHON_VERSION, PIPENV_PYTHON, PIPENV_USE_SYSTEM ) python = None if PIPENV_PYTHON is not None: python = PIPENV_PYTHON elif PIPENV_DEFAULT_PYTHON_VERSION is not None: python = PIPENV_DEFAULT_PYTHON_VERSION if not system and not PIPENV_USE_SYSTEM: if not project.virtualenv_exists: try: do_create_virtualenv(python=python, three=None, pypi_mirror=pypi_mirror) except KeyboardInterrupt: cleanup_virtualenv(bare=False) sys.exit(1) # Ensure the Pipfile exists. if not deploy: ensure_pipfile(system=system) if not requirements_dir: requirements_dir = vistir.path.create_tracked_tempdir( suffix="-requirements", prefix="pipenv-" ) # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if (project.lockfile_exists and not ignore_pipfile) and not skip_lock: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: if deploy: click.echo( crayons.red( "Your Pipfile.lock ({0}) is out of date. Expected: ({1}).".format( old_hash[-6:], new_hash[-6:] ) ) ) raise exceptions.DeployException sys.exit(1) elif (system or allow_global) and not (PIPENV_VIRTUALENV): click.echo( crayons.red(fix_utf8( "Pipfile.lock ({0}) out of date, but installation " "uses {1}… re-building lockfile must happen in " "isolation. Please rebuild lockfile in a virtualenv. " "Continuing anyway…".format( crayons.white(old_hash[-6:]), crayons.white("--system") )), bold=True, ), err=True, ) else: if old_hash: msg = fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…") else: msg = fix_utf8("Pipfile.lock is corrupted, replaced with ({1})…") click.echo( crayons.red(msg.format(old_hash[-6:], new_hash[-6:]), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) # Write out the lockfile if it doesn't exist. if not project.lockfile_exists and not skip_lock: # Unless we're in a virtualenv not managed by pipenv, abort if we're # using the system's python. if (system or allow_global) and not (PIPENV_VIRTUALENV): raise exceptions.PipenvOptionsError( "--system", "--system is intended to be used for Pipfile installation, " "not installation of specific packages. Aborting.\n" "See also: --deploy flag." ) else: click.echo( crayons.normal(fix_utf8("Pipfile.lock not found, creating…"), bold=True), err=True, ) do_lock( system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror, ) do_install_dependencies( dev=dev, requirements=requirements, allow_global=allow_global, skip_lock=skip_lock, concurrent=concurrent, requirements_dir=requirements_dir, pypi_mirror=pypi_mirror, ) # Hint the user what to do to activate the virtualenv. if not allow_global and not deploy and "PIPENV_ACTIVE" not in os.environ: click.echo( "To activate this project's virtualenv, run {0}.\n" "Alternatively, run a command " "inside the virtualenv with {1}.".format( crayons.red("pipenv shell"), crayons.red("pipenv run") ) )
A fallback implementation of the `which` utility command that relies exclusively on searching the path for commands. :param str command: The command to search for, optional :param str location: The search location to prioritize (prepend to path), defaults to None :param bool allow_global: Whether to search the global path, defaults to False :param bool system: Whether to use the system python instead of pipenv's python, defaults to False :raises ValueError: Raised if no command is provided :raises TypeError: Raised if the command provided is not a string :return: A path to the discovered command location :rtype: str def fallback_which(command, location=None, allow_global=False, system=False): """ A fallback implementation of the `which` utility command that relies exclusively on searching the path for commands. :param str command: The command to search for, optional :param str location: The search location to prioritize (prepend to path), defaults to None :param bool allow_global: Whether to search the global path, defaults to False :param bool system: Whether to use the system python instead of pipenv's python, defaults to False :raises ValueError: Raised if no command is provided :raises TypeError: Raised if the command provided is not a string :return: A path to the discovered command location :rtype: str """ from .vendor.pythonfinder import Finder if not command: raise ValueError("fallback_which: Must provide a command to search for...") if not isinstance(command, six.string_types): raise TypeError("Provided command must be a string, received {0!r}".format(command)) global_search = system or allow_global if location is None: global_search = True finder = Finder(system=False, global_search=global_search, path=location) if is_python_command(command): result = find_python(finder, command) if result: return result result = finder.which(command) if result: return result.path.as_posix() return ""
Returns the location of virtualenv-installed pip. def which_pip(allow_global=False): """Returns the location of virtualenv-installed pip.""" location = None if "VIRTUAL_ENV" in os.environ: location = os.environ["VIRTUAL_ENV"] if allow_global: if location: pip = which("pip", location=location) if pip: return pip for p in ("pip", "pip3", "pip2"): where = system_which(p) if where: return where pip = which("pip") if not pip: pip = fallback_which("pip", allow_global=allow_global, location=location) return pip
Emulates the system's which. Returns None if not found. def system_which(command, mult=False): """Emulates the system's which. Returns None if not found.""" _which = "which -a" if not os.name == "nt" else "where" os.environ = { vistir.compat.fs_str(k): vistir.compat.fs_str(val) for k, val in os.environ.items() } result = None try: c = delegator.run("{0} {1}".format(_which, command)) try: # Which Not found… if c.return_code == 127: click.echo( "{}: the {} system utility is required for Pipenv to find Python installations properly." "\n Please install it.".format( crayons.red("Warning", bold=True), crayons.red(_which) ), err=True, ) assert c.return_code == 0 except AssertionError: result = fallback_which(command, allow_global=True) except TypeError: if not result: result = fallback_which(command, allow_global=True) else: if not result: result = next(iter([c.out, c.err]), "").split("\n") result = next(iter(result)) if not mult else result return result if not result: result = fallback_which(command, allow_global=True) result = [result] if mult else result return result
Formats the help string. def format_help(help): """Formats the help string.""" help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.red(" check", bold=True))) help = help.replace(" clean", str(crayons.red(" clean", bold=True))) help = help.replace(" graph", str(crayons.red(" graph", bold=True))) help = help.replace(" install", str(crayons.magenta(" install", bold=True))) help = help.replace(" lock", str(crayons.green(" lock", bold=True))) help = help.replace(" open", str(crayons.red(" open", bold=True))) help = help.replace(" run", str(crayons.yellow(" run", bold=True))) help = help.replace(" shell", str(crayons.yellow(" shell", bold=True))) help = help.replace(" sync", str(crayons.green(" sync", bold=True))) help = help.replace(" uninstall", str(crayons.magenta(" uninstall", bold=True))) help = help.replace(" update", str(crayons.green(" update", bold=True))) additional_help = """ Usage Examples: Create a new project using Python 3.7, specifically: $ {1} Remove project virtualenv (inferred from current directory): $ {9} Install all dependencies for a project (including dev): $ {2} Create a lockfile containing pre-releases: $ {6} Show a graph of your installed dependencies: $ {4} Check your installed dependencies for security vulnerabilities: $ {7} Install a local setup.py into your virtual environment/Pipfile: $ {5} Use a lower-level pip command: $ {8} Commands:""".format( crayons.red("pipenv --three"), crayons.red("pipenv --python 3.7"), crayons.red("pipenv install --dev"), crayons.red("pipenv lock"), crayons.red("pipenv graph"), crayons.red("pipenv install -e ."), crayons.red("pipenv lock --pre"), crayons.red("pipenv check"), crayons.red("pipenv run pip freeze"), crayons.red("pipenv --rm"), ) help = help.replace("Commands:", additional_help) return help
Ensures that the lockfile is up-to-date. def ensure_lockfile(keep_outdated=False, pypi_mirror=None): """Ensures that the lockfile is up-to-date.""" if not keep_outdated: keep_outdated = project.settings.get("keep_outdated") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if project.lockfile_exists: old_hash = project.get_lockfile_hash() new_hash = project.calculate_pipfile_hash() if new_hash != old_hash: click.echo( crayons.red( fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…".format( old_hash[-6:], new_hash[-6:] )), bold=True, ), err=True, ) do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror) else: do_lock(keep_outdated=keep_outdated, pypi_mirror=pypi_mirror)
Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455 def _inline_activate_venv(): """Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455 """ components = [] for name in ("bin", "Scripts"): bindir = os.path.join(project.virtualenv_location, name) if os.path.exists(bindir): components.append(bindir) if "PATH" in os.environ: components.append(os.environ["PATH"]) os.environ["PATH"] = os.pathsep.join(components)
Attempt to run command either pulling from project or interpreting as executable. Args are appended to the command in [scripts] section of project if found. def do_run(command, args, three=None, python=False, pypi_mirror=None): """Attempt to run command either pulling from project or interpreting as executable. Args are appended to the command in [scripts] section of project if found. """ from .cmdparse import ScriptEmptyError # Ensure that virtualenv is available. ensure_project( three=three, python=python, validate=False, pypi_mirror=pypi_mirror, ) load_dot_env() previous_pip_shims_module = os.environ.pop("PIP_SHIMS_BASE_MODULE", None) # Activate virtualenv under the current interpreter's environment inline_activate_virtual_environment() # Set an environment variable, so we know we're in the environment. # Only set PIPENV_ACTIVE after finishing reading virtualenv_location # such as in inline_activate_virtual_environment # otherwise its value will be changed previous_pipenv_active_value = os.environ.get("PIPENV_ACTIVE") os.environ["PIPENV_ACTIVE"] = vistir.misc.fs_str("1") try: script = project.build_script(command, args) cmd_string = ' '.join([script.command] + script.args) if environments.is_verbose(): click.echo(crayons.normal("$ {0}".format(cmd_string)), err=True) except ScriptEmptyError: click.echo("Can't run script {0!r}-it's empty?", err=True) run_args = [script] run_kwargs = {} if os.name == "nt": run_fn = do_run_nt else: run_fn = do_run_posix run_kwargs = {"command": command} try: run_fn(*run_args, **run_kwargs) finally: os.environ.pop("PIPENV_ACTIVE", None) if previous_pipenv_active_value is not None: os.environ["PIPENV_ACTIVE"] = previous_pipenv_active_value if previous_pip_shims_module is not None: os.environ["PIP_SHIMS_BASE_MODULE"] = previous_pip_shims_module
Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'} def _iter_process(): """Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'} """ # TODO: Process32{First,Next} does not return full executable path, only # the name. To get the full path, Module32{First,Next} is needed, but that # does not contain parent process information. We probably need to call # BOTH to build the correct process tree. h_process = windll.kernel32.CreateToolhelp32Snapshot( 2, # dwFlags=TH32CS_SNAPPROCESS (include all processes). 0, # th32ProcessID=0 (the current process). ) if h_process == INVALID_HANDLE_VALUE: raise WinError() pe = PROCESSENTRY32() pe.dwSize = sizeof(PROCESSENTRY32) success = windll.kernel32.Process32First(h_process, byref(pe)) while True: if not success: errcode = windll.kernel32.GetLastError() if errcode == ERROR_NO_MORE_FILES: # No more processes to iterate through, we're done here. return elif errcode == ERROR_INSUFFICIENT_BUFFER: # This is likely because the file path is longer than the # Windows limit. Just ignore it, it's likely not what we're # looking for. We can fix this when it actually matters. (#8) continue raise WinError() # The executable name would be encoded with the current code page if # we're in ANSI mode (usually). Try to decode it into str/unicode, # replacing invalid characters to be safe (not thoeratically necessary, # I think). Note that we need to use 'mbcs' instead of encoding # settings from sys because this is from the Windows API, not Python # internals (which those settings reflect). (pypa/pipenv#3382) executable = pe.szExeFile if isinstance(executable, bytes): executable = executable.decode('mbcs', 'replace') info = {'executable': executable} if pe.th32ParentProcessID: info['parent_pid'] = pe.th32ParentProcessID yield pe.th32ProcessID, info success = windll.kernel32.Process32Next(h_process, byref(pe))
Get the shell that the supplied pid or os.getpid() is running in. def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ if not pid: pid = os.getpid() processes = dict(_iter_process()) def check_parent(pid, lvl=0): ppid = processes[pid].get('parent_pid') shell_name = _get_executable(processes.get(ppid)) if shell_name in SHELL_NAMES: return (shell_name, processes[ppid]['executable']) if lvl >= max_depth: return None return check_parent(ppid, lvl=lvl + 1) shell_name = _get_executable(processes.get(pid)) if shell_name in SHELL_NAMES: return (shell_name, processes[pid]['executable']) try: return check_parent(pid) except KeyError: return None
Helper method to fail with an invalid value message. def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. def user_cache_dir(appname): # type: (str) -> str r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: macOS: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. """ if WINDOWS: # Get the base path path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) # When using Python 2, return paths as bytes on Windows like we do on # other operating systems. See helper function docs for more details. if PY2 and isinstance(path, text_type): path = _win_path_to_bytes(path) # Add our app name and Cache directory to it path = os.path.join(path, appname, "Cache") elif sys.platform == "darwin": # Get the base path path = expanduser("~/Library/Caches") # Add our app name to it path = os.path.join(path, appname) else: # Get the base path path = os.getenv("XDG_CACHE_HOME", expanduser("~/.cache")) # Add our app name to it path = os.path.join(path, appname) return path
Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3 def auto_decode(data): # type: (bytes) -> Text """Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3""" for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if line[0:1] == b'#' and ENCODING_RE.search(line): encoding = ENCODING_RE.search(line).groups()[0].decode('ascii') return data.decode(encoding) return data.decode( locale.getpreferredencoding(False) or sys.getdefaultencoding(), )
Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. def resolve_color_default(color=None): """"Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color ctx = get_current_context(silent=True) if ctx is not None: return ctx.color
Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed def load(f, _dict=dict, decoder=None): """Parses named file or files as toml and returns a dictionary Args: f: Path to the file to open, array of files to read into single dict or a file descriptor _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError -- When f is invalid type TomlDecodeError: Error while decoding toml IOError / FileNotFoundError -- When an array with no valid (existing) (Python 2 / Python 3) file paths is passed """ if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import warn if not [path for path in f if op.exists(path)]: error_msg = "Load expects a list to contain filenames only." error_msg += linesep error_msg += ("The list needs to contain the path of at least one " "existing file.") raise FNFError(error_msg) if decoder is None: decoder = TomlDecoder() d = decoder.get_empty_table() for l in f: if op.exists(l): d.update(load(l, _dict, decoder)) else: warn("Non-existent filename in list with at least one valid " "filename") return d else: try: return loads(f.read(), _dict, decoder) except AttributeError: raise TypeError("You can only load a file descriptor, filename or " "list")
Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml def loads(s, _dict=dict, decoder=None): """Parses string as toml Args: s: String to be parsed _dict: (optional) Specifies the class of the returned toml dictionary Returns: Parsed toml file represented as a dictionary Raises: TypeError: When a non-string is passed TomlDecodeError: Error while decoding toml """ implicitgroups = [] if decoder is None: decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if not isinstance(s, basestring): raise TypeError("Expecting something like a string") if not isinstance(s, unicode): s = s.decode('utf8') original = s sl = list(s) openarr = 0 openstring = False openstrchar = "" multilinestr = False arrayoftables = False beginline = True keygroup = False dottedkey = False keyname = 0 for i, item in enumerate(sl): if item == '\r' and sl[i + 1] == '\n': sl[i] = ' ' continue if keyname: if item == '\n': raise TomlDecodeError("Key name found without value." " Reached end of line.", original, i) if openstring: if item == openstrchar: keyname = 2 openstring = False openstrchar = "" continue elif keyname == 1: if item.isspace(): keyname = 2 continue elif item == '.': dottedkey = True continue elif item.isalnum() or item == '_' or item == '-': continue elif (dottedkey and sl[i - 1] == '.' and (item == '"' or item == "'")): openstring = True openstrchar = item continue elif keyname == 2: if item.isspace(): if dottedkey: nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '.': dottedkey = True nextitem = sl[i + 1] if not nextitem.isspace() and nextitem != '.': keyname = 1 continue if item == '=': keyname = 0 dottedkey = False else: raise TomlDecodeError("Found invalid character in key name: '" + item + "'. Try quoting the key name.", original, i) if item == "'" and openstrchar != '"': k = 1 try: while sl[i - k] == "'": k += 1 if k == 3: break except IndexError: pass if k == 3: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = "'" else: openstrchar = "" if item == '"' and openstrchar != "'": oddbackslash = False k = 1 tripquote = False try: while sl[i - k] == '"': k += 1 if k == 3: tripquote = True break if k == 1 or (k == 3 and tripquote): while sl[i - k] == '\\': oddbackslash = not oddbackslash k += 1 except IndexError: pass if not oddbackslash: if tripquote: multilinestr = not multilinestr openstring = multilinestr else: openstring = not openstring if openstring: openstrchar = '"' else: openstrchar = "" if item == '#' and (not openstring and not keygroup and not arrayoftables): j = i try: while sl[j] != '\n': sl[j] = ' ' j += 1 except IndexError: break if item == '[' and (not openstring and not keygroup and not arrayoftables): if beginline: if len(sl) > i + 1 and sl[i + 1] == '[': arrayoftables = True else: keygroup = True else: openarr += 1 if item == ']' and not openstring: if keygroup: keygroup = False elif arrayoftables: if sl[i - 1] == ']': arrayoftables = False else: openarr -= 1 if item == '\n': if openstring or multilinestr: if not multilinestr: raise TomlDecodeError("Unbalanced quotes", original, i) if ((sl[i - 1] == "'" or sl[i - 1] == '"') and ( sl[i - 2] == sl[i - 1])): sl[i] = sl[i - 1] if sl[i - 3] == sl[i - 1]: sl[i - 3] = ' ' elif openarr: sl[i] = ' ' else: beginline = True elif beginline and sl[i] != ' ' and sl[i] != '\t': beginline = False if not keygroup and not arrayoftables: if sl[i] == '=': raise TomlDecodeError("Found empty keyname. ", original, i) keyname = 1 s = ''.join(sl) s = s.split('\n') multikey = None multilinestr = "" multibackslash = False pos = 0 for idx, line in enumerate(s): if idx > 0: pos += len(s[idx - 1]) + 1 if not multilinestr or multibackslash or '\n' not in multilinestr: line = line.strip() if line == "" and (not multikey or multibackslash): continue if multikey: if multibackslash: multilinestr += line else: multilinestr += line multibackslash = False if len(line) > 2 and (line[-1] == multilinestr[0] and line[-2] == multilinestr[0] and line[-3] == multilinestr[0]): try: value, vtype = decoder.load_value(multilinestr) except ValueError as err: raise TomlDecodeError(str(err), original, pos) currentlevel[multikey] = value multikey = None multilinestr = "" else: k = len(multilinestr) - 1 while k > -1 and multilinestr[k] == '\\': multibackslash = not multibackslash k -= 1 if multibackslash: multilinestr = multilinestr[:-1] else: multilinestr += "\n" continue if line[0] == '[': arrayoftables = False if len(line) == 1: raise TomlDecodeError("Opening key group bracket on line by " "itself.", original, pos) if line[1] == '[': arrayoftables = True line = line[2:] splitstr = ']]' else: line = line[1:] splitstr = ']' i = 1 quotesplits = decoder._get_split_on_quotes(line) quoted = False for quotesplit in quotesplits: if not quoted and splitstr in quotesplit: break i += quotesplit.count(splitstr) quoted = not quoted line = line.split(splitstr, i) if len(line) < i + 1 or line[-1].strip() != "": raise TomlDecodeError("Key group not on a line by itself.", original, pos) groups = splitstr.join(line[:-1]).split('.') i = 0 while i < len(groups): groups[i] = groups[i].strip() if len(groups[i]) > 0 and (groups[i][0] == '"' or groups[i][0] == "'"): groupstr = groups[i] j = i + 1 while not groupstr[0] == groupstr[-1]: j += 1 if j > len(groups) + 2: raise TomlDecodeError("Invalid group name '" + groupstr + "' Something " + "went wrong.", original, pos) groupstr = '.'.join(groups[i:j]).strip() groups[i] = groupstr[1:-1] groups[i + 1:j] = [] else: if not _groupname_re.match(groups[i]): raise TomlDecodeError("Invalid group name '" + groups[i] + "'. Try quoting it.", original, pos) i += 1 currentlevel = retval for i in _range(len(groups)): group = groups[i] if group == "": raise TomlDecodeError("Can't have a keygroup with an empty " "name", original, pos) try: currentlevel[group] if i == len(groups) - 1: if group in implicitgroups: implicitgroups.remove(group) if arrayoftables: raise TomlDecodeError("An implicitly defined " "table can't be an array", original, pos) elif arrayoftables: currentlevel[group].append(decoder.get_empty_table() ) else: raise TomlDecodeError("What? " + group + " already exists?" + str(currentlevel), original, pos) except TypeError: currentlevel = currentlevel[-1] if group not in currentlevel: currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] except KeyError: if i != len(groups) - 1: implicitgroups.append(group) currentlevel[group] = decoder.get_empty_table() if i == len(groups) - 1 and arrayoftables: currentlevel[group] = [decoder.get_empty_table()] currentlevel = currentlevel[group] if arrayoftables: try: currentlevel = currentlevel[-1] except KeyError: pass elif line[0] == "{": if line[-1] != "}": raise TomlDecodeError("Line breaks are not allowed in inline" "objects", original, pos) try: decoder.load_inline_object(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) elif "=" in line: try: ret = decoder.load_line(line, currentlevel, multikey, multibackslash) except ValueError as err: raise TomlDecodeError(str(err), original, pos) if ret is not None: multikey, multilinestr, multibackslash = ret return retval
Concatenation that escapes if necessary and converts to unicode. def markup_join(seq): """Concatenation that escapes if necessary and converts to unicode.""" buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
Internal helper to for context creation. def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: # if the parent is shared a copy should be created because # we don't want to modify the dict passed if shared: parent = dict(parent) for key, value in iteritems(locals): if value is not missing: parent[key] = value return environment.context_class(environment, parent, template_name, blocks)
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
Render a parent block. def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' 'called %r.' % name, name='super') return BlockReference(name, self, blocks, index)
Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. def resolve(self, key): """Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. """ if self._legacy_resolve_mode: rv = resolve_or_missing(self, key) else: rv = self.resolve_or_missing(key) if rv is missing: return self.environment.undefined(name=key) return rv
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. def resolve_or_missing(self, key): """Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found. """ if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
Get a new dict with the exported variables. def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. def get_all(self): """Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. """ if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. def derived(self, locals=None): """Internal helper function to create a derived context. This is used in situations where the system needs a new context in the same template that is independent. """ context = new_context(self.environment, self.name, {}, self.get_all(), True, None, locals) context.eval_ctx = self.eval_ctx context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks)) return context
Super the block. def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, self._stack, self._depth + 1)
Cycles among the arguments with the current loop index. def cycle(self, *args): """Cycles among the arguments with the current loop index.""" if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
Checks whether the value has changed since the last call. def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
This method is being swapped out by the async implementation. def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. def main(): '''This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. ''' f = FSM ('INIT', []) f.set_default_transition (Error, 'INIT') f.add_transition_any ('INIT', None, 'INIT') f.add_transition ('=', 'INIT', DoEqual, 'INIT') f.add_transition_list (string.digits, 'INIT', BeginBuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.digits, 'BUILDING_NUMBER', BuildNumber, 'BUILDING_NUMBER') f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber, 'INIT') f.add_transition_list ('+-*/', 'INIT', DoOperator, 'INIT') print() print('Enter an RPN Expression.') print('Numbers may be integers. Operators are * / + -') print('Use the = sign to evaluate and print the expression.') print('For example: ') print(' 167 3 2 2 * * * 1 - =') inputstr = (input if PY3 else raw_input)('> ') # analysis:ignore f.process_list(inputstr)
This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. You can also set transitions for a list of symbols by using add_transition_list(). ''' if next_state is None: next_state = state self.state_transitions[(input_symbol, state)] = (action, next_state)
This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. def add_transition_any (self, state, action=None, next_state=None): '''This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method checks the "any" state associations after it first checks for an exact match of (input_symbol, current_state). The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state self.state_transitions_any [state] = (action, next_state)
This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. def get_transition (self, input_symbol, state): '''This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is called by process(). The sequence of steps to check for a defined transition goes from the most specific to the least specific. 1. Check state_transitions[] that match exactly the tuple, (input_symbol, state) 2. Check state_transitions_any[] that match (state) In other words, match a specific state and ANY input_symbol. 3. Check if the default_transition is defined. This catches any input_symbol and any state. This is a handler for errors, undefined states, or defaults. 4. No transition was defined. If we get here then raise an exception. ''' if (input_symbol, state) in self.state_transitions: return self.state_transitions[(input_symbol, state)] elif state in self.state_transitions_any: return self.state_transitions_any[state] elif self.default_transition is not None: return self.default_transition else: raise ExceptionFSM ('Transition is undefined: (%s, %s).' % (str(input_symbol), str(state)) )
This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). def process (self, input_symbol): '''This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the input_symbol and current_state. If the action is None then the action is not called and only the current state is changed. This method processes one complete input symbol. You can process a list of symbols (or a string) by calling process_list(). ''' self.input_symbol = input_symbol (self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state) if self.action is not None: self.action (self) self.current_state = self.next_state self.next_state = None
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address, bytes): raise AddressValueError( '%r does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' % address) raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address)