utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import os
  2. import sys
  3. from .globals import resolve_color_default
  4. from ._compat import text_type, open_stream, get_filesystem_encoding, \
  5. get_streerror, string_types, PY2, binary_streams, text_streams, \
  6. filename_to_ui, auto_wrap_for_ansi, strip_ansi, should_strip_ansi, \
  7. _default_text_stdout, _default_text_stderr, is_bytes, WIN
  8. if not PY2:
  9. from ._compat import _find_binary_writer
  10. elif WIN:
  11. from ._winconsole import _get_windows_argv, \
  12. _hash_py_argv, _initial_argv_hash
  13. echo_native_types = string_types + (bytes, bytearray)
  14. def _posixify(name):
  15. return '-'.join(name.split()).lower()
  16. def safecall(func):
  17. """Wraps a function so that it swallows exceptions."""
  18. def wrapper(*args, **kwargs):
  19. try:
  20. return func(*args, **kwargs)
  21. except Exception:
  22. pass
  23. return wrapper
  24. def make_str(value):
  25. """Converts a value into a valid string."""
  26. if isinstance(value, bytes):
  27. try:
  28. return value.decode(get_filesystem_encoding())
  29. except UnicodeError:
  30. return value.decode('utf-8', 'replace')
  31. return text_type(value)
  32. def make_default_short_help(help, max_length=45):
  33. words = help.split()
  34. total_length = 0
  35. result = []
  36. done = False
  37. for word in words:
  38. if word[-1:] == '.':
  39. done = True
  40. new_length = result and 1 + len(word) or len(word)
  41. if total_length + new_length > max_length:
  42. result.append('...')
  43. done = True
  44. else:
  45. if result:
  46. result.append(' ')
  47. result.append(word)
  48. if done:
  49. break
  50. total_length += new_length
  51. return ''.join(result)
  52. class LazyFile(object):
  53. """A lazy file works like a regular file but it does not fully open
  54. the file but it does perform some basic checks early to see if the
  55. filename parameter does make sense. This is useful for safely opening
  56. files for writing.
  57. """
  58. def __init__(self, filename, mode='r', encoding=None, errors='strict',
  59. atomic=False):
  60. self.name = filename
  61. self.mode = mode
  62. self.encoding = encoding
  63. self.errors = errors
  64. self.atomic = atomic
  65. if filename == '-':
  66. self._f, self.should_close = open_stream(filename, mode,
  67. encoding, errors)
  68. else:
  69. if 'r' in mode:
  70. # Open and close the file in case we're opening it for
  71. # reading so that we can catch at least some errors in
  72. # some cases early.
  73. open(filename, mode).close()
  74. self._f = None
  75. self.should_close = True
  76. def __getattr__(self, name):
  77. return getattr(self.open(), name)
  78. def __repr__(self):
  79. if self._f is not None:
  80. return repr(self._f)
  81. return '<unopened file %r %s>' % (self.name, self.mode)
  82. def open(self):
  83. """Opens the file if it's not yet open. This call might fail with
  84. a :exc:`FileError`. Not handling this error will produce an error
  85. that Click shows.
  86. """
  87. if self._f is not None:
  88. return self._f
  89. try:
  90. rv, self.should_close = open_stream(self.name, self.mode,
  91. self.encoding,
  92. self.errors,
  93. atomic=self.atomic)
  94. except (IOError, OSError) as e:
  95. from .exceptions import FileError
  96. raise FileError(self.name, hint=get_streerror(e))
  97. self._f = rv
  98. return rv
  99. def close(self):
  100. """Closes the underlying file, no matter what."""
  101. if self._f is not None:
  102. self._f.close()
  103. def close_intelligently(self):
  104. """This function only closes the file if it was opened by the lazy
  105. file wrapper. For instance this will never close stdin.
  106. """
  107. if self.should_close:
  108. self.close()
  109. def __enter__(self):
  110. return self
  111. def __exit__(self, exc_type, exc_value, tb):
  112. self.close_intelligently()
  113. def __iter__(self):
  114. self.open()
  115. return iter(self._f)
  116. class KeepOpenFile(object):
  117. def __init__(self, file):
  118. self._file = file
  119. def __getattr__(self, name):
  120. return getattr(self._file, name)
  121. def __enter__(self):
  122. return self
  123. def __exit__(self, exc_type, exc_value, tb):
  124. pass
  125. def __repr__(self):
  126. return repr(self._file)
  127. def __iter__(self):
  128. return iter(self._file)
  129. def echo(message=None, file=None, nl=True, err=False, color=None):
  130. """Prints a message plus a newline to the given file or stdout. On
  131. first sight, this looks like the print function, but it has improved
  132. support for handling Unicode and binary data that does not fail no
  133. matter how badly configured the system is.
  134. Primarily it means that you can print binary data as well as Unicode
  135. data on both 2.x and 3.x to the given file in the most appropriate way
  136. possible. This is a very carefree function as in that it will try its
  137. best to not fail. As of Click 6.0 this includes support for unicode
  138. output on the Windows console.
  139. In addition to that, if `colorama`_ is installed, the echo function will
  140. also support clever handling of ANSI codes. Essentially it will then
  141. do the following:
  142. - add transparent handling of ANSI color codes on Windows.
  143. - hide ANSI codes automatically if the destination file is not a
  144. terminal.
  145. .. _colorama: http://pypi.python.org/pypi/colorama
  146. .. versionchanged:: 6.0
  147. As of Click 6.0 the echo function will properly support unicode
  148. output on the windows console. Not that click does not modify
  149. the interpreter in any way which means that `sys.stdout` or the
  150. print statement or function will still not provide unicode support.
  151. .. versionchanged:: 2.0
  152. Starting with version 2.0 of Click, the echo function will work
  153. with colorama if it's installed.
  154. .. versionadded:: 3.0
  155. The `err` parameter was added.
  156. .. versionchanged:: 4.0
  157. Added the `color` flag.
  158. :param message: the message to print
  159. :param file: the file to write to (defaults to ``stdout``)
  160. :param err: if set to true the file defaults to ``stderr`` instead of
  161. ``stdout``. This is faster and easier than calling
  162. :func:`get_text_stderr` yourself.
  163. :param nl: if set to `True` (the default) a newline is printed afterwards.
  164. :param color: controls if the terminal supports ANSI colors or not. The
  165. default is autodetection.
  166. """
  167. if file is None:
  168. if err:
  169. file = _default_text_stderr()
  170. else:
  171. file = _default_text_stdout()
  172. # Convert non bytes/text into the native string type.
  173. if message is not None and not isinstance(message, echo_native_types):
  174. message = text_type(message)
  175. if nl:
  176. message = message or u''
  177. if isinstance(message, text_type):
  178. message += u'\n'
  179. else:
  180. message += b'\n'
  181. # If there is a message, and we're in Python 3, and the value looks
  182. # like bytes, we manually need to find the binary stream and write the
  183. # message in there. This is done separately so that most stream
  184. # types will work as you would expect. Eg: you can write to StringIO
  185. # for other cases.
  186. if message and not PY2 and is_bytes(message):
  187. binary_file = _find_binary_writer(file)
  188. if binary_file is not None:
  189. file.flush()
  190. binary_file.write(message)
  191. binary_file.flush()
  192. return
  193. # ANSI-style support. If there is no message or we are dealing with
  194. # bytes nothing is happening. If we are connected to a file we want
  195. # to strip colors. If we are on windows we either wrap the stream
  196. # to strip the color or we use the colorama support to translate the
  197. # ansi codes to API calls.
  198. if message and not is_bytes(message):
  199. color = resolve_color_default(color)
  200. if should_strip_ansi(file, color):
  201. message = strip_ansi(message)
  202. elif WIN:
  203. if auto_wrap_for_ansi is not None:
  204. file = auto_wrap_for_ansi(file)
  205. elif not color:
  206. message = strip_ansi(message)
  207. if message:
  208. file.write(message)
  209. file.flush()
  210. def get_binary_stream(name):
  211. """Returns a system stream for byte processing. This essentially
  212. returns the stream from the sys module with the given name but it
  213. solves some compatibility issues between different Python versions.
  214. Primarily this function is necessary for getting binary streams on
  215. Python 3.
  216. :param name: the name of the stream to open. Valid names are ``'stdin'``,
  217. ``'stdout'`` and ``'stderr'``
  218. """
  219. opener = binary_streams.get(name)
  220. if opener is None:
  221. raise TypeError('Unknown standard stream %r' % name)
  222. return opener()
  223. def get_text_stream(name, encoding=None, errors='strict'):
  224. """Returns a system stream for text processing. This usually returns
  225. a wrapped stream around a binary stream returned from
  226. :func:`get_binary_stream` but it also can take shortcuts on Python 3
  227. for already correctly configured streams.
  228. :param name: the name of the stream to open. Valid names are ``'stdin'``,
  229. ``'stdout'`` and ``'stderr'``
  230. :param encoding: overrides the detected default encoding.
  231. :param errors: overrides the default error mode.
  232. """
  233. opener = text_streams.get(name)
  234. if opener is None:
  235. raise TypeError('Unknown standard stream %r' % name)
  236. return opener(encoding, errors)
  237. def open_file(filename, mode='r', encoding=None, errors='strict',
  238. lazy=False, atomic=False):
  239. """This is similar to how the :class:`File` works but for manual
  240. usage. Files are opened non lazy by default. This can open regular
  241. files as well as stdin/stdout if ``'-'`` is passed.
  242. If stdin/stdout is returned the stream is wrapped so that the context
  243. manager will not close the stream accidentally. This makes it possible
  244. to always use the function like this without having to worry to
  245. accidentally close a standard stream::
  246. with open_file(filename) as f:
  247. ...
  248. .. versionadded:: 3.0
  249. :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).
  250. :param mode: the mode in which to open the file.
  251. :param encoding: the encoding to use.
  252. :param errors: the error handling for this file.
  253. :param lazy: can be flipped to true to open the file lazily.
  254. :param atomic: in atomic mode writes go into a temporary file and it's
  255. moved on close.
  256. """
  257. if lazy:
  258. return LazyFile(filename, mode, encoding, errors, atomic=atomic)
  259. f, should_close = open_stream(filename, mode, encoding, errors,
  260. atomic=atomic)
  261. if not should_close:
  262. f = KeepOpenFile(f)
  263. return f
  264. def get_os_args():
  265. """This returns the argument part of sys.argv in the most appropriate
  266. form for processing. What this means is that this return value is in
  267. a format that works for Click to process but does not necessarily
  268. correspond well to what's actually standard for the interpreter.
  269. On most environments the return value is ``sys.argv[:1]`` unchanged.
  270. However if you are on Windows and running Python 2 the return value
  271. will actually be a list of unicode strings instead because the
  272. default behavior on that platform otherwise will not be able to
  273. carry all possible values that sys.argv can have.
  274. .. versionadded:: 6.0
  275. """
  276. # We can only extract the unicode argv if sys.argv has not been
  277. # changed since the startup of the application.
  278. if PY2 and WIN and _initial_argv_hash == _hash_py_argv():
  279. return _get_windows_argv()
  280. return sys.argv[1:]
  281. def format_filename(filename, shorten=False):
  282. """Formats a filename for user display. The main purpose of this
  283. function is to ensure that the filename can be displayed at all. This
  284. will decode the filename to unicode if necessary in a way that it will
  285. not fail. Optionally, it can shorten the filename to not include the
  286. full path to the filename.
  287. :param filename: formats a filename for UI display. This will also convert
  288. the filename into unicode without failing.
  289. :param shorten: this optionally shortens the filename to strip of the
  290. path that leads up to it.
  291. """
  292. if shorten:
  293. filename = os.path.basename(filename)
  294. return filename_to_ui(filename)
  295. def get_app_dir(app_name, roaming=True, force_posix=False):
  296. r"""Returns the config folder for the application. The default behavior
  297. is to return whatever is most appropriate for the operating system.
  298. To give you an idea, for an app called ``"Foo Bar"``, something like
  299. the following folders could be returned:
  300. Mac OS X:
  301. ``~/Library/Application Support/Foo Bar``
  302. Mac OS X (POSIX):
  303. ``~/.foo-bar``
  304. Unix:
  305. ``~/.config/foo-bar``
  306. Unix (POSIX):
  307. ``~/.foo-bar``
  308. Win XP (roaming):
  309. ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
  310. Win XP (not roaming):
  311. ``C:\Documents and Settings\<user>\Application Data\Foo Bar``
  312. Win 7 (roaming):
  313. ``C:\Users\<user>\AppData\Roaming\Foo Bar``
  314. Win 7 (not roaming):
  315. ``C:\Users\<user>\AppData\Local\Foo Bar``
  316. .. versionadded:: 2.0
  317. :param app_name: the application name. This should be properly capitalized
  318. and can contain whitespace.
  319. :param roaming: controls if the folder should be roaming or not on Windows.
  320. Has no affect otherwise.
  321. :param force_posix: if this is set to `True` then on any POSIX system the
  322. folder will be stored in the home folder with a leading
  323. dot instead of the XDG config home or darwin's
  324. application support folder.
  325. """
  326. if WIN:
  327. key = roaming and 'APPDATA' or 'LOCALAPPDATA'
  328. folder = os.environ.get(key)
  329. if folder is None:
  330. folder = os.path.expanduser('~')
  331. return os.path.join(folder, app_name)
  332. if force_posix:
  333. return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))
  334. if sys.platform == 'darwin':
  335. return os.path.join(os.path.expanduser(
  336. '~/Library/Application Support'), app_name)
  337. return os.path.join(
  338. os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),
  339. _posixify(app_name))