Skip to content
Myr

utils.py

This file

Path

click/utils.py

480 lines · 16.5 KiB · Python

Last changed by

Only return unicode params from get_os_args if unchanged.Armin Ronacherbefore adoption0859d19

History of this file

Take it

1import os2import sys3from collections import deque45from .globals import resolve_color_default67from ._compat import text_type, open_stream, get_filesystem_encoding, \8    get_streerror, string_types, PY2, binary_streams, text_streams, \9    filename_to_ui, auto_wrap_for_ansi, strip_ansi, should_strip_ansi, \10    _default_text_stdout, _default_text_stderr, is_bytes, WIN1112if not PY2:13    from ._compat import _find_binary_writer14elif WIN:15    from ._winconsole import _get_windows_argv, \16         _hash_py_argv, _initial_argv_hash171819echo_native_types = string_types + (bytes, bytearray)202122def _posixify(name):23    return '-'.join(name.split()).lower()242526def unpack_args(args, nargs_spec):27    """Given an iterable of arguments and an iterable of nargs specifications,28    it returns a tuple with all the unpacked arguments at the first index29    and all remaining arguments as the second.3031    The nargs specification is the number of arguments that should be consumed32    or `-1` to indicate that this position should eat up all the remainders.3334    Missing items are filled with `None`.3536    Examples:3738    >>> unpack_args(range(6), [1, 2, 1, -1])39    ((0, (1, 2), 3, (4, 5)), [])40    >>> unpack_args(range(6), [1, 2, 1])41    ((0, (1, 2), 3), [4, 5])42    >>> unpack_args(range(6), [-1])43    (((0, 1, 2, 3, 4, 5),), [])44    >>> unpack_args(range(6), [1, 1])45    ((0, 1), [2, 3, 4, 5])46    >>> unpack_args(range(6), [-1,1,1,1,1])47    (((0, 1), 2, 3, 4, 5), [])48    """49    args = deque(args)50    nargs_spec = deque(nargs_spec)51    rv = []52    spos = None5354    def _fetch(c):55        try:56            if spos is None:57                return c.popleft()58            else:59                return c.pop()60        except IndexError:61            return None6263    while nargs_spec:64        nargs = _fetch(nargs_spec)65        if nargs == 1:66            rv.append(_fetch(args))67        elif nargs > 1:68            x = [_fetch(args) for _ in range(nargs)]69            # If we're reversed, we're pulling in the arguments in reverse,70            # so we need to turn them around.71            if spos is not None:72                x.reverse()73            rv.append(tuple(x))74        elif nargs < 0:75            if spos is not None:76                raise TypeError('Cannot have two nargs < 0')77            spos = len(rv)78            rv.append(None)7980    # spos is the position of the wildcard (star).  If it's not `None`,81    # we fill it with the remainder.82    if spos is not None:83        rv[spos] = tuple(args)84        args = []85        rv[spos + 1:] = reversed(rv[spos + 1:])8687    return tuple(rv), list(args)888990def safecall(func):91    """Wraps a function so that it swallows exceptions."""92    def wrapper(*args, **kwargs):93        try:94            return func(*args, **kwargs)95        except Exception:96            pass97    return wrapper9899100def make_str(value):101    """Converts a value into a valid string."""102    if isinstance(value, bytes):103        try:104            return value.decode(get_filesystem_encoding())105        except UnicodeError:106            return value.decode('utf-8', 'replace')107    return text_type(value)108109110def make_default_short_help(help, max_length=45):111    words = help.split()112    total_length = 0113    result = []114    done = False115116    for word in words:117        if word[-1:] == '.':118            done = True119        new_length = result and 1 + len(word) or len(word)120        if total_length + new_length > max_length:121            result.append('...')122            done = True123        else:124            if result:125                result.append(' ')126            result.append(word)127        if done:128            break129        total_length += new_length130131    return ''.join(result)132133134class LazyFile(object):135    """A lazy file works like a regular file but it does not fully open136    the file but it does perform some basic checks early to see if the137    filename parameter does make sense.  This is useful for safely opening138    files for writing.139    """140141    def __init__(self, filename, mode='r', encoding=None, errors='strict',142                 atomic=False):143        self.name = filename144        self.mode = mode145        self.encoding = encoding146        self.errors = errors147        self.atomic = atomic148149        if filename == '-':150            self._f, self.should_close = open_stream(filename, mode,151                                                     encoding, errors)152        else:153            if 'r' in mode:154                # Open and close the file in case we're opening it for155                # reading so that we can catch at least some errors in156                # some cases early.157                open(filename, mode).close()158            self._f = None159            self.should_close = True160161    def __getattr__(self, name):162        return getattr(self.open(), name)163164    def __repr__(self):165        if self._f is not None:166            return repr(self._f)167        return '<unopened file %r %s>' % (self.name, self.mode)168169    def open(self):170        """Opens the file if it's not yet open.  This call might fail with171        a :exc:`FileError`.  Not handling this error will produce an error172        that Click shows.173        """174        if self._f is not None:175            return self._f176        try:177            rv, self.should_close = open_stream(self.name, self.mode,178                                                self.encoding,179                                                self.errors,180                                                atomic=self.atomic)181        except (IOError, OSError) as e:182            from .exceptions import FileError183            raise FileError(self.name, hint=get_streerror(e))184        self._f = rv185        return rv186187    def close(self):188        """Closes the underlying file, no matter what."""189        if self._f is not None:190            self._f.close()191192    def close_intelligently(self):193        """This function only closes the file if it was opened by the lazy194        file wrapper.  For instance this will never close stdin.195        """196        if self.should_close:197            self.close()198199    def __enter__(self):200        return self201202    def __exit__(self, exc_type, exc_value, tb):203        self.close_intelligently()204205    def __iter__(self):206        self.open()207        return iter(self._f)208209210class KeepOpenFile(object):211212    def __init__(self, file):213        self._file = file214215    def __getattr__(self, name):216        return getattr(self._file, name)217218    def __enter__(self):219        return self220221    def __exit__(self, exc_type, exc_value, tb):222        pass223224    def __repr__(self):225        return repr(self._file)226227    def __iter__(self):228        return iter(self._file)229230231def echo(message=None, file=None, nl=True, err=False, color=None):232    """Prints a message plus a newline to the given file or stdout.  On233    first sight, this looks like the print function, but it has improved234    support for handling Unicode and binary data that does not fail no235    matter how badly configured the system is.236237    Primarily it means that you can print binary data as well as Unicode238    data on both 2.x and 3.x to the given file in the most appropriate way239    possible.  This is a very carefree function as in that it will try its240    best to not fail.  As of Click 6.0 this includes support for unicode241    output on the Windows console.242243    In addition to that, if `colorama`_ is installed, the echo function will244    also support clever handling of ANSI codes.  Essentially it will then245    do the following:246247    -   add transparent handling of ANSI color codes on Windows.248    -   hide ANSI codes automatically if the destination file is not a249        terminal.250251    .. _colorama: http://pypi.python.org/pypi/colorama252253    .. versionchanged:: 6.0254       As of Click 6.0 the echo function will properly support unicode255       output on the windows console.  Not that click does not modify256       the interpreter in any way which means that `sys.stdout` or the257       print statement or function will still not provide unicode support.258259    .. versionchanged:: 2.0260       Starting with version 2.0 of Click, the echo function will work261       with colorama if it's installed.262263    .. versionadded:: 3.0264       The `err` parameter was added.265266    .. versionchanged:: 4.0267       Added the `color` flag.268269    :param message: the message to print270    :param file: the file to write to (defaults to ``stdout``)271    :param err: if set to true the file defaults to ``stderr`` instead of272                ``stdout``.  This is faster and easier than calling273                :func:`get_text_stderr` yourself.274    :param nl: if set to `True` (the default) a newline is printed afterwards.275    :param color: controls if the terminal supports ANSI colors or not.  The276                  default is autodetection.277    """278    if file is None:279        if err:280            file = _default_text_stderr()281        else:282            file = _default_text_stdout()283284    # Convert non bytes/text into the native string type.285    if message is not None and not isinstance(message, echo_native_types):286        message = text_type(message)287288    if nl:289        message = message or u''290        if isinstance(message, text_type):291            message += u'\n'292        else:293            message += b'\n'294295    # If there is a message, and we're in Python 3, and the value looks296    # like bytes, we manually need to find the binary stream and write the297    # message in there.  This is done separately so that most stream298    # types will work as you would expect.  Eg: you can write to StringIO299    # for other cases.300    if message and not PY2 and is_bytes(message):301        binary_file = _find_binary_writer(file)302        if binary_file is not None:303            file.flush()304            binary_file.write(message)305            binary_file.flush()306            return307308    # ANSI-style support.  If there is no message or we are dealing with309    # bytes nothing is happening.  If we are connected to a file we want310    # to strip colors.  If we are on windows we either wrap the stream311    # to strip the color or we use the colorama support to translate the312    # ansi codes to API calls.313    if message and not is_bytes(message):314        color = resolve_color_default(color)315        if should_strip_ansi(file, color):316            message = strip_ansi(message)317        elif WIN:318            if auto_wrap_for_ansi is not None:319                file = auto_wrap_for_ansi(file)320            elif not color:321                message = strip_ansi(message)322323    if message:324        file.write(message)325    file.flush()326327328def get_binary_stream(name):329    """Returns a system stream for byte processing.  This essentially330    returns the stream from the sys module with the given name but it331    solves some compatibility issues between different Python versions.332    Primarily this function is necessary for getting binary streams on333    Python 3.334335    :param name: the name of the stream to open.  Valid names are ``'stdin'``,336                 ``'stdout'`` and ``'stderr'``337    """338    opener = binary_streams.get(name)339    if opener is None:340        raise TypeError('Unknown standard stream %r' % name)341    return opener()342343344def get_text_stream(name, encoding=None, errors='strict'):345    """Returns a system stream for text processing.  This usually returns346    a wrapped stream around a binary stream returned from347    :func:`get_binary_stream` but it also can take shortcuts on Python 3348    for already correctly configured streams.349350    :param name: the name of the stream to open.  Valid names are ``'stdin'``,351                 ``'stdout'`` and ``'stderr'``352    :param encoding: overrides the detected default encoding.353    :param errors: overrides the default error mode.354    """355    opener = text_streams.get(name)356    if opener is None:357        raise TypeError('Unknown standard stream %r' % name)358    return opener(encoding, errors)359360361def open_file(filename, mode='r', encoding=None, errors='strict',362              lazy=False, atomic=False):363    """This is similar to how the :class:`File` works but for manual364    usage.  Files are opened non lazy by default.  This can open regular365    files as well as stdin/stdout if ``'-'`` is passed.366367    If stdin/stdout is returned the stream is wrapped so that the context368    manager will not close the stream accidentally.  This makes it possible369    to always use the function like this without having to worry to370    accidentally close a standard stream::371372        with open_file(filename) as f:373            ...374375    .. versionadded:: 3.0376377    :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).378    :param mode: the mode in which to open the file.379    :param encoding: the encoding to use.380    :param errors: the error handling for this file.381    :param lazy: can be flipped to true to open the file lazily.382    :param atomic: in atomic mode writes go into a temporary file and it's383                   moved on close.384    """385    if lazy:386        return LazyFile(filename, mode, encoding, errors, atomic=atomic)387    f, should_close = open_stream(filename, mode, encoding, errors,388                                  atomic=atomic)389    if not should_close:390        f = KeepOpenFile(f)391    return f392393394def get_os_args():395    """This returns the argument part of sys.argv in the most appropriate396    form for processing.  What this means is that this return value is in397    a format that works for Click to process but does not necessarily398    correspond well to what's actually standard for the interpreter.399400    On most environments the return value is ``sys.argv[:1]`` unchanged.401    However if you are on Windows and running Python 2 the return value402    will actually be a list of unicode strings instead because the403    default behavior on that platform otherwise will not be able to404    carry all possible values that sys.argv can have.405406    .. versionadded:: 6.0407    """408    # We can only extract the unicode argv if sys.argv has not been409    # changed since the startup of the application.410    if PY2 and WIN and _initial_argv_hash == _hash_py_argv():411        return _get_windows_argv()412    return sys.argv[1:]413414415def format_filename(filename, shorten=False):416    """Formats a filename for user display.  The main purpose of this417    function is to ensure that the filename can be displayed at all.  This418    will decode the filename to unicode if necessary in a way that it will419    not fail.  Optionally, it can shorten the filename to not include the420    full path to the filename.421422    :param filename: formats a filename for UI display.  This will also convert423                     the filename into unicode without failing.424    :param shorten: this optionally shortens the filename to strip of the425                    path that leads up to it.426    """427    if shorten:428        filename = os.path.basename(filename)429    return filename_to_ui(filename)430431432def get_app_dir(app_name, roaming=True, force_posix=False):433    r"""Returns the config folder for the application.  The default behavior434    is to return whatever is most appropriate for the operating system.435436    To give you an idea, for an app called ``"Foo Bar"``, something like437    the following folders could be returned:438439    Mac OS X:440      ``~/Library/Application Support/Foo Bar``441    Mac OS X (POSIX):442      ``~/.foo-bar``443    Unix:444      ``~/.config/foo-bar``445    Unix (POSIX):446      ``~/.foo-bar``447    Win XP (roaming):448      ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``449    Win XP (not roaming):450      ``C:\Documents and Settings\<user>\Application Data\Foo Bar``451    Win 7 (roaming):452      ``C:\Users\<user>\AppData\Roaming\Foo Bar``453    Win 7 (not roaming):454      ``C:\Users\<user>\AppData\Local\Foo Bar``455456    .. versionadded:: 2.0457458    :param app_name: the application name.  This should be properly capitalized459                     and can contain whitespace.460    :param roaming: controls if the folder should be roaming or not on Windows.461                    Has no affect otherwise.462    :param force_posix: if this is set to `True` then on any POSIX system the463                        folder will be stored in the home folder with a leading464                        dot instead of the XDG config home or darwin's465                        application support folder.466    """467    if WIN:468        key = roaming and 'APPDATA' or 'LOCALAPPDATA'469        folder = os.environ.get(key)470        if folder is None:471            folder = os.path.expanduser('~')472        return os.path.join(folder, app_name)473    if force_posix:474        return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))475    if sys.platform == 'darwin':476        return os.path.join(os.path.expanduser(477            '~/Library/Application Support'), app_name)478    return os.path.join(479        os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),480        _posixify(app_name))