| 1 |
""" |
| 2 |
This module contains implementations for the termui module. To keep the |
| 3 |
import time of Click down, some infrequently used functionality is |
| 4 |
placed in this module and only imported as needed. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import collections.abc as cabc |
| 10 |
import contextlib |
| 11 |
import math |
| 12 |
import os |
| 13 |
import shlex |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import typing as t |
| 17 |
from gettext import gettext as _ |
| 18 |
from io import StringIO |
| 19 |
from pathlib import Path |
| 20 |
from types import TracebackType |
| 21 |
|
| 22 |
from ._compat import _default_text_stdout |
| 23 |
from ._compat import CYGWIN |
| 24 |
from ._compat import get_best_encoding |
| 25 |
from ._compat import isatty |
| 26 |
from ._compat import open_stream |
| 27 |
from ._compat import strip_ansi |
| 28 |
from ._compat import term_len |
| 29 |
from ._compat import WIN |
| 30 |
from .exceptions import ClickException |
| 31 |
from .utils import echo |
| 32 |
|
| 33 |
V = t.TypeVar("V") |
| 34 |
|
| 35 |
if os.name == "nt": |
| 36 |
BEFORE_BAR = "\r" |
| 37 |
AFTER_BAR = "\n" |
| 38 |
else: |
| 39 |
BEFORE_BAR = "\r\033[?25l" |
| 40 |
AFTER_BAR = "\033[?25h\n" |
| 41 |
|
| 42 |
|
| 43 |
class ProgressBar(t.Generic[V]): |
| 44 |
def __init__( |
| 45 |
self, |
| 46 |
iterable: cabc.Iterable[V] | None, |
| 47 |
length: int | None = None, |
| 48 |
fill_char: str = "#", |
| 49 |
empty_char: str = " ", |
| 50 |
bar_template: str = "%(bar)s", |
| 51 |
info_sep: str = " ", |
| 52 |
hidden: bool = False, |
| 53 |
show_eta: bool = True, |
| 54 |
show_percent: bool | None = None, |
| 55 |
show_pos: bool = False, |
| 56 |
item_show_func: t.Callable[[V | None], str | None] | None = None, |
| 57 |
label: str | None = None, |
| 58 |
file: t.TextIO | None = None, |
| 59 |
color: bool | None = None, |
| 60 |
update_min_steps: int = 1, |
| 61 |
width: int = 30, |
| 62 |
) -> None: |
| 63 |
self.fill_char = fill_char |
| 64 |
self.empty_char = empty_char |
| 65 |
self.bar_template = bar_template |
| 66 |
self.info_sep = info_sep |
| 67 |
self.hidden = hidden |
| 68 |
self.show_eta = show_eta |
| 69 |
self.show_percent = show_percent |
| 70 |
self.show_pos = show_pos |
| 71 |
self.item_show_func = item_show_func |
| 72 |
self.label: str = label or "" |
| 73 |
|
| 74 |
if file is None: |
| 75 |
file = _default_text_stdout() |
| 76 |
|
| 77 |
# There are no standard streams attached to write to. For example, |
| 78 |
# pythonw on Windows. |
| 79 |
if file is None: |
| 80 |
file = StringIO() |
| 81 |
|
| 82 |
self.file = file |
| 83 |
self.color = color |
| 84 |
self.update_min_steps = update_min_steps |
| 85 |
self._completed_intervals = 0 |
| 86 |
self.width: int = width |
| 87 |
self.autowidth: bool = width == 0 |
| 88 |
|
| 89 |
if length is None: |
| 90 |
from operator import length_hint |
| 91 |
|
| 92 |
length = length_hint(iterable, -1) |
| 93 |
|
| 94 |
if length == -1: |
| 95 |
length = None |
| 96 |
if iterable is None: |
| 97 |
if length is None: |
| 98 |
raise TypeError("iterable or length is required") |
| 99 |
iterable = t.cast("cabc.Iterable[V]", range(length)) |
| 100 |
self.iter: cabc.Iterable[V] = iter(iterable) |
| 101 |
self.length = length |
| 102 |
self.pos: int = 0 |
| 103 |
self.avg: list[float] = [] |
| 104 |
self.last_eta: float |
| 105 |
self.start: float |
| 106 |
self.start = self.last_eta = time.time() |
| 107 |
self.eta_known: bool = False |
| 108 |
self.finished: bool = False |
| 109 |
self.max_width: int | None = None |
| 110 |
self.entered: bool = False |
| 111 |
self.current_item: V | None = None |
| 112 |
self._is_atty = isatty(self.file) |
| 113 |
self._last_line: str | None = None |
| 114 |
|
| 115 |
def __enter__(self) -> ProgressBar[V]: |
| 116 |
self.entered = True |
| 117 |
self.render_progress() |
| 118 |
return self |
| 119 |
|
| 120 |
def __exit__( |
| 121 |
self, |
| 122 |
exc_type: type[BaseException] | None, |
| 123 |
exc_value: BaseException | None, |
| 124 |
tb: TracebackType | None, |
| 125 |
) -> None: |
| 126 |
self.render_finish() |
| 127 |
|
| 128 |
def __iter__(self) -> cabc.Iterator[V]: |
| 129 |
if not self.entered: |
| 130 |
raise RuntimeError("You need to use progress bars in a with block.") |
| 131 |
self.render_progress() |
| 132 |
return self.generator() |
| 133 |
|
| 134 |
def __next__(self) -> V: |
| 135 |
# Iteration is defined in terms of a generator function, |
| 136 |
# returned by iter(self); use that to define next(). This works |
| 137 |
# because `self.iter` is an iterable consumed by that generator, |
| 138 |
# so it is re-entry safe. Calling `next(self.generator())` |
| 139 |
# twice works and does "what you want". |
| 140 |
return next(iter(self)) |
| 141 |
|
| 142 |
def render_finish(self) -> None: |
| 143 |
if self.hidden or not self._is_atty: |
| 144 |
return |
| 145 |
self.file.write(AFTER_BAR) |
| 146 |
self.file.flush() |
| 147 |
|
| 148 |
@property |
| 149 |
def pct(self) -> float: |
| 150 |
if self.finished: |
| 151 |
return 1.0 |
| 152 |
return min(self.pos / (float(self.length or 1) or 1), 1.0) |
| 153 |
|
| 154 |
@property |
| 155 |
def time_per_iteration(self) -> float: |
| 156 |
if not self.avg: |
| 157 |
return 0.0 |
| 158 |
return sum(self.avg) / float(len(self.avg)) |
| 159 |
|
| 160 |
@property |
| 161 |
def eta(self) -> float: |
| 162 |
if self.length is not None and not self.finished: |
| 163 |
return self.time_per_iteration * (self.length - self.pos) |
| 164 |
return 0.0 |
| 165 |
|
| 166 |
def format_eta(self) -> str: |
| 167 |
if self.eta_known: |
| 168 |
t = int(self.eta) |
| 169 |
seconds = t % 60 |
| 170 |
t //= 60 |
| 171 |
minutes = t % 60 |
| 172 |
t //= 60 |
| 173 |
hours = t % 24 |
| 174 |
t //= 24 |
| 175 |
if t > 0: |
| 176 |
return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" |
| 177 |
else: |
| 178 |
return f"{hours:02}:{minutes:02}:{seconds:02}" |
| 179 |
return "" |
| 180 |
|
| 181 |
def format_pos(self) -> str: |
| 182 |
pos = str(self.pos) |
| 183 |
if self.length is not None: |
| 184 |
pos += f"/{self.length}" |
| 185 |
return pos |
| 186 |
|
| 187 |
def format_pct(self) -> str: |
| 188 |
return f"{int(self.pct * 100): 4}%"[1:] |
| 189 |
|
| 190 |
def format_bar(self) -> str: |
| 191 |
if self.length is not None: |
| 192 |
bar_length = int(self.pct * self.width) |
| 193 |
bar = self.fill_char * bar_length |
| 194 |
bar += self.empty_char * (self.width - bar_length) |
| 195 |
elif self.finished: |
| 196 |
bar = self.fill_char * self.width |
| 197 |
else: |
| 198 |
chars = list(self.empty_char * (self.width or 1)) |
| 199 |
if self.time_per_iteration != 0: |
| 200 |
chars[ |
| 201 |
int( |
| 202 |
(math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) |
| 203 |
* self.width |
| 204 |
) |
| 205 |
] = self.fill_char |
| 206 |
bar = "".join(chars) |
| 207 |
return bar |
| 208 |
|
| 209 |
def format_progress_line(self) -> str: |
| 210 |
show_percent = self.show_percent |
| 211 |
|
| 212 |
info_bits = [] |
| 213 |
if self.length is not None and show_percent is None: |
| 214 |
show_percent = not self.show_pos |
| 215 |
|
| 216 |
if self.show_pos: |
| 217 |
info_bits.append(self.format_pos()) |
| 218 |
if show_percent: |
| 219 |
info_bits.append(self.format_pct()) |
| 220 |
if self.show_eta and self.eta_known and not self.finished: |
| 221 |
info_bits.append(self.format_eta()) |
| 222 |
if self.item_show_func is not None: |
| 223 |
item_info = self.item_show_func(self.current_item) |
| 224 |
if item_info is not None: |
| 225 |
info_bits.append(item_info) |
| 226 |
|
| 227 |
return ( |
| 228 |
self.bar_template |
| 229 |
% { |
| 230 |
"label": self.label, |
| 231 |
"bar": self.format_bar(), |
| 232 |
"info": self.info_sep.join(info_bits), |
| 233 |
} |
| 234 |
).rstrip() |
| 235 |
|
| 236 |
def render_progress(self) -> None: |
| 237 |
if self.hidden: |
| 238 |
return |
| 239 |
|
| 240 |
if not self._is_atty: |
| 241 |
# Only output the label once if the output is not a TTY. |
| 242 |
if self._last_line != self.label: |
| 243 |
self._last_line = self.label |
| 244 |
echo(self.label, file=self.file, color=self.color) |
| 245 |
return |
| 246 |
|
| 247 |
buf = [] |
| 248 |
# Update width in case the terminal has been resized |
| 249 |
if self.autowidth: |
| 250 |
import shutil |
| 251 |
|
| 252 |
old_width = self.width |
| 253 |
self.width = 0 |
| 254 |
clutter_length = term_len(self.format_progress_line()) |
| 255 |
new_width = max(0, shutil.get_terminal_size().columns - clutter_length) |
| 256 |
if new_width < old_width and self.max_width is not None: |
| 257 |
buf.append(BEFORE_BAR) |
| 258 |
buf.append(" " * self.max_width) |
| 259 |
self.max_width = new_width |
| 260 |
self.width = new_width |
| 261 |
|
| 262 |
clear_width = self.width |
| 263 |
if self.max_width is not None: |
| 264 |
clear_width = self.max_width |
| 265 |
|
| 266 |
buf.append(BEFORE_BAR) |
| 267 |
line = self.format_progress_line() |
| 268 |
line_len = term_len(line) |
| 269 |
if self.max_width is None or self.max_width < line_len: |
| 270 |
self.max_width = line_len |
| 271 |
|
| 272 |
buf.append(line) |
| 273 |
buf.append(" " * (clear_width - line_len)) |
| 274 |
line = "".join(buf) |
| 275 |
# Render the line only if it changed. |
| 276 |
|
| 277 |
if line != self._last_line: |
| 278 |
self._last_line = line |
| 279 |
echo(line, file=self.file, color=self.color, nl=False) |
| 280 |
self.file.flush() |
| 281 |
|
| 282 |
def make_step(self, n_steps: int) -> None: |
| 283 |
self.pos += n_steps |
| 284 |
if self.length is not None and self.pos >= self.length: |
| 285 |
self.finished = True |
| 286 |
|
| 287 |
if (time.time() - self.last_eta) < 1.0: |
| 288 |
return |
| 289 |
|
| 290 |
self.last_eta = time.time() |
| 291 |
|
| 292 |
# self.avg is a rolling list of length <= 7 of steps where steps are |
| 293 |
# defined as time elapsed divided by the total progress through |
| 294 |
# self.length. |
| 295 |
if self.pos: |
| 296 |
step = (time.time() - self.start) / self.pos |
| 297 |
else: |
| 298 |
step = time.time() - self.start |
| 299 |
|
| 300 |
self.avg = self.avg[-6:] + [step] |
| 301 |
|
| 302 |
self.eta_known = self.length is not None |
| 303 |
|
| 304 |
def update(self, n_steps: int, current_item: V | None = None) -> None: |
| 305 |
"""Update the progress bar by advancing a specified number of |
| 306 |
steps, and optionally set the ``current_item`` for this new |
| 307 |
position. |
| 308 |
|
| 309 |
:param n_steps: Number of steps to advance. |
| 310 |
:param current_item: Optional item to set as ``current_item`` |
| 311 |
for the updated position. |
| 312 |
|
| 313 |
.. versionchanged:: 8.0 |
| 314 |
Added the ``current_item`` optional parameter. |
| 315 |
|
| 316 |
.. versionchanged:: 8.0 |
| 317 |
Only render when the number of steps meets the |
| 318 |
``update_min_steps`` threshold. |
| 319 |
""" |
| 320 |
if current_item is not None: |
| 321 |
self.current_item = current_item |
| 322 |
|
| 323 |
self._completed_intervals += n_steps |
| 324 |
|
| 325 |
if self._completed_intervals >= self.update_min_steps: |
| 326 |
self.make_step(self._completed_intervals) |
| 327 |
self.render_progress() |
| 328 |
self._completed_intervals = 0 |
| 329 |
|
| 330 |
def finish(self) -> None: |
| 331 |
self.eta_known = False |
| 332 |
self.current_item = None |
| 333 |
self.finished = True |
| 334 |
|
| 335 |
def generator(self) -> cabc.Iterator[V]: |
| 336 |
"""Return a generator which yields the items added to the bar |
| 337 |
during construction, and updates the progress bar *after* the |
| 338 |
yielded block returns. |
| 339 |
""" |
| 340 |
# WARNING: the iterator interface for `ProgressBar` relies on |
| 341 |
# this and only works because this is a simple generator which |
| 342 |
# doesn't create or manage additional state. If this function |
| 343 |
# changes, the impact should be evaluated both against |
| 344 |
# `iter(bar)` and `next(bar)`. `next()` in particular may call |
| 345 |
# `self.generator()` repeatedly, and this must remain safe in |
| 346 |
# order for that interface to work. |
| 347 |
if not self.entered: |
| 348 |
raise RuntimeError("You need to use progress bars in a with block.") |
| 349 |
|
| 350 |
if not self._is_atty: |
| 351 |
yield from self.iter |
| 352 |
else: |
| 353 |
for rv in self.iter: |
| 354 |
self.current_item = rv |
| 355 |
|
| 356 |
# This allows show_item_func to be updated before the |
| 357 |
# item is processed. Only trigger at the beginning of |
| 358 |
# the update interval. |
| 359 |
if self._completed_intervals == 0: |
| 360 |
self.render_progress() |
| 361 |
|
| 362 |
yield rv |
| 363 |
self.update(1) |
| 364 |
|
| 365 |
self.finish() |
| 366 |
self.render_progress() |
| 367 |
|
| 368 |
|
| 369 |
def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None: |
| 370 |
"""Decide what method to use for paging through text.""" |
| 371 |
stdout = _default_text_stdout() |
| 372 |
|
| 373 |
# There are no standard streams attached to write to. For example, |
| 374 |
# pythonw on Windows. |
| 375 |
if stdout is None: |
| 376 |
stdout = StringIO() |
| 377 |
|
| 378 |
if not isatty(sys.stdin) or not isatty(stdout): |
| 379 |
return _nullpager(stdout, generator, color) |
| 380 |
|
| 381 |
# Split and normalize the pager command into parts. |
| 382 |
pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False) |
| 383 |
if pager_cmd_parts: |
| 384 |
if WIN: |
| 385 |
if _tempfilepager(generator, pager_cmd_parts, color): |
| 386 |
return |
| 387 |
elif _pipepager(generator, pager_cmd_parts, color): |
| 388 |
return |
| 389 |
|
| 390 |
if os.environ.get("TERM") in ("dumb", "emacs"): |
| 391 |
return _nullpager(stdout, generator, color) |
| 392 |
if (WIN or sys.platform.startswith("os2")) and _tempfilepager( |
| 393 |
generator, ["more"], color |
| 394 |
): |
| 395 |
return |
| 396 |
if _pipepager(generator, ["less"], color): |
| 397 |
return |
| 398 |
|
| 399 |
import tempfile |
| 400 |
|
| 401 |
fd, filename = tempfile.mkstemp() |
| 402 |
os.close(fd) |
| 403 |
try: |
| 404 |
if _pipepager(generator, ["more"], color): |
| 405 |
return |
| 406 |
return _nullpager(stdout, generator, color) |
| 407 |
finally: |
| 408 |
os.unlink(filename) |
| 409 |
|
| 410 |
|
| 411 |
def _pipepager( |
| 412 |
generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None |
| 413 |
) -> bool: |
| 414 |
"""Page through text by feeding it to another program. Invoking a |
| 415 |
pager through this might support colors. |
| 416 |
|
| 417 |
Returns `True` if the command was found, `False` otherwise and thus another |
| 418 |
pager should be attempted. |
| 419 |
""" |
| 420 |
# Split the command into the invoked CLI and its parameters. |
| 421 |
if not cmd_parts: |
| 422 |
return False |
| 423 |
|
| 424 |
import shutil |
| 425 |
|
| 426 |
cmd = cmd_parts[0] |
| 427 |
cmd_params = cmd_parts[1:] |
| 428 |
|
| 429 |
cmd_filepath = shutil.which(cmd) |
| 430 |
if not cmd_filepath: |
| 431 |
return False |
| 432 |
# Resolves symlinks and produces a normalized absolute path string. |
| 433 |
cmd_path = Path(cmd_filepath).resolve() |
| 434 |
cmd_name = cmd_path.name |
| 435 |
|
| 436 |
import subprocess |
| 437 |
|
| 438 |
# Make a local copy of the environment to not affect the global one. |
| 439 |
env = dict(os.environ) |
| 440 |
|
| 441 |
# If we're piping to less and the user hasn't decided on colors, we enable |
| 442 |
# them by default we find the -R flag in the command line arguments. |
| 443 |
if color is None and cmd_name == "less": |
| 444 |
less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" |
| 445 |
if not less_flags: |
| 446 |
env["LESS"] = "-R" |
| 447 |
color = True |
| 448 |
elif "r" in less_flags or "R" in less_flags: |
| 449 |
color = True |
| 450 |
|
| 451 |
c = subprocess.Popen( |
| 452 |
[str(cmd_path)] + cmd_params, |
| 453 |
shell=True, |
| 454 |
stdin=subprocess.PIPE, |
| 455 |
env=env, |
| 456 |
errors="replace", |
| 457 |
text=True, |
| 458 |
) |
| 459 |
assert c.stdin is not None |
| 460 |
try: |
| 461 |
for text in generator: |
| 462 |
if not color: |
| 463 |
text = strip_ansi(text) |
| 464 |
|
| 465 |
c.stdin.write(text) |
| 466 |
except BrokenPipeError: |
| 467 |
# In case the pager exited unexpectedly, ignore the broken pipe error. |
| 468 |
pass |
| 469 |
except Exception as e: |
| 470 |
# In case there is an exception we want to close the pager immediately |
| 471 |
# and let the caller handle it. |
| 472 |
# Otherwise the pager will keep running, and the user may not notice |
| 473 |
# the error message, or worse yet it may leave the terminal in a broken state. |
| 474 |
c.terminate() |
| 475 |
raise e |
| 476 |
finally: |
| 477 |
# We must close stdin and wait for the pager to exit before we continue |
| 478 |
try: |
| 479 |
c.stdin.close() |
| 480 |
# Close implies flush, so it might throw a BrokenPipeError if the pager |
| 481 |
# process exited already. |
| 482 |
except BrokenPipeError: |
| 483 |
pass |
| 484 |
|
| 485 |
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting |
| 486 |
# search or other commands inside less). |
| 487 |
# |
| 488 |
# That means when the user hits ^C, the parent process (click) terminates, |
| 489 |
# but less is still alive, paging the output and messing up the terminal. |
| 490 |
# |
| 491 |
# If the user wants to make the pager exit on ^C, they should set |
| 492 |
# `LESS='-K'`. It's not our decision to make. |
| 493 |
while True: |
| 494 |
try: |
| 495 |
c.wait() |
| 496 |
except KeyboardInterrupt: |
| 497 |
pass |
| 498 |
else: |
| 499 |
break |
| 500 |
|
| 501 |
return True |
| 502 |
|
| 503 |
|
| 504 |
def _tempfilepager( |
| 505 |
generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None |
| 506 |
) -> bool: |
| 507 |
"""Page through text by invoking a program on a temporary file. |
| 508 |
|
| 509 |
Returns `True` if the command was found, `False` otherwise and thus another |
| 510 |
pager should be attempted. |
| 511 |
""" |
| 512 |
# Split the command into the invoked CLI and its parameters. |
| 513 |
if not cmd_parts: |
| 514 |
return False |
| 515 |
|
| 516 |
import shutil |
| 517 |
|
| 518 |
cmd = cmd_parts[0] |
| 519 |
|
| 520 |
cmd_filepath = shutil.which(cmd) |
| 521 |
if not cmd_filepath: |
| 522 |
return False |
| 523 |
# Resolves symlinks and produces a normalized absolute path string. |
| 524 |
cmd_path = Path(cmd_filepath).resolve() |
| 525 |
|
| 526 |
import subprocess |
| 527 |
import tempfile |
| 528 |
|
| 529 |
fd, filename = tempfile.mkstemp() |
| 530 |
# TODO: This never terminates if the passed generator never terminates. |
| 531 |
text = "".join(generator) |
| 532 |
if not color: |
| 533 |
text = strip_ansi(text) |
| 534 |
encoding = get_best_encoding(sys.stdout) |
| 535 |
with open_stream(filename, "wb")[0] as f: |
| 536 |
f.write(text.encode(encoding)) |
| 537 |
try: |
| 538 |
subprocess.call([str(cmd_path), filename]) |
| 539 |
except OSError: |
| 540 |
# Command not found |
| 541 |
pass |
| 542 |
finally: |
| 543 |
os.close(fd) |
| 544 |
os.unlink(filename) |
| 545 |
|
| 546 |
return True |
| 547 |
|
| 548 |
|
| 549 |
def _nullpager( |
| 550 |
stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None |
| 551 |
) -> None: |
| 552 |
"""Simply print unformatted text. This is the ultimate fallback.""" |
| 553 |
for text in generator: |
| 554 |
if not color: |
| 555 |
text = strip_ansi(text) |
| 556 |
stream.write(text) |
| 557 |
|
| 558 |
|
| 559 |
class Editor: |
| 560 |
def __init__( |
| 561 |
self, |
| 562 |
editor: str | None = None, |
| 563 |
env: cabc.Mapping[str, str] | None = None, |
| 564 |
require_save: bool = True, |
| 565 |
extension: str = ".txt", |
| 566 |
) -> None: |
| 567 |
self.editor = editor |
| 568 |
self.env = env |
| 569 |
self.require_save = require_save |
| 570 |
self.extension = extension |
| 571 |
|
| 572 |
def get_editor(self) -> str: |
| 573 |
if self.editor is not None: |
| 574 |
return self.editor |
| 575 |
for key in "VISUAL", "EDITOR": |
| 576 |
rv = os.environ.get(key) |
| 577 |
if rv: |
| 578 |
return rv |
| 579 |
if WIN: |
| 580 |
return "notepad" |
| 581 |
|
| 582 |
from shutil import which |
| 583 |
|
| 584 |
for editor in "sensible-editor", "vim", "nano": |
| 585 |
if which(editor) is not None: |
| 586 |
return editor |
| 587 |
return "vi" |
| 588 |
|
| 589 |
def edit_files(self, filenames: cabc.Iterable[str]) -> None: |
| 590 |
import subprocess |
| 591 |
|
| 592 |
editor = self.get_editor() |
| 593 |
environ: dict[str, str] | None = None |
| 594 |
|
| 595 |
if self.env: |
| 596 |
environ = os.environ.copy() |
| 597 |
environ.update(self.env) |
| 598 |
|
| 599 |
exc_filename = " ".join(f'"{filename}"' for filename in filenames) |
| 600 |
|
| 601 |
try: |
| 602 |
c = subprocess.Popen( |
| 603 |
args=f"{editor} {exc_filename}", env=environ, shell=True |
| 604 |
) |
| 605 |
exit_code = c.wait() |
| 606 |
if exit_code != 0: |
| 607 |
raise ClickException( |
| 608 |
_("{editor}: Editing failed").format(editor=editor) |
| 609 |
) |
| 610 |
except OSError as e: |
| 611 |
raise ClickException( |
| 612 |
_("{editor}: Editing failed: {e}").format(editor=editor, e=e) |
| 613 |
) from e |
| 614 |
|
| 615 |
@t.overload |
| 616 |
def edit(self, text: bytes | bytearray) -> bytes | None: ... |
| 617 |
|
| 618 |
# We cannot know whether or not the type expected is str or bytes when None |
| 619 |
# is passed, so str is returned as that was what was done before. |
| 620 |
@t.overload |
| 621 |
def edit(self, text: str | None) -> str | None: ... |
| 622 |
|
| 623 |
def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: |
| 624 |
import tempfile |
| 625 |
|
| 626 |
if text is None: |
| 627 |
data: bytes | bytearray = b"" |
| 628 |
elif isinstance(text, (bytes, bytearray)): |
| 629 |
data = text |
| 630 |
else: |
| 631 |
if text and not text.endswith("\n"): |
| 632 |
text += "\n" |
| 633 |
|
| 634 |
if WIN: |
| 635 |
data = text.replace("\n", "\r\n").encode("utf-8-sig") |
| 636 |
else: |
| 637 |
data = text.encode("utf-8") |
| 638 |
|
| 639 |
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) |
| 640 |
f: t.BinaryIO |
| 641 |
|
| 642 |
try: |
| 643 |
with os.fdopen(fd, "wb") as f: |
| 644 |
f.write(data) |
| 645 |
|
| 646 |
# If the filesystem resolution is 1 second, like Mac OS |
| 647 |
# 10.12 Extended, or 2 seconds, like FAT32, and the editor |
| 648 |
# closes very fast, require_save can fail. Set the modified |
| 649 |
# time to be 2 seconds in the past to work around this. |
| 650 |
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) |
| 651 |
# Depending on the resolution, the exact value might not be |
| 652 |
# recorded, so get the new recorded value. |
| 653 |
timestamp = os.path.getmtime(name) |
| 654 |
|
| 655 |
self.edit_files((name,)) |
| 656 |
|
| 657 |
if self.require_save and os.path.getmtime(name) == timestamp: |
| 658 |
return None |
| 659 |
|
| 660 |
with open(name, "rb") as f: |
| 661 |
rv = f.read() |
| 662 |
|
| 663 |
if isinstance(text, (bytes, bytearray)): |
| 664 |
return rv |
| 665 |
|
| 666 |
return rv.decode("utf-8-sig").replace("\r\n", "\n") |
| 667 |
finally: |
| 668 |
os.unlink(name) |
| 669 |
|
| 670 |
|
| 671 |
def open_url(url: str, wait: bool = False, locate: bool = False) -> int: |
| 672 |
import subprocess |
| 673 |
|
| 674 |
def _unquote_file(url: str) -> str: |
| 675 |
from urllib.parse import unquote |
| 676 |
|
| 677 |
if url.startswith("file://"): |
| 678 |
url = unquote(url[7:]) |
| 679 |
|
| 680 |
return url |
| 681 |
|
| 682 |
if sys.platform == "darwin": |
| 683 |
args = ["open"] |
| 684 |
if wait: |
| 685 |
args.append("-W") |
| 686 |
if locate: |
| 687 |
args.append("-R") |
| 688 |
args.append(_unquote_file(url)) |
| 689 |
null = open("/dev/null", "w") |
| 690 |
try: |
| 691 |
return subprocess.Popen(args, stderr=null).wait() |
| 692 |
finally: |
| 693 |
null.close() |
| 694 |
elif WIN: |
| 695 |
if locate: |
| 696 |
url = _unquote_file(url) |
| 697 |
args = ["explorer", f"/select,{url}"] |
| 698 |
else: |
| 699 |
args = ["start"] |
| 700 |
if wait: |
| 701 |
args.append("/WAIT") |
| 702 |
args.append("") |
| 703 |
args.append(url) |
| 704 |
try: |
| 705 |
return subprocess.call(args) |
| 706 |
except OSError: |
| 707 |
# Command not found |
| 708 |
return 127 |
| 709 |
elif CYGWIN: |
| 710 |
if locate: |
| 711 |
url = _unquote_file(url) |
| 712 |
args = ["cygstart", os.path.dirname(url)] |
| 713 |
else: |
| 714 |
args = ["cygstart"] |
| 715 |
if wait: |
| 716 |
args.append("-w") |
| 717 |
args.append(url) |
| 718 |
try: |
| 719 |
return subprocess.call(args) |
| 720 |
except OSError: |
| 721 |
# Command not found |
| 722 |
return 127 |
| 723 |
|
| 724 |
try: |
| 725 |
if locate: |
| 726 |
url = os.path.dirname(_unquote_file(url)) or "." |
| 727 |
else: |
| 728 |
url = _unquote_file(url) |
| 729 |
c = subprocess.Popen(["xdg-open", url]) |
| 730 |
if wait: |
| 731 |
return c.wait() |
| 732 |
return 0 |
| 733 |
except OSError: |
| 734 |
if url.startswith(("http://", "https://")) and not locate and not wait: |
| 735 |
import webbrowser |
| 736 |
|
| 737 |
webbrowser.open(url) |
| 738 |
return 0 |
| 739 |
return 1 |
| 740 |
|
| 741 |
|
| 742 |
def _translate_ch_to_exc(ch: str) -> None: |
| 743 |
if ch == "\x03": |
| 744 |
raise KeyboardInterrupt() |
| 745 |
|
| 746 |
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D |
| 747 |
raise EOFError() |
| 748 |
|
| 749 |
if ch == "\x1a" and WIN: # Windows, Ctrl+Z |
| 750 |
raise EOFError() |
| 751 |
|
| 752 |
return None |
| 753 |
|
| 754 |
|
| 755 |
if sys.platform == "win32": |
| 756 |
import msvcrt |
| 757 |
|
| 758 |
@contextlib.contextmanager |
| 759 |
def raw_terminal() -> cabc.Iterator[int]: |
| 760 |
yield -1 |
| 761 |
|
| 762 |
def getchar(echo: bool) -> str: |
| 763 |
# The function `getch` will return a bytes object corresponding to |
| 764 |
# the pressed character. Since Windows 10 build 1803, it will also |
| 765 |
# return \x00 when called a second time after pressing a regular key. |
| 766 |
# |
| 767 |
# `getwch` does not share this probably-bugged behavior. Moreover, it |
| 768 |
# returns a Unicode object by default, which is what we want. |
| 769 |
# |
| 770 |
# Either of these functions will return \x00 or \xe0 to indicate |
| 771 |
# a special key, and you need to call the same function again to get |
| 772 |
# the "rest" of the code. The fun part is that \u00e0 is |
| 773 |
# "latin small letter a with grave", so if you type that on a French |
| 774 |
# keyboard, you _also_ get a \xe0. |
| 775 |
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The |
| 776 |
# resulting Unicode string reads as "a with grave" + "capital H". |
| 777 |
# This is indistinguishable from when the user actually types |
| 778 |
# "a with grave" and then "capital H". |
| 779 |
# |
| 780 |
# When \xe0 is returned, we assume it's part of a special-key sequence |
| 781 |
# and call `getwch` again, but that means that when the user types |
| 782 |
# the \u00e0 character, `getchar` doesn't return until a second |
| 783 |
# character is typed. |
| 784 |
# The alternative is returning immediately, but that would mess up |
| 785 |
# cross-platform handling of arrow keys and others that start with |
| 786 |
# \xe0. Another option is using `getch`, but then we can't reliably |
| 787 |
# read non-ASCII characters, because return values of `getch` are |
| 788 |
# limited to the current 8-bit codepage. |
| 789 |
# |
| 790 |
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch` |
| 791 |
# is doing the right thing in more situations than with `getch`. |
| 792 |
|
| 793 |
if echo: |
| 794 |
func = t.cast(t.Callable[[], str], msvcrt.getwche) |
| 795 |
else: |
| 796 |
func = t.cast(t.Callable[[], str], msvcrt.getwch) |
| 797 |
|
| 798 |
rv = func() |
| 799 |
|
| 800 |
if rv in ("\x00", "\xe0"): |
| 801 |
# \x00 and \xe0 are control characters that indicate special key, |
| 802 |
# see above. |
| 803 |
rv += func() |
| 804 |
|
| 805 |
_translate_ch_to_exc(rv) |
| 806 |
return rv |
| 807 |
|
| 808 |
else: |
| 809 |
import termios |
| 810 |
import tty |
| 811 |
|
| 812 |
@contextlib.contextmanager |
| 813 |
def raw_terminal() -> cabc.Iterator[int]: |
| 814 |
f: t.TextIO | None |
| 815 |
fd: int |
| 816 |
|
| 817 |
if not isatty(sys.stdin): |
| 818 |
f = open("/dev/tty") |
| 819 |
fd = f.fileno() |
| 820 |
else: |
| 821 |
fd = sys.stdin.fileno() |
| 822 |
f = None |
| 823 |
|
| 824 |
try: |
| 825 |
old_settings = termios.tcgetattr(fd) |
| 826 |
|
| 827 |
try: |
| 828 |
tty.setraw(fd) |
| 829 |
yield fd |
| 830 |
finally: |
| 831 |
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) |
| 832 |
sys.stdout.flush() |
| 833 |
|
| 834 |
if f is not None: |
| 835 |
f.close() |
| 836 |
except termios.error: |
| 837 |
pass |
| 838 |
|
| 839 |
def getchar(echo: bool) -> str: |
| 840 |
with raw_terminal() as fd: |
| 841 |
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace") |
| 842 |
|
| 843 |
if echo and isatty(sys.stdout): |
| 844 |
sys.stdout.write(ch) |
| 845 |
|
| 846 |
_translate_ch_to_exc(ch) |
| 847 |
return ch |