Coverage for typer / _click / utils.py: 100%

190 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-18 11:12 +0000

1import os 1defgabchij

2import re 1defgabchij

3import sys 1defgabchij

4from collections.abc import Callable, Iterable, Iterator 1defgabchij

5from functools import update_wrapper 1defgabchij

6from types import ModuleType, TracebackType 1defgabchij

7from typing import ( 1defgabchij

8 IO, 

9 Any, 

10 AnyStr, 

11 BinaryIO, 

12 Literal, 

13 ParamSpec, 

14 TextIO, 

15 TypeVar, 

16 cast, 

17) 

18 

19from ._compat import ( 1defgabchij

20 WIN, 

21 _default_text_stderr, 

22 _default_text_stdout, 

23 _find_binary_writer, 

24 auto_wrap_for_ansi, 

25 binary_streams, 

26 open_stream, 

27 should_strip_ansi, 

28 strip_ansi, 

29 text_streams, 

30) 

31from .globals import resolve_color_default 1defgabchij

32 

33P = ParamSpec("P") 1defgabchij

34R = TypeVar("R") 1defgabchij

35 

36 

37def _escape_control_characters(value: str) -> str: 1defgabchij

38 """Display untrusted diagnostic values without terminal control characters.""" 

39 return re.sub( 1defgabchij

40 r"[\x00-\x1f\x7f-\x9f]", lambda match: f"\\x{ord(match[0]):02x}", value 

41 ) 

42 

43 

44def _posixify(name: str) -> str: 1defgabchij

45 return "-".join(name.split()).lower() 1defg

46 

47 

48def safecall(func: Callable[P, R]) -> Callable[P, R | None]: 1defgabchij

49 """Wraps a function so that it swallows exceptions.""" 

50 

51 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: 1defgabchij

52 try: 1defgabchij

53 return func(*args, **kwargs) 1defgabchij

54 except Exception: # pragma: no cover 

55 pass 

56 return None # pragma: no cover 

57 

58 return update_wrapper(wrapper, func) 1defgabchij

59 

60 

61def make_default_short_help(help: str, max_length: int = 45) -> str: 1defgabchij

62 """Returns a condensed version of help string.""" 

63 # Consider only the first paragraph. 

64 paragraph_end = help.find("\n\n") 1defgabchij

65 

66 if paragraph_end != -1: 1defgabchij

67 help = help[:paragraph_end] 1defgabchij

68 

69 # Collapse newlines, tabs, and spaces. 

70 words = help.split() 1defgabchij

71 

72 if not words: 1defgabchij

73 return "" 1defgabchij

74 

75 # The first paragraph started with a "no rewrap" marker, ignore it. 

76 if words[0] == "\b": 1defgabchij

77 words = words[1:] 1defgabchij

78 

79 total_length = 0 1defgabchij

80 last_index = len(words) - 1 1defgabchij

81 

82 for i, word in enumerate(words): 1defgabchij

83 total_length += len(word) + (i > 0) 1defgabchij

84 

85 if total_length > max_length: # too long, truncate 1defgabchij

86 break 1defgabchij

87 

88 if word[-1] == ".": # sentence end, truncate without "..." 1defgabchij

89 return " ".join(words[: i + 1]) 1defgabchij

90 

91 if total_length == max_length and i != last_index: 1defgabchij

92 break # not at sentence end, truncate with "..." 1defgabchij

93 else: 

94 return " ".join(words) # no truncation needed 1defgabchij

95 

96 # Account for the length of the suffix. 

97 total_length += len("...") 1defgabchij

98 

99 # remove words until the length is short enough 

100 while i > 0: 1defgabchij

101 total_length -= len(words[i]) + (i > 0) 1defgabchij

102 

103 if total_length <= max_length: 1defgabchij

104 break 1defgabchij

105 

106 i -= 1 1defgabchij

107 

108 return " ".join(words[:i]) + "..." 1defgabchij

109 

110 

111class LazyFile: 1defgabchij

112 """A lazy file works like a regular file but it does not fully open 

113 the file but it does perform some basic checks early to see if the 

114 filename parameter does make sense. This is useful for safely opening 

115 files for writing. 

116 """ 

117 

118 def __init__( 1defgabchij

119 self, 

120 filename: str | os.PathLike[str], 

121 mode: str = "r", 

122 encoding: str | None = None, 

123 errors: str | None = "strict", 

124 atomic: bool = False, 

125 ): 

126 self.name: str = os.fspath(filename) 1defgabchij

127 self.mode = mode 1defgabchij

128 self.encoding = encoding 1defgabchij

