utils.py 15 KB

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