utils.py 16 KB

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