129 self.errors = errors 1defgabchij

130 self.atomic = atomic 1defgabchij

131 self._f: IO[Any] | None 1defgabchij

132 self.should_close: bool 1defgabchij

133 

134 if self.name == "-": 1defgabchij

135 self._f, self.should_close = open_stream(filename, mode, encoding, errors) 1defgabchij

136 else: 

137 if "r" in mode: 1defgabchij

138 # Open and close the file in case we're opening it for 

139 # reading so that we can catch at least some errors in 

140 # some cases early. 

141 open(filename, mode).close() 1defgabchij

142 self._f = None 1defgabchij

143 self.should_close = True 1defgabchij

144 

145 def __getattr__(self, name: str) -> Any: 1defgabchij

146 return getattr(self.open(), name) 1defgabchij

147 

148 def __repr__(self) -> str: 1defgabchij

149 if self._f is not None: 1defgabchij

150 return repr(self._f) 1defgabchij

151 return f"<unopened file '{format_filename(self.name)}' {self.mode}>" 1defgabchij

152 

153 def open(self) -> IO[Any]: 1defgabchij

154 """Opens the file if it's not yet open. This call might fail with 

155 a `FileError`. Not handling this error will produce an error 

156 that Click shows. 

157 """ 

158 if self._f is not None: 1defgabchij

159 return self._f 1defgabchij

160 try: 1defgabchij

161 rv, self.should_close = open_stream( 1defgabchij

162 self.name, self.mode, self.encoding, self.errors, atomic=self.atomic 

163 ) 

164 except OSError as e: 1defgabchij

165 from .exceptions import FileError 1defgabchij

166 

167 raise FileError(self.name, hint=e.strerror) from e 1defgabchij

168 self._f = rv 1defgabchij

169 return rv 1defgabchij

170 

171 def close(self) -> None: 1defgabchij

172 """Closes the underlying file, no matter what.""" 

173 if self._f is not None: 1defgabchij

174 self._f.close() 1defgabchij

175 

176 def close_intelligently(self) -> None: 1defgabchij

177 """This function only closes the file if it was opened by the lazy 

178 file wrapper. For instance this will never close stdin. 

179 """ 

180 if self.should_close: 1defgabchij

181 self.close() 1defgabchij

182 

183 def __enter__(self) -> "LazyFile": 1defgabchij

184 return self 1defgabchij

185 

186 def __exit__( 1defgabchij

187 self, 

188 exc_type: type[BaseException] | None, 

189 exc_value: BaseException | None, 

190 tb: TracebackType | None, 

191 ) -> None: 

192 self.close_intelligently() 1defgabchij

193 

194 def __iter__(self) -> Iterator[AnyStr]: 1defgabchij

195 self.open() 1defgabchij

196 return iter(self._f) # type: ignore 1defgabchij

197 

198 

199def echo( 1defgabchij

200 message: Any | None = None, 

201 file: IO[Any] | None = None, 

202 nl: bool = True, 

203 err: bool = False, 

204 color: bool | None = None, 

205) -> None: 

206 """Print a message and newline to stdout or a file. This should be 

207 used instead of `print` because it provides better support 

208 for different data, files, and environments. 

209 

210 Compared to `print`, this does the following: 

211 

212 - Ensures that the output encoding is not misconfigured on Linux. 

213 - Supports Unicode in the Windows console. 

214 - Supports writing to binary outputs, and supports writing bytes 

215 to text outputs. 

216 - Supports colors and styles on Windows. 

217 - Removes ANSI color and style codes if the output does not look 

218 like an interactive terminal. 

219 - Always flushes the output. 

220 """ 

221 if file is None: 1defgabchij

222 if err: 1defgabchij

223 file = _default_text_stderr() 1defgabchij

224 else: 

225 file = _default_text_stdout() 1defgabchij

226 

227 # There are no standard streams attached to write to. For example, 

228 # pythonw on Windows. 

229 if file is None: 1defgabchij

230 return 1defgabchij

231 

232 # Convert non bytes/text into the native string type. 

233 if message is not None and not isinstance(message, (str, bytes, bytearray)): 1defgabchij

234 out: str | bytes | bytearray | None = str(message) 1defgabchij

235 else: 

236 out = message 1defgabchij

237 

238 if nl: 1defgabchij

239 out = out or "" 1defgabchij

240 if isinstance(out, str): 1defgabchij

241 out += "\n" 1defgabchij

242 else: 

243 out += b"\n" 1defgabchij

244 

245 if not out: 1defgabchij

246 file.flush() 1defgabchij

247 return 1defgabchij

248 

249 # If there is a message and the value looks like bytes, we manually 

250 # need to find the binary stream and write the message in there. 

251 # This is done separately so that most stream types will work as you 

252 # would expect. Eg: you can write to StringIO for other cases. 

253 if isinstance(out, (bytes, bytearray)): 1defgabchij

254 binary_file = _find_binary_writer(file) 1defgabchij

255 

256 if binary_file is not None: 1defgabchij

257 file.flush() 1defgabchij

258 binary_file.write(out) 1defgabchij

259 binary_file.flush() 1defgabchij

260 return 1defgabchij

261 

262 # ANSI style code support. For no message or bytes, nothing happens. 

263 # When outputting to a file instead of a terminal, strip codes. 

264 else: 

265 color = resolve_color_default(color) 1defgabchij

266 

267 if should_strip_ansi(file, color): 1defgabchij

268 out = strip_ansi(out) 1defgabchij

269 elif WIN: 1defgabchij

270 if auto_wrap_for_ansi is not None: 1abc

271 file = auto_wrap_for_ansi(file, color) # type: ignore[arg-type,call-arg] 1abc

272 elif not color: 1abc

273 out = strip_ansi(out) 1abc

274 

275 file.write(out) # type: ignore[arg-type] 1defgabchij

276 file.flush() 1defgabchij

277 

278 

279def get_binary_stream(name: Literal["stdin", "stdout", "stderr"]) -> BinaryIO: 1defgabchij

280 """Returns a system stream for byte processing.""" 

281 opener = binary_streams.get(name) 1defgabchij

282 if opener is None: 1defgabchij

283 raise TypeError(f"Unknown standard stream '{name}'") 1defgabchij

284 return opener() 1defgabchij

285 

286 

287def get_text_stream( 1defgabchij

288 name: Literal["stdin", "stdout", "stderr"], 

289 encoding: str | None = None, 

290 errors: str | None = "strict", 

291) -> TextIO: 

292 """Returns a system stream for text processing. This usually returns 

293 a wrapped stream around a binary stream returned from 

294 `get_binary_stream` but it also can take shortcuts for already 

295 correctly configured streams. 

296 """ 

297 opener = text_streams.get(name) 1defgabchij

298 if opener is None: 1defgabchij

299 raise TypeError(f"Unknown standard stream '{name}'") 1defgabchij

300 return opener(encoding, errors) 1defgabchij

301 

302 

303def format_filename( 1defgabchij

304 filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], 

305 shorten: bool = False, 

306) -> str: 

307 """Format a filename as a string for display. Ensures the filename can be 

308 displayed by replacing any invalid bytes or surrogate escapes in the name 

309 with the replacement character ``�``. 

310 

311 Invalid bytes or surrogate escapes will raise an error when written to a 

312 stream with ``errors="strict"``. This will typically happen with ``stdout`` 

313 when the locale is something like ``en_GB.UTF-8``. 

314 

315 Many scenarios *are* safe to write surrogates though, due to PEP 538 and 

316 PEP 540, including: 

317 

318 - Writing to ``stderr``, which uses ``errors="backslashreplace"``. 

319 - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens 

320 stdout and stderr with ``errors="surrogateescape"``. 

321 - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. 

322 - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. 

323 Python opens stdout and stderr with ``errors="surrogateescape"``. 

324 """ 

325 if shorten: 1defgabchij

326 filename = os.path.basename(filename) 1defgabchij

327 else: 

328 filename = os.fspath(filename) 1defgabchij

329 

330 if isinstance(filename, bytes): 1defgabchij

331 filename = filename.decode(sys.getfilesystemencoding(), "replace") 1defgabchij

332 else: 

333 filename = filename.encode("utf-8", "surrogateescape").decode( 1defgabchij

334 "utf-8", "replace" 

335 ) 

336 

337 return filename 1defgabchij

338 

339 

340def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: 1defgabchij

341 r"""Returns the config folder for the application. The default behavior 

342 is to return whatever is most appropriate for the operating system. 

343 

344 To give you an idea, for an app called ``"Foo Bar"``, something like 

345 the following folders could be returned: 

346 

347 Mac OS X: 

348 ``~/Library/Application Support/Foo Bar`` 

349 Mac OS X (POSIX): 

350 ``~/.foo-bar`` 

351 Unix: 

352 ``~/.config/foo-bar`` 

353 Unix (POSIX): 

354 ``~/.foo-bar`` 

355 Windows (roaming): 

356 ``C:\Users\<user>\AppData\Roaming\Foo Bar`` 

357 Windows (not roaming): 

358 ``C:\Users\<user>\AppData\Local\Foo Bar`` 

359 """ 

360 if WIN: 1defgabchij

361 key = "APPDATA" if roaming else "LOCALAPPDATA" 1abc

362 folder = os.environ.get(key) 1abc

363 if folder is None: 1abc

364 folder = os.path.expanduser("~") 1abc

365 return os.path.join(folder, app_name) 1abc

366 if force_posix: 1defghij

367 return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) 1defg

368 if sys.platform == "darwin": 1defghij

369 return os.path.join( 1hij

370 os.path.expanduser("~/Library/Application Support"), app_name 

371 ) 

372 return os.path.join( 1defg

373 os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), 

374 _posixify(app_name), 

375 ) 

376 

377 

378class PacifyFlushWrapper: 1defgabchij

379 """This wrapper is used to catch and suppress BrokenPipeErrors resulting 

380 from ``.flush()`` being called on broken pipe during the shutdown/final-GC 

381 of the Python interpreter. Notably ``.flush()`` is always called on 

382 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any 

383 other cleanup code, and the case where the underlying file is not a broken 

384 pipe, all calls and attributes are proxied. 

385 """ 

386 

387 def __init__(self, wrapped: IO[Any]) -> None: 1defgabchij

388 self.wrapped = wrapped 1defgabchij

389 

390 def flush(self) -> None: 1defgabchij

391 try: 1defgabchij

392 self.wrapped.flush() 1defgabchij

393 except OSError as e: # pragma: no cover 

394 import errno 

395 

396 if e.errno != errno.EPIPE: 

397 raise 

398 

399 def __getattr__(self, attr: str) -> Any: 1defgabchij

400 return getattr(self.wrapped, attr) 1defgabchij

401 

402 

403def _detect_program_name( 1defgabchij

404 path: str | None = None, _main: ModuleType | None = None 

405) -> str: 

406 """Determine the command used to run the program, for use in help 

407 text. If a file or entry point was executed, the file name is 

408 returned. If ``python -m`` was used to execute a module or package, 

409 ``python -m name`` is returned. 

410 

411 This doesn't try to be too precise, the goal is to give a concise 

412 name for help text. Files are only shown as their name without the 

413 path. ``python`` is only shown for modules, and the full path to 

414 ``sys.executable`` is not shown. 

415 """ 

416 if _main is None: 1defgabchij

417 _main = sys.modules["__main__"] 1defgabchij

418 

419 if not path: 1defgabchij

420 path = sys.argv[0] 1defgabchij

421 

422 # The value of __package__ indicates how Python was called. It may 

423 # not exist if a setuptools script is installed as an egg. It may be 

424 # set incorrectly for entry points created with pip on Windows. 

425 # It is set to "" inside a Shiv or PEX zipapp. 

426 if getattr(_main, "__package__", None) in {None, ""} or ( 1defgabchij

427 os.name == "nt" 

428 and _main.__package__ == "" 

429 and not os.path.exists(path) 

430 and os.path.exists(f"{path}.exe") 

431 ): 

432 # Executed a file, like "python app.py". 

433 return os.path.basename(path) 1defgabchij

434 

435 # Executed a module, like "python -m example". 

436 # Rewritten by Python from "-m script" to "/path/to/script.py". 

437 # Need to look at main module to determine how it was executed. 

438 py_module = cast(str, _main.__package__) 1defgabchij

439 name = os.path.splitext(os.path.basename(path))[0] 1defgabchij

440 

441 # A submodule like "example.cli". 

442 if name != "__main__": 1defgabchij

443 py_module = f"{py_module}.{name}" 1defgabchij

444 

445 return f"python -m {py_module.lstrip('.')}" 1defgabchij

446 

447 

448def _expand_args( 1defgabchij

449 args: Iterable[str], 

450 *, 

451 user: bool = True, 

452 env: bool = True, 

453 glob_recursive: bool = True, 

454) -> list[str]: 

455 """Simulate Unix shell expansion with Python functions.""" 

456 from glob import glob 1abc

457 

458 out = [] 1abc

459 

460 for arg in args: 1abc

461 if user: 1abc

462 arg = os.path.expanduser(arg) 1abc

463 

464 if env: 1abc

465 arg = os.path.expandvars(arg) 1abc

466 

467 try: 1abc

468 matches = glob(arg, recursive=glob_recursive) 1abc

469 except re.error: # pragma: no cover 

470 matches = [] 

471 

472 if not matches: 1abc

473 out.append(arg) 1abc

474 else: 

475 out.extend(matches) 1abc

476 

477 return out 1abc