multiCMD 1.67__tar.gz → 1.69__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {multicmd-1.67 → multicmd-1.69}/PKG-INFO +37 -1
  2. {multicmd-1.67 → multicmd-1.69}/README.md +36 -0
  3. {multicmd-1.67 → multicmd-1.69}/multiCMD.egg-info/PKG-INFO +37 -1
  4. {multicmd-1.67 → multicmd-1.69}/multiCMD.egg-info/SOURCES.txt +1 -0
  5. {multicmd-1.67 → multicmd-1.69}/multiCMD.py +162 -52
  6. {multicmd-1.67 → multicmd-1.69}/tests/test_helpers.py +19 -4
  7. {multicmd-1.67 → multicmd-1.69}/tests/test_interrupts.py +22 -4
  8. multicmd-1.69/tests/test_terminal_width.py +550 -0
  9. {multicmd-1.67 → multicmd-1.69}/LICENSE +0 -0
  10. {multicmd-1.67 → multicmd-1.69}/multiCMD.egg-info/dependency_links.txt +0 -0
  11. {multicmd-1.67 → multicmd-1.69}/multiCMD.egg-info/entry_points.txt +0 -0
  12. {multicmd-1.67 → multicmd-1.69}/multiCMD.egg-info/top_level.txt +0 -0
  13. {multicmd-1.67 → multicmd-1.69}/scripts/multiCMD +0 -0
  14. {multicmd-1.67 → multicmd-1.69}/setup.cfg +0 -0
  15. {multicmd-1.67 → multicmd-1.69}/setup.py +0 -0
  16. {multicmd-1.67 → multicmd-1.69}/tests/test_api.py +0 -0
  17. {multicmd-1.67 → multicmd-1.69}/tests/test_async_executor.py +0 -0
  18. {multicmd-1.67 → multicmd-1.69}/tests/test_cli.py +0 -0
  19. {multicmd-1.67 → multicmd-1.69}/tests/test_cli_closed_stdout.py +0 -0
  20. {multicmd-1.67 → multicmd-1.69}/tests/test_cli_failed_stdout.py +0 -0
  21. {multicmd-1.67 → multicmd-1.69}/tests/test_cli_input.py +0 -0
  22. {multicmd-1.67 → multicmd-1.69}/tests/test_cli_summary.py +0 -0
  23. {multicmd-1.67 → multicmd-1.69}/tests/test_display.py +0 -0
  24. {multicmd-1.67 → multicmd-1.69}/tests/test_embed.py +0 -0
  25. {multicmd-1.67 → multicmd-1.69}/tests/test_env.py +0 -0
  26. {multicmd-1.67 → multicmd-1.69}/tests/test_expand_ranges.py +0 -0
  27. {multicmd-1.67 → multicmd-1.69}/tests/test_handover.py +0 -0
  28. {multicmd-1.67 → multicmd-1.69}/tests/test_packaging.py +0 -0
  29. {multicmd-1.67 → multicmd-1.69}/tests/test_parsing.py +0 -0
  30. {multicmd-1.67 → multicmd-1.69}/tests/test_pass_fds.py +0 -0
  31. {multicmd-1.67 → multicmd-1.69}/tests/test_ping.py +0 -0
  32. {multicmd-1.67 → multicmd-1.69}/tests/test_pool.py +0 -0
  33. {multicmd-1.67 → multicmd-1.69}/tests/test_process_groups.py +0 -0
  34. {multicmd-1.67 → multicmd-1.69}/tests/test_pty.py +0 -0
  35. {multicmd-1.67 → multicmd-1.69}/tests/test_reader.py +0 -0
  36. {multicmd-1.67 → multicmd-1.69}/tests/test_reader_quit.py +0 -0
  37. {multicmd-1.67 → multicmd-1.69}/tests/test_regressions.py +0 -0
  38. {multicmd-1.67 → multicmd-1.69}/tests/test_run_command.py +0 -0
  39. {multicmd-1.67 → multicmd-1.69}/tests/test_run_commands.py +0 -0
  40. {multicmd-1.67 → multicmd-1.69}/tests/test_sudo.py +0 -0
  41. {multicmd-1.67 → multicmd-1.69}/tests/test_supervision.py +0 -0
  42. {multicmd-1.67 → multicmd-1.69}/tests/test_task.py +0 -0
  43. {multicmd-1.67 → multicmd-1.69}/tests/test_windows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.67
3
+ Version: 1.69
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -558,6 +558,42 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
558
558
 
559
559
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
560
560
 
561
+ ## Upgrading to 1.69 from 1.68
562
+
563
+ - Nothing needs doing. `mcmd` is unchanged.
564
+ - Changed, library: a `print_progress_bar()` frame with a total keeps a bar of at least 10 cells (from 12 columns up; the first
565
+ frame holds ` Calculating... ` or blanks in its place). Beside it the percent
566
+ gives way first, then the prefix from its end down to its first field, then the suffix from its start, then that first
567
+ field, a whole field at a time, so a number keeps its unit and its label (1.68 shrank the bar to two cells, then dropped
568
+ the percent and the prefix whole). At 80 columns hpcp's copy bar shows its count and its time left (1.68: no count).
569
+ - Fix, library: the first frame at or past the total ends its line, so the program's next output does not join a count
570
+ that stepped over its total (1.68 ended the line only at a frame equal to the total). A count that goes on past its
571
+ total draws its later frames on the next line, and the last stays open: the next output joins it.
572
+ - Fix, library: a control character in a frame's prefix or suffix (a tab, a newline, an escape: a file name can hold one)
573
+ is drawn as `?` (1.68: a newline started a row, so each frame scrolled, and a tab could wrap the frame). A prefix or
574
+ suffix coloured with escape codes shows them as text (`?[32m`).
575
+
576
+ ## Upgrading to 1.68 from 1.67
577
+
578
+ - Nothing needs doing.
579
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
580
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
581
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
582
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
583
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
584
+ was 20 columns by 0 rows).
585
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
586
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
587
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
588
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
589
+ than the width (1.67: the full width, and never cut).
590
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
591
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
592
+ more than 1.67's.
593
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
594
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
595
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
596
+
561
597
  ## Upgrading to 1.67 from 1.66
562
598
 
563
599
  - Nothing needs doing. `mcmd` is unchanged.
@@ -533,6 +533,42 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
533
533
 
534
534
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
535
535
 
536
+ ## Upgrading to 1.69 from 1.68
537
+
538
+ - Nothing needs doing. `mcmd` is unchanged.
539
+ - Changed, library: a `print_progress_bar()` frame with a total keeps a bar of at least 10 cells (from 12 columns up; the first
540
+ frame holds ` Calculating... ` or blanks in its place). Beside it the percent
541
+ gives way first, then the prefix from its end down to its first field, then the suffix from its start, then that first
542
+ field, a whole field at a time, so a number keeps its unit and its label (1.68 shrank the bar to two cells, then dropped
543
+ the percent and the prefix whole). At 80 columns hpcp's copy bar shows its count and its time left (1.68: no count).
544
+ - Fix, library: the first frame at or past the total ends its line, so the program's next output does not join a count
545
+ that stepped over its total (1.68 ended the line only at a frame equal to the total). A count that goes on past its
546
+ total draws its later frames on the next line, and the last stays open: the next output joins it.
547
+ - Fix, library: a control character in a frame's prefix or suffix (a tab, a newline, an escape: a file name can hold one)
548
+ is drawn as `?` (1.68: a newline started a row, so each frame scrolled, and a tab could wrap the frame). A prefix or
549
+ suffix coloured with escape codes shows them as text (`?[32m`).
550
+
551
+ ## Upgrading to 1.68 from 1.67
552
+
553
+ - Nothing needs doing.
554
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
555
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
556
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
557
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
558
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
559
+ was 20 columns by 0 rows).
560
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
561
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
562
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
563
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
564
+ than the width (1.67: the full width, and never cut).
565
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
566
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
567
+ more than 1.67's.
568
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
569
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
570
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
571
+
536
572
  ## Upgrading to 1.67 from 1.66
537
573
 
538
574
  - Nothing needs doing. `mcmd` is unchanged.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.67
3
+ Version: 1.69
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -558,6 +558,42 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
558
558
 
559
559
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
560
560
 
561
+ ## Upgrading to 1.69 from 1.68
562
+
563
+ - Nothing needs doing. `mcmd` is unchanged.
564
+ - Changed, library: a `print_progress_bar()` frame with a total keeps a bar of at least 10 cells (from 12 columns up; the first
565
+ frame holds ` Calculating... ` or blanks in its place). Beside it the percent
566
+ gives way first, then the prefix from its end down to its first field, then the suffix from its start, then that first
567
+ field, a whole field at a time, so a number keeps its unit and its label (1.68 shrank the bar to two cells, then dropped
568
+ the percent and the prefix whole). At 80 columns hpcp's copy bar shows its count and its time left (1.68: no count).
569
+ - Fix, library: the first frame at or past the total ends its line, so the program's next output does not join a count
570
+ that stepped over its total (1.68 ended the line only at a frame equal to the total). A count that goes on past its
571
+ total draws its later frames on the next line, and the last stays open: the next output joins it.
572
+ - Fix, library: a control character in a frame's prefix or suffix (a tab, a newline, an escape: a file name can hold one)
573
+ is drawn as `?` (1.68: a newline started a row, so each frame scrolled, and a tab could wrap the frame). A prefix or
574
+ suffix coloured with escape codes shows them as text (`?[32m`).
575
+
576
+ ## Upgrading to 1.68 from 1.67
577
+
578
+ - Nothing needs doing.
579
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
580
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
581
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
582
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
583
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
584
+ was 20 columns by 0 rows).
585
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
586
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
587
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
588
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
589
+ than the width (1.67: the full width, and never cut).
590
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
591
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
592
+ more than 1.67's.
593
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
594
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
595
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
596
+
561
597
  ## Upgrading to 1.67 from 1.66
562
598
 
563
599
  - Nothing needs doing. `mcmd` is unchanged.
@@ -37,4 +37,5 @@ tests/test_run_commands.py
37
37
  tests/test_sudo.py
38
38
  tests/test_supervision.py
39
39
  tests/test_task.py
40
+ tests/test_terminal_width.py
40
41
  tests/test_windows.py
@@ -29,9 +29,9 @@ import traceback
29
29
  from pprint import pformat
30
30
 
31
31
  #%% global vars
32
- version = '1.67'
32
+ version = '1.69'
33
33
  __version__ = version
34
- COMMIT_DATE = '2026-11-14'
34
+ COMMIT_DATE = '2026-11-20'
35
35
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
36
36
  # lock for it: each update is one set operation and each snapshot one set.copy(), as for _live_procs below
37
37
  __running_threads = set()
@@ -3347,9 +3347,17 @@ def input_with_timeout_and_countdown(timeout, prompt='Please enter your selectio
3347
3347
  if ended:
3348
3348
  time.sleep(max(deadline - (seconds - 1) - time.monotonic(), 0))
3349
3349
 
3350
+ def _char_width(ch):
3351
+ '''The terminal columns a character takes ( internal ): an East Asian wide character two, a combining mark none'''
3352
+ if ch < "\u0300": # ASCII and Latin-1
3353
+ return 1
3354
+ import unicodedata
3355
+ if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Cf") or "\u1160" <= ch <= "\u11ff":
3356
+ return 0
3357
+ return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
3358
+
3350
3359
  def pretty_format_table(data, delimiter=None, header=None, full=False, remove_empty_columns=False):
3351
3360
  import re
3352
- import unicodedata
3353
3361
  version = 1.21
3354
3362
  _ = version
3355
3363
  if not data:
@@ -3383,12 +3391,7 @@ def pretty_format_table(data, delimiter=None, header=None, full=False, remove_em
3383
3391
  # Widths count terminal columns: an East Asian wide character takes two,
3384
3392
  # a combining mark and an ANSI color code none.
3385
3393
  ansi = re.compile(r"(\x1b\[[0-?]*[ -/]*[@-~])")
3386
- def char_width(ch):
3387
- if ch < "\u0300": # ASCII and Latin-1
3388
- return 1
3389
- if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Cf") or "\u1160" <= ch <= "\u11ff":
3390
- return 0
3391
- return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
3394
+ char_width = _char_width
3392
3395
  def visible_len(s):
3393
3396
  if "\x1b" in s:
3394
3397
  s = ansi.sub("", s)
@@ -3533,7 +3536,11 @@ def slugify(value, allow_unicode=False):
3533
3536
 
3534
3537
  def get_terminal_size():
3535
3538
  '''
3536
- Get the terminal size
3539
+ Get the terminal size: stdout's terminal, else stdin's (cmd | less), else COLUMNS / LINES, else 240x50 (no terminal).
3540
+
3541
+ A terminal that reports 0 columns or rows does not know its size (a pty nobody set one on: script
3542
+ without a terminal of its own, some CI runners). What it does not know comes from
3543
+ COLUMNS / LINES, else 80x24, what other programs take such a terminal for.
3537
3544
 
3538
3545
  @params:
3539
3546
  None
@@ -3541,9 +3548,11 @@ def get_terminal_size():
3541
3548
  @returns:
3542
3549
  (int,int): the number of columns and rows of the terminal
3543
3550
  '''
3551
+ # ( shutil.get_terminal_size is not enough: before Python 3.11 it returns a terminal's zeros, it does not read stdin's size,
3552
+ # and COLUMNS overrides a real size )
3553
+ answered = True # a terminal answered, maybe with zeros: it is taken for a screen of 80x24 ( so is the log that script writes )
3544
3554
  try:
3545
- import os
3546
- _tsize = os.get_terminal_size()
3555
+ columns, rows = os.get_terminal_size()
3547
3556
  except Exception:
3548
3557
  try:
3549
3558
  import fcntl
@@ -3551,19 +3560,109 @@ def get_terminal_size():
3551
3560
  import termios
3552
3561
  packed = fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))
3553
3562
  rows, columns = struct.unpack('HHHH', packed)[:2]
3554
- _tsize = (columns, rows)
3555
3563
  except Exception:
3556
- import shutil
3557
- _tsize = shutil.get_terminal_size(fallback=(240, 50))
3558
- return _tsize
3564
+ columns = rows = 0
3565
+ answered = False
3566
+ def from_environment(name, fallback):
3567
+ try:
3568
+ value = int(os.environ.get(name, ''))
3569
+ except ValueError:
3570
+ return fallback
3571
+ return value if value > 0 else fallback
3572
+ # 80x24 is what terminfo, curses, ls and shutil take a terminal for when it does not say, so a line that fits never wraps on
3573
+ # its screen; no terminal at all is a log or a pipe, where a wide line costs nothing
3574
+ if columns <= 0:
3575
+ columns = from_environment('COLUMNS', 80 if answered else 240)
3576
+ if rows <= 0:
3577
+ rows = from_environment('LINES', 24 if answered else 50)
3578
+ return os.terminal_size((columns, rows))
3559
3579
 
3560
3580
  # the bar's blocks, and what a stdout whose encoding has no such characters gets for them ( see _writable )
3561
3581
  _BAR_BLOCKS = '▁▂▃▄▅▆▇█'
3562
3582
  _ASCII_BAR = str.maketrans(_BAR_BLOCKS, '.:-=+*%#')
3563
3583
 
3584
+ def _cells(text):
3585
+ '''The terminal columns text takes ( internal ): a wide character two, a combining mark none'''
3586
+ # ASCII and Latin-1, the usual text, is a column a character ( as pretty_format_table's visible_len ): a frame is measured twice
3587
+ # a time it is drawn, twice a second
3588
+ if not text or max(text) < "\u0300":
3589
+ return len(text)
3590
+ return sum(map(_char_width, text))
3591
+
3592
+ def _cuts_at(text, i):
3593
+ '''
3594
+ Whether text can be cut at its index i ( internal ): at a blank that follows neither a digit nor a colon. A blank after a digit
3595
+ may sit between a number and its unit ( format_bytes writes '1.23 K' ), one after a colon between a label and its number
3596
+ '''
3597
+ return text[i] == ' ' and not (i and (text[i - 1].isdigit() or text[i - 1] == ':'))
3598
+
3599
+ def _fit(text, width, from_start=False, whole=False):
3600
+ '''
3601
+ text cut to width terminal columns ( internal ): its end, back to the last blank it can be cut at ( _cuts_at ), so a number
3602
+ keeps its label and its unit, else at the column ( with whole, not at all: '' ); from_start, its start, at the column
3603
+ '''
3604
+ used = 0
3605
+ for i in (range(len(text) - 1, -1, -1) if from_start else range(len(text))):
3606
+ used += _char_width(text[i])
3607
+ if used > width:
3608
+ if from_start:
3609
+ return text[i + 1:]
3610
+ blank = i
3611
+ while blank > 0 and not _cuts_at(text, blank):
3612
+ blank -= 1
3613
+ return text[:blank] if blank > 0 else '' if whole else text[:i]
3614
+ return text
3615
+
3616
+ # The least bar of a frame with a total, in cells, whatever the total, so it reads at a glance. Its text gives way before the bar
3617
+ # shrinks below it ( 1.68 shrank the bar first, down to two cells, then dropped the percent and the prefix whole: hpcp's copy
3618
+ # bar at 80 columns showed no count )
3619
+ _LEAST_BAR = 10
3620
+
3621
+ # the control characters ( C0, DEL, C1 ), each a '?' in a frame's text: a newline starts a row, a tab jumps to a tab stop, an
3622
+ # escape starts a sequence the terminal acts on, so the frame cannot be measured ( a file name may hold any of them )
3623
+ _CONTROLS = dict.fromkeys(list(range(0x20)) + list(range(0x7f, 0xa0)), '?')
3624
+
3625
+ def _cut_prefix(prefix, width):
3626
+ '''
3627
+ A frame's prefix in width terminal columns ( internal ): whole, or its start, cut after a whole field ( _fit ) and joined
3628
+ to the bar by ' |' again; '' where not even its first field fits
3629
+ '''
3630
+ if _cells(prefix) <= width:
3631
+ return prefix
3632
+ kept = _fit(prefix, width - 2, whole=True).rstrip(' |')
3633
+ return kept + ' |' if kept else ''
3634
+
3635
+ def _first_field(prefix):
3636
+ '''A frame's prefix cut after its first field ( internal; see _cut_prefix ), or '' if it holds only the joint to the bar'''
3637
+ for i in range(1, len(prefix) + 1):
3638
+ if i == len(prefix) or _cuts_at(prefix, i):
3639
+ kept = prefix[:i].rstrip(' |')
3640
+ if kept:
3641
+ return kept + ' |'
3642
+ return ''
3643
+
3644
+ def _cut_suffix(suffix, width):
3645
+ '''
3646
+ A frame's suffix in width terminal columns ( internal ): whole, or its end, joined to the bar by '| ' again, from a blank it
3647
+ can be cut at ( _cuts_at ) before a number, a label ( a word that ends in a colon ) or a '|': a word after a number's unit
3648
+ ( '1.23 M Files', '5.00 KF/s Limit' ) never starts it without its number. '' where not even its last such part fits
3649
+ '''
3650
+ if _cells(suffix) <= width:
3651
+ return suffix
3652
+ # the first character of the end that fits beside the '| '
3653
+ start = len(suffix) - len(_fit(suffix, width - 2, from_start=True))
3654
+ for i in range(max(start - 1, 0), len(suffix)):
3655
+ if _cuts_at(suffix, i):
3656
+ word = suffix[i + 1:].lstrip(' ').split(' ', 1)[0]
3657
+ if word[:1].isdigit() or word[:1] == '|' or word.endswith(':'):
3658
+ kept = suffix[i + 1:].lstrip('| ')
3659
+ return '| ' + kept if kept else ''
3660
+ return ''
3661
+
3564
3662
  def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3565
3663
  '''
3566
- Generate a progress bar string
3664
+ Generate a progress bar string: one line, within one column less than columns ( a line that reaches the last column
3665
+ wraps on some terminals, and a frame that wraps scrolls a row each time it is drawn ), counted in terminal columns
3567
3666
 
3568
3667
  @params:
3569
3668
  iteration - Required : current iteration (Int)
@@ -3575,50 +3674,49 @@ def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3575
3674
  @returns:
3576
3675
  str: the progress bar string
3577
3676
  '''
3578
- noPrefix = False
3579
- noSuffix = False
3580
- noPercent = False
3581
- noBar = False
3582
- # if total is 0, we don't want to divide by 0
3677
+ # a control character would break the frame over rows or columns it cannot count: it is drawn as a '?'
3678
+ prefix, suffix = prefix.translate(_CONTROLS), suffix.translate(_CONTROLS)
3679
+ width = columns - 1
3680
+ # if total is 0, we don't want to divide by 0: the iteration, padded to clear the last frame. What does not fit gives way
3681
+ # from the prefix's start ( hpcp's is the end of a path ), then from the end
3583
3682
  if total == 0:
3584
- return f'{prefix} iteration:{iteration} {suffix}'.ljust(columns)
3683
+ rest = f' iteration:{iteration} {suffix}'
3684
+ line = _fit(_fit(prefix, width - _cells(rest), from_start=True) + rest, width)
3685
+ return line + ' ' * (width - _cells(line))
3585
3686
  percent = f'|{("{0:.1f}").format(100 * (iteration / float(total)))}% '
3586
- length = columns - len(prefix) - len(suffix) - len(percent) - 3
3587
- if length <= 0:
3588
- length = columns - len(prefix) - len(suffix) - 3
3589
- noPercent = True
3590
- if length <= 0:
3591
- length = columns - len(suffix) - 3
3592
- noPrefix = True
3593
- if length <= 0:
3594
- length = columns - 3
3595
- noSuffix = True
3687
+ # a bar is length + 1 wide, full or not ( see below ), so a frame is at most columns - 2 wide. Beside a bar of _LEAST_BAR
3688
+ # cells, what does not fit gives way from the bar outward: the percent, the prefix from its end down to its first field, the
3689
+ # suffix from its start, then that first field, each a whole field at a time. The line keeps what it starts and ends with
3690
+ # longest: hpcp's count, and its time left
3691
+ room = columns - 2 - _LEAST_BAR
3692
+ prefix_cells, suffix_cells = _cells(prefix), _cells(suffix)
3693
+ if prefix_cells + suffix_cells + len(percent) > room:
3694
+ percent = ''
3695
+ if prefix_cells + suffix_cells > room:
3696
+ prefix = _cut_prefix(prefix, room - suffix_cells) or _first_field(prefix)
3697
+ if _cells(prefix) > room:
3698
+ prefix = ''
3699
+ suffix = _cut_suffix(suffix, room - _cells(prefix))
3700
+ length = columns - _cells(prefix) - _cells(suffix) - len(percent) - 3
3596
3701
  if length <= 0:
3597
- return f'{prefix}\niteration:\n {iteration}\ntotal:\n {total}\n| {suffix}\n'
3598
- if iteration == 0:
3599
- noBar = True
3702
+ # 3 columns or fewer: no room for a bar
3703
+ return ''
3600
3704
  filled_length = int(length * iteration // total)
3601
3705
  progress_chars = _BAR_BLOCKS
3602
3706
  fractional_progress = (length * iteration / total) - filled_length
3603
3707
  char_index = int(fractional_progress * (len(progress_chars) - 1))
3604
3708
  bar_char = progress_chars[char_index]
3605
- if filled_length == length:
3606
- bar = progress_chars[-1] * length
3709
+ # past the total too ( a total that was an estimate ): a full bar, not a longer one, and as wide as the bars before it: the
3710
+ # frame is drawn over the one before it, and what it does not cover stays on the screen ( '| 00:00:001' for '| 00:00:00' )
3711
+ if filled_length >= length:
3712
+ bar = progress_chars[-1] * (length + 1)
3607
3713
  else:
3608
3714
  bar = progress_chars[-1] * filled_length + bar_char + '_' * (length - filled_length)
3609
- lineOut = ''
3610
- if not noPrefix:
3611
- lineOut += prefix
3612
- if not noBar:
3613
- lineOut += f'{bar}'
3614
- if not noPercent:
3615
- lineOut += percent
3616
- else:
3617
- if length >= 16:
3618
- lineOut += ' Calculating... '
3619
- if not noSuffix:
3620
- lineOut += suffix
3621
- return lineOut
3715
+ if iteration == 0:
3716
+ # the place of the bar ( length + 1 cells ): ' Calculating... ' when it fits, else blanks, so the first frame is cut as a frame
3717
+ # under 10% is ( a percent as wide as its own ), and the prefix's joint and the suffix's never stand side by side ( '||' )
3718
+ return prefix + (' Calculating... ' if length + 1 >= 16 else ' ' * (length + 1)) + suffix
3719
+ return prefix + bar + percent + suffix
3622
3720
 
3623
3721
  def _writable(text, stream):
3624
3722
  '''
@@ -3642,6 +3740,9 @@ def _writable(text, stream):
3642
3740
  text = text.translate(_ASCII_BAR)
3643
3741
  return text.encode(encoding, 'replace').decode(encoding)
3644
3742
 
3743
+ # the total of the bar whose last frame was at or past it, else None ( see print_progress_bar )
3744
+ _bar_done = [None]
3745
+
3645
3746
  def print_progress_bar(iteration, total, prefix='', suffix=''):
3646
3747
  '''
3647
3748
  Call in a loop to create terminal progress bar
@@ -3661,9 +3762,18 @@ def print_progress_bar(iteration, total, prefix='', suffix=''):
3661
3762
  # the lock held ( docs/limitations.md ) would hang every later frame; it never took the lock before.
3662
3763
  try:
3663
3764
  columns, _ = get_terminal_size()
3765
+ # measured as stdout will write them: a stdout whose errors handler raises ( the default ) writes a character it cannot
3766
+ # write as one '?', whatever its width ( a combining mark takes none, a wide character two ), and a frame measured before
3767
+ # that wraps or leaves the one before it showing
3768
+ prefix, suffix = _writable(prefix, sys.stdout), _writable(suffix, sys.stdout)
3664
3769
  _display._write(_writable(f'\r{_genrate_progress_bar(iteration, total, prefix, suffix, columns)}', sys.stdout))
3665
- if iteration == total and total > 0:
3770
+ # the frame at the total ends its line, each time, and so does the first one past it ( a total that was an estimate, a
3771
+ # count that steps over it ), so the program's next output starts a line of its own. A later frame past the total is
3772
+ # drawn on the line after it, and left open: ending each would scroll a line per frame
3773
+ done = total > 0 and iteration >= total
3774
+ if done and (iteration == total or _bar_done[0] != total):
3666
3775
  _display._write('\n')
3776
+ _bar_done[0] = total if done else None
3667
3777
  except Exception:
3668
3778
  if iteration % 5 == 0:
3669
3779
  _display._write(_writable(_genrate_progress_bar(iteration, total, prefix, suffix), sys.stdout) + '\n')
@@ -194,7 +194,7 @@ def test_progress_bar_on_a_stdout_that_cannot_write_its_blocks(monkeypatch):
194
194
  out.flush()
195
195
  assert out.buffer.getvalue().decode('ascii') == (
196
196
  "\rProgress: |" + "#" * 24 + "=" + "_" * 25 + "|50.0% | Complete"
197
- "\rProgress: |" + "#" * 48 + "|100.0% | Complete\n"
197
+ "\rProgress: |" + "#" * 49 + "|100.0% | Complete\n"
198
198
  )
199
199
 
200
200
 
@@ -203,7 +203,22 @@ def test_progress_bar_with_a_name_its_stdout_cannot_write(monkeypatch):
203
203
  out = ascii_stdout(monkeypatch, 'utf-8', 'strict')
204
204
  print_progress_bar(3, 0, prefix='dir/caf\udce9', suffix='s')
205
205
  out.flush()
206
- assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(80)
206
+ assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(79)
207
+
208
+
209
+ def test_progress_bar_is_measured_as_its_stdout_writes_it(monkeypatch):
210
+ # an ASCII stdout ( Python 3.6 in a C locale ) writes a combining mark, which takes no column, as a '?' that takes one, and a wide
211
+ # character, which takes two, as one: a frame measured before that wrapped ( 80 columns and more ) or came out short, leaving the
212
+ # end of the frame before it showing
213
+ out = ascii_stdout(monkeypatch, 'ascii', 'strict')
214
+ print_progress_bar(7, 0, prefix='e\u0301' * 60, suffix='s')
215
+ print_progress_bar(7, 0, prefix='\u4e2d' * 30, suffix='s')
216
+ print_progress_bar(5, 10, prefix='e\u0301' * 12, suffix='\u4e2d' * 3)
217
+ print_progress_bar(5, 10, prefix='dir', suffix='s')
218
+ out.flush()
219
+ frames = out.buffer.getvalue().decode('ascii').split('\r')[1:]
220
+ assert [len(frame) for frame in frames] == [79, 79, 78, 78]
221
+ assert frames[0].endswith('e? | iteration:7 | s') and frames[2].startswith('e?' * 12 + ' |') and frames[2].endswith('|50.0% | ???')
207
222
 
208
223
 
209
224
  def test_progress_bar_in_a_c_locale_python():
@@ -234,14 +249,14 @@ def test_get_terminal_size_reads_columns_from_stdin_when_stdout_is_piped():
234
249
  try:
235
250
  fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 200, 0, 0))
236
251
  out = subprocess.run(
237
- [sys.executable, "-c", "import multiCMD; print(*multiCMD.get_terminal_size()[:2])"],
252
+ [sys.executable, "-c", "import os, multiCMD; size = multiCMD.get_terminal_size(); print(*size[:2], isinstance(size, os.terminal_size))"],
238
253
  stdin=slave, stdout=subprocess.PIPE, cwd=str(Path(__file__).resolve().parents[1]),
239
254
  universal_newlines=True, check=True,
240
255
  ).stdout
241
256
  finally:
242
257
  os.close(slave)
243
258
  os.close(master)
244
- assert out.split() == ["200", "40"]
259
+ assert out.split() == ["200", "40", "True"]
245
260
 
246
261
 
247
262
  @pytest.fixture
@@ -603,13 +603,28 @@ def handler(signum, frame):
603
603
  armed[0] = False
604
604
  raise KeyboardInterrupt
605
605
  signal.signal(signal.SIGALRM, handler)
606
+ def reap_strays():
607
+ # a stop that lands as Popen's fork returns leaves a child that no Popen knows ( docs/limitations.md, "A Ctrl-C inside
608
+ # Popen during a serial start ..." ), a zombie until the probe exits: in 5,000 stops one run reaped 770 ( 3.6 ), 782 ( 3.9 ),
609
+ # 1,821 ( 3.11 ), 1,822 ( 3.12 ) and 2,032 ( 3.14 ), so on 3.11 and later a process limit of 1,024 ( Docker's default ) runs
610
+ # out, and the next start fails with EAGAIN. The test asserts that some were reaped: a probe that reaps none passes wherever
611
+ # the process limit is above its strays
612
+ count = 0
613
+ while True:
614
+ try:
615
+ pid, _ = os.waitpid(-1, os.WNOHANG)
616
+ except ChildProcessError:
617
+ return count
618
+ if not pid:
619
+ return count
620
+ count += 1
606
621
  times = []
607
622
  for _ in range(50):
608
623
  start = time.perf_counter()
609
624
  multiCMD.run_command(['true'], quiet=True)
610
625
  times.append(time.perf_counter() - start)
611
626
  window = sorted(times)[len(times) // 2] * 1.5
612
- stops = others = 0
627
+ stops = others = strays = 0
613
628
  for i in range(n):
614
629
  try:
615
630
  try:
@@ -630,12 +645,13 @@ for i in range(n):
630
645
  print('LEAK: threading._active_limbo_lock held after %d calls' % (i + 1), flush=True)
631
646
  os._exit(2)
632
647
  threading._active_limbo_lock.release()
648
+ strays += reap_strays()
633
649
  done[0] = i + 1
634
650
  assert multiCMD.run_command(['true'], quiet=True, return_code_only=True) == 0
635
651
  # ( Python 3.6 - 3.8 block-buffer a redirected stderr, where the stops that landed in a finalizer are told: a result line
636
652
  # printed while a flush at 8 KB had left half a line there would land on the end of it, so the line is told after a flush )
637
653
  sys.stderr.flush()
638
- print('%d calls, %d stopped, %d other errors' % (n, stops, others), flush=True)
654
+ print('%d calls, %d stopped, %d other errors, %d strays reaped' % (n, stops, others, strays), flush=True)
639
655
  '''
640
656
 
641
657
 
@@ -646,13 +662,15 @@ def test_stops_in_serial_commands_never_jam_thread_starts(tmp_path):
646
662
  # left threading's _active_limbo_lock held, and every later thread start hung: up to 1.59 on 3.14 this probe hung in 6 of
647
663
  # 6 runs of 20,000 calls, after 30 to 9,000 calls ( three runs by the plan, three by the build ). 3.6 never hung so in
648
664
  # 60,000 calls. 5,000 calls take about 75 s on 3.6 ( a call and the sleep after it ): 600 s leaves eight times that
649
- # under -n auto
665
+ # under -n auto. The probe reaps the zombies such stops leave ( 1.69: 1.68's probe failed under a process limit of 1,024 )
650
666
  probe = tmp_path / 'probe.py'
651
667
  probe.write_text(STOP_PROBE)
652
668
  run = subprocess.run([sys.executable, '-I', str(probe), str(PACKAGE_ROOT), '5000'], stdout=subprocess.PIPE,
653
669
  stderr=subprocess.STDOUT, universal_newlines=True, timeout=600)
654
670
  # ( the probe flushes stderr before its result line: see there )
655
- assert run.returncode == 0 and re.search(r'^5000 calls, \d+ stopped, 0 other errors$', run.stdout, re.M), run.stdout[-4000:]
671
+ result = re.search(r'^5000 calls, \d+ stopped, 0 other errors, (\d+) strays reaped$', run.stdout, re.M)
672
+ # ( 770 to 2,032 were reaped in 5,000 stops on the five Pythons: a probe that reaps none has lost its reaper )
673
+ assert run.returncode == 0 and result and int(result.group(1)) > 0, run.stdout[-4000:]
656
674
 
657
675
 
658
676
  def _dummy_threads():
@@ -0,0 +1,550 @@
1
+ '''A progress line fits its terminal (1.68): a terminal of no size counts as unknown, and a frame is cut to one column less
2
+ than the width, in terminal columns. A bar with a total keeps 10 cells, and its text gives way a field at a time; a bar past
3
+ its total ends its line; a control character in a frame's text is a '?' (1.69).'''
4
+ import os
5
+ import re
6
+ import select
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ import unicodedata
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+
15
+ import multiCMD
16
+ from multiCMD import _genrate_progress_bar, get_terminal_size, print_progress_bar
17
+
18
+ ROOT = str(Path(__file__).resolve().parents[1])
19
+ posix_only = pytest.mark.skipif(os.name != 'posix', reason='needs a pseudo-terminal')
20
+
21
+ # hpcp's removal and listing lines ( hpcp 9.95: prefix=path[-50:], the suffix after it, its numbers from format_bytes(), which
22
+ # writes a blank between a number and its unit: '1.23 K', '1.15 Gi', and '45.00 ' with none )
23
+ PATH = '/srv/data/projects/2026/run-0042/outputs/checkpoints/step-001200/model.safetensors'
24
+
25
+
26
+ def fb(count):
27
+ return multiCMD.format_bytes(count, use_1024_bytes=False, to_str=True)
28
+
29
+
30
+ REMOVAL = f'Removed: {fb(1230)} Folders: {fb(45)} | Overall: {fb(1230000)} Files'
31
+ LISTING = f'Files: {fb(1230)} Links: {fb(12)} Folders: {fb(45)} Size: {multiCMD.format_bytes(1.15 * 2 ** 30)}B | Overall: {fb(1230000)} Files'
32
+ WIDE_PATH = '/数据/项目/二〇二六/运行记录/输出结果/检查点/第一千二百步/模型权重文件.safetensors'
33
+ # hpcp 9.96's copy bar ( Adaptive_Progress_Bar.print_progress, read, not imported ), with this module's format_bytes: its count,
34
+ # size and jobs, then its rates, the last jobs' rates and the time left; with a rate limit set, the limits in the jobs' place
35
+ COPY_PREFIX = f'{fb(123456)}F ({multiCMD.format_bytes(45.6 * 2 ** 30)}B) Copied | 16 Scheduled {4.0:0>3.1f} F/Job '
36
+ COPY = (f'{multiCMD.format_bytes(1.23 * 2 ** 30)}B/s {fb(2345.6)}F/s | {2.5:.1f}s: {multiCMD.format_bytes(1.1 * 2 ** 30)}B/s '
37
+ f'{fb(2100)}F/s | 1h2m3s')
38
+ COPY_LIMITED = (f'{multiCMD.format_bytes(1.23 * 2 ** 30)}B/s {fb(2345.6)}F/s | {multiCMD.format_bytes(2 ** 30)}B/s Limit | '
39
+ f'{fb(5000)}F/s Limit | 1h2m3s')
40
+
41
+
42
+ def cells(text):
43
+ '''The terminal columns text takes, by the test's own count: a wide character two, a combining mark none.'''
44
+ return sum(0 if unicodedata.combining(ch) else 2 if unicodedata.east_asian_width(ch) in ('W', 'F') else 1 for ch in text)
45
+
46
+
47
+ def frames(text):
48
+ '''The frames in what print_progress_bar wrote: each starts with a carriage return.'''
49
+ return [frame for frame in re.split(r'[\r\n]', text) if frame]
50
+
51
+
52
+ def env_without_a_size():
53
+ env = dict(os.environ)
54
+ env.pop('COLUMNS', None)
55
+ env.pop('LINES', None)
56
+ return env
57
+
58
+
59
+ def at_a_pty(code, rows, columns):
60
+ '''What a child Python running code writes to a pty of rows x columns (its stdin and stdout), up to the "END" it writes last,
61
+ with the pty's \\r\\n made \\n.'''
62
+ import fcntl
63
+ import pty
64
+ import struct
65
+ import termios
66
+ master, slave = pty.openpty()
67
+ try:
68
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, columns, 0, 0))
69
+ child = subprocess.Popen([sys.executable, '-c', code + '\nimport sys; sys.stdout.write("END"); sys.stdout.flush()'],
70
+ stdin=slave, stdout=slave, stderr=subprocess.PIPE, cwd=ROOT, env=env_without_a_size())
71
+ finally:
72
+ os.close(slave)
73
+ output = b''
74
+ deadline = time.monotonic() + 60
75
+ try:
76
+ while not output.endswith(b'END') and time.monotonic() < deadline:
77
+ if not select.select([master], [], [], 1)[0]:
78
+ continue
79
+ try:
80
+ chunk = os.read(master, 65536)
81
+ except OSError: # Linux: EIO, the child has closed its side
82
+ break
83
+ if not chunk:
84
+ break
85
+ output += chunk
86
+ _, err = child.communicate(timeout=60)
87
+ finally:
88
+ os.close(master)
89
+ assert child.returncode == 0 and err == b'', err
90
+ assert output.endswith(b'END'), output
91
+ return output[:-3].decode('utf-8', 'replace').replace('\r\n', '\n')
92
+
93
+
94
+ def test_the_test_strings_are_what_format_bytes_writes():
95
+ # REMOVAL and LISTING are the suffixes of hpcp 9.95's removal line ( _RemoveProgress.show ) and its listing line, with this
96
+ # module's own format_bytes: hpcp's code is not read. A number and its unit are two words ( the first 1.68 build tested
97
+ # '1.23K' and cut 'Size: 123.45 GiB' after its number )
98
+ assert REMOVAL == 'Removed: 1.23 K Folders: 45.00 | Overall: 1.23 M Files'
99
+ assert LISTING == 'Files: 1.23 K Links: 12.00 Folders: 45.00 Size: 1.15 GiB | Overall: 1.23 M Files'
100
+ # and hpcp 9.96's copy bar ( the 1.69 tests )
101
+ assert COPY_PREFIX == '123.46 KF (45.60 GiB) Copied | 16 Scheduled 4.0 F/Job '
102
+ assert COPY == '1.23 GiB/s 2.35 KF/s | 2.5s: 1.10 GiB/s 2.10 KF/s | 1h2m3s'
103
+ assert COPY_LIMITED == '1.23 GiB/s 2.35 KF/s | 1.00 GiB/s Limit | 5.00 KF/s Limit | 1h2m3s'
104
+
105
+
106
+ @pytest.mark.parametrize('reported, environ, expected', [
107
+ # a terminal that does not say: 80x24, what other programs take it for, so a line that fits never wraps on its screen
108
+ ((0, 0), {}, (80, 24)),
109
+ ((0, 0), {'COLUMNS': '100', 'LINES': '40'}, (100, 40)),
110
+ ((0, 40), {}, (80, 40)),
111
+ ((200, 0), {}, (200, 24)),
112
+ ((200, 0), {'LINES': '30'}, (200, 30)),
113
+ ((0, 0), {'COLUMNS': '0', 'LINES': '-3'}, (80, 24)),
114
+ ((0, 0), {'COLUMNS': 'wide', 'LINES': ''}, (80, 24)),
115
+ # a size the terminal knows wins, as before
116
+ ((200, 40), {'COLUMNS': '100', 'LINES': '10'}, (200, 40)),
117
+ ])
118
+ def test_get_terminal_size_takes_a_reported_zero_as_unknown(monkeypatch, reported, environ, expected):
119
+ # a pty nobody set a size on (script without a terminal, a serial console, some CI runners) reports 0x0; 1.67 returned it
120
+ monkeypatch.setattr(os, 'get_terminal_size', lambda *args: os.terminal_size(reported))
121
+ monkeypatch.delenv('COLUMNS', raising=False)
122
+ monkeypatch.delenv('LINES', raising=False)
123
+ for name, value in environ.items():
124
+ monkeypatch.setenv(name, value)
125
+ size = get_terminal_size()
126
+ assert isinstance(size, os.terminal_size) and tuple(size) == expected
127
+
128
+
129
+ @pytest.mark.parametrize('environ, expected', [
130
+ ({}, ['240', '50']),
131
+ ({'COLUMNS': '100', 'LINES': '30'}, ['100', '30']),
132
+ ])
133
+ def test_get_terminal_size_without_a_terminal_is_240x50_or_what_the_environment_says(environ, expected):
134
+ # no terminal at all is a pipe or a log: nothing wraps, so the wide fallback stays ( a terminal that answered 0 is 80x24 )
135
+ code = 'import sys, multiCMD; sys.stderr.write(" ".join(map(str, multiCMD.get_terminal_size()[:2])))'
136
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
137
+ cwd=ROOT, env=dict(env_without_a_size(), **environ), universal_newlines=True, timeout=60)
138
+ assert result.stderr.split() == expected
139
+
140
+
141
+ @posix_only
142
+ @pytest.mark.parametrize('stdout_is_the_pty, size, expected', [
143
+ (True, (0, 0), ['80', '24']),
144
+ # stdout a pipe ( cmd | less ): stdin's terminal answers, with zeros too, so it is a terminal of no size and not no terminal ( 240x50 )
145
+ (False, (0, 0), ['80', '24']),
146
+ (False, (30, 100), ['100', '30']),
147
+ ], ids=['stdout', 'stdin', 'stdin-sized'])
148
+ def test_get_terminal_size_of_a_pty(stdout_is_the_pty, size, expected):
149
+ import fcntl
150
+ import pty
151
+ import struct
152
+ import termios
153
+ master, slave = pty.openpty()
154
+ code = 'import sys, multiCMD; sys.stderr.write(" ".join(map(str, multiCMD.get_terminal_size()[:2])))'
155
+ try:
156
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', size[0], size[1], 0, 0))
157
+ result = subprocess.run([sys.executable, '-c', code], stdin=slave, stdout=slave if stdout_is_the_pty else subprocess.PIPE,
158
+ stderr=subprocess.PIPE, cwd=ROOT, env=env_without_a_size(), universal_newlines=True, timeout=60)
159
+ finally:
160
+ os.close(slave)
161
+ os.close(master)
162
+ assert result.stderr.split() == expected
163
+
164
+
165
+ @posix_only
166
+ def test_a_pty_command_gets_a_window_of_80x24_less_the_prefix_at_a_terminal_of_no_size():
167
+ # 1.67 gave the command a window of 20 columns by 0 rows ( the terminal's zeros ), a pager or a table in it no room
168
+ code = ('import fcntl, struct, termios, multiCMD\n'
169
+ 'master, slave = multiCMD._open_pty(4)\n'
170
+ 'rows, columns = struct.unpack("HHHH", fcntl.ioctl(slave, termios.TIOCGWINSZ, b"\\0" * 8))[:2]\n'
171
+ 'print(rows, columns)')
172
+ assert at_a_pty(code, 0, 0).split() == ['24', '76']
173
+
174
+
175
+ @posix_only
176
+ def test_a_table_gets_80_columns_at_a_terminal_of_no_size():
177
+ # 1.67 cut every column to its heading's width ( 'a |xxx..', 10 columns a row ): the zero was the width
178
+ code = ('import sys, multiCMD\n'
179
+ 'sys.stdout.write(multiCMD.pretty_format_table([["name", "value"], ["a", "x" * 100], ["b", "y" * 30]]))')
180
+ lines = at_a_pty(code, 0, 0).split('\n')
181
+ assert [len(line) for line in lines[:4]] == [80] * 4 and lines[2].startswith('a |xxx') and lines[2].endswith('xxx..'), lines
182
+ assert lines[3] == 'b |' + 'y' * 30 + ' ' * 45, lines
183
+
184
+
185
+ @posix_only
186
+ def test_a_bar_of_a_known_total_stays_on_one_line_at_a_terminal_of_no_size():
187
+ # 1.67 took the 0 columns for a width, and each frame came out over six lines
188
+ shown = at_a_pty('import multiCMD\nfor i in range(11): multiCMD.print_progress_bar(i, 10, "p", "s")', 0, 0)
189
+ assert shown.count('\n') == 1 and shown.endswith('\n'), shown
190
+ assert len(frames(shown)) == 11 and all(cells(frame) <= 79 for frame in frames(shown)), shown
191
+ assert frames(shown)[5].startswith('p |') and frames(shown)[5].endswith('|50.0% | s'), shown
192
+
193
+
194
+ @posix_only
195
+ def test_a_short_line_stays_on_one_row_at_a_terminal_of_no_size():
196
+ # a serial console or `qm terminal` gives 0x0 until someone runs resize ( known from the platform, not tested ), with a real
197
+ # 80-column screen behind it: the first 1.68 build padded every frame to 239 columns, three rows that scrolled twice a
198
+ # second ( 1.67 wrote 58 and did not pad )
199
+ shown = at_a_pty('import multiCMD\nfor i in range(3): multiCMD.print_progress_bar(i, 0, "/scratch/old-runs/job-1234", "Removed: 1.23 K")', 0, 0)
200
+ assert '\n' not in shown and len(frames(shown)) == 3, shown
201
+ assert [len(frame) for frame in frames(shown)] == [79] * 3 and frames(shown)[2].rstrip() == (
202
+ '/scratch/old-runs/job-1234 | iteration:2 | Removed: 1.23 K'), shown
203
+
204
+
205
+ @posix_only
206
+ def test_a_long_prefix_does_not_wrap_at_80_columns():
207
+ # hpcp's removal and listing lines pass 80 columns with a path of 50 ( this test's: 122 and 149 ): 1.67 wrapped them, and
208
+ # each frame scrolled a row. %a, not %r: the child's code stays ASCII, so it starts under a C locale ( Python 3.6 ) too
209
+ code = ('import multiCMD\n'
210
+ 'for i in range(3):\n'
211
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
212
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
213
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
214
+ % (PATH[-50:], REMOVAL, PATH[-50:], LISTING, WIDE_PATH[-50:], REMOVAL))
215
+ shown = at_a_pty(code, 24, 80)
216
+ assert '\n' not in shown, shown
217
+ assert len(frames(shown)) == 9 and all(cells(frame) <= 79 for frame in frames(shown)), shown
218
+ removal, listing, wide = frames(shown)[-3:]
219
+ # the prefix gives way first, from its start: the end of the path stays, and the counts stay whole
220
+ assert removal.rstrip() == 'tensors | iteration:2 | ' + REMOVAL, removal
221
+ assert wide.rstrip() == 'tensors | iteration:2 | ' + REMOVAL, wide
222
+ # wider than the terminal without the path: the end gives way a whole field at a time ( 1.15 GiB stays whole, then the
223
+ # label of a number that does not fit goes with it )
224
+ assert listing.rstrip() == ' iteration:2 | Files: 1.23 K Links: 12.00 Folders: 45.00 Size: 1.15 GiB |', listing
225
+
226
+
227
+ def test_a_frame_is_measured_as_an_ascii_stdout_writes_it():
228
+ # a combining mark counts none, and an ASCII stdout ( PYTHONIOENCODING, or Python 3.6 in a C locale ) writes it as one '?': a
229
+ # decomposed name ( macOS writes them ), measured before it is written, came out 109 columns at 80, and wrapped. Only a
230
+ # combining mark shows it: a wide character is two columns and written as one '?', so the frame comes out narrower
231
+ prefix = 'e\u0301' * 30
232
+ code = ('import multiCMD\n'
233
+ 'for i in range(3): multiCMD.print_progress_bar(i, 0, %a, "| Removed: 1.23 K")\n' % prefix)
234
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
235
+ cwd=ROOT, env=dict(env_without_a_size(), PYTHONIOENCODING='ascii', COLUMNS='80'), timeout=60)
236
+ assert result.returncode == 0 and result.stderr == b'', result.stderr
237
+ shown = frames(result.stdout.decode('ascii'))
238
+ # the prefix as the stream writes it is 62 columns, and what is left of the 79 after the rest of the line is its end
239
+ written, rests = 'e?' * 30 + ' |', [' iteration:%d | Removed: 1.23 K' % i for i in range(3)]
240
+ assert shown == [written[len(rest) - 79:] + rest for rest in rests], shown
241
+
242
+
243
+ def test_a_pipe_draws_its_frames_at_240_columns():
244
+ # no terminal, and no COLUMNS ( the environment has none ): 240 columns, as in 1.67
245
+ code = ('import multiCMD\n'
246
+ 'multiCMD.print_progress_bar(5, 10, "p", "s")\n'
247
+ 'multiCMD.print_progress_bar(10, 10, "p", "s")\n'
248
+ 'multiCMD.print_progress_bar(3, 0, "p", "s")\n')
249
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
250
+ cwd=ROOT, env=dict(env_without_a_size(), PYTHONIOENCODING='utf-8'), timeout=60)
251
+ assert result.returncode == 0 and result.stderr == b'', result.stderr
252
+ full = '\N{FULL BLOCK}'
253
+ assert result.stdout.decode('utf-8') == (
254
+ '\rp |' + full * 112 + '\N{LOWER ONE EIGHTH BLOCK}' + '_' * 112 + '|50.0% | s'
255
+ '\rp |' + full * 224 + '|100.0% | s\n'
256
+ # padded to clear the last frame, to 239 columns ( 1.67: 240 )
257
+ '\r' + 'p | iteration:3 | s'.ljust(239))
258
+
259
+
260
+ @pytest.mark.parametrize('columns, shown', [
261
+ (240, '/outputs/checkpoints/step-001200/model.safetensors | iteration:7 | ' + REMOVAL),
262
+ (80, 'tensors | iteration:7 | ' + REMOVAL),
263
+ (73, ' | iteration:7 | ' + REMOVAL),
264
+ (71, ' iteration:7 | ' + REMOVAL),
265
+ # the end gives way a word at a time: ' Files', the word after a number's unit, goes on its own; the number keeps its unit
266
+ (70, ' iteration:7 | Removed: 1.23 K Folders: 45.00 | Overall: 1.23 M'),
267
+ # a label goes with its number ( 'Overall: 1.23 M' did not fit; 'Overall:' alone is not left )
268
+ (64, ' iteration:7 | Removed: 1.23 K Folders: 45.00 |'),
269
+ # 'Folders:' fits in the 39 columns, its number does not
270
+ (40, ' iteration:7 | Removed: 1.23 K'),
271
+ # '1.23' fits in the 29 columns, its unit does not
272
+ (30, ' iteration:7 |'),
273
+ # a field that fits to the last column stays ( the blank after it is the first thing that does not fit )
274
+ (31, ' iteration:7 | Removed: 1.23 K'),
275
+ (8, ' iterat'),
276
+ (1, ''),
277
+ ])
278
+ def test_a_frame_of_no_total_gives_way_from_the_prefix_then_the_end(columns, shown):
279
+ frame = _genrate_progress_bar(7, 0, PATH[-50:] + ' |', '| ' + REMOVAL, columns)
280
+ assert frame == shown.ljust(columns - 1)
281
+
282
+
283
+ def test_a_number_is_not_cut_from_its_unit_at_80_columns():
284
+ # hpcp's listing at 80 columns, five minutes in: 1.68's first build cut it at the blank before the unit, 'Size: 123.45' of 123.45 GiB
285
+ suffix = '| Files: 123.45 K Links: 1.20 K Folders: 12.34 K Size: 123.45 GiB '
286
+ frame = _genrate_progress_bar(300, 0, PATH[-50:] + ' |', suffix, 80)
287
+ assert frame == ' iteration:300 | Files: 123.45 K Links: 1.20 K Folders: 12.34 K'.ljust(79)
288
+
289
+
290
+ def a_broken_end(kept, whole):
291
+ '''Why a frame of the line whole ends badly, at kept ( what is left of whole from ' iteration:' on ), else None: inside a
292
+ word, on a label without its number, or on a number without its unit. A plain count ( '45.00' ) is complete: the word after
293
+ it is a label or a bar, not a unit.'''
294
+ if not whole.startswith(kept):
295
+ return 'is not the start of the line'
296
+ if kept != whole.rstrip() and whole[len(kept)] != ' ':
297
+ return 'ends inside a word'
298
+ if kept.endswith(':'):
299
+ return 'ends on a label without its number'
300
+ after = whole[len(kept):].split()
301
+ if re.fullmatch(r'\d+(\.\d+)?', kept.split(' ')[-1]) and after and after[0][:1].isalpha() and not after[0].endswith(':'):
302
+ return 'ends on a number without its unit'
303
+ return None
304
+
305
+
306
+ @pytest.mark.parametrize('prefix', [PATH[-50:], WIDE_PATH[-50:]], ids=['path', 'wide-path'])
307
+ @pytest.mark.parametrize('suffix', [REMOVAL, LISTING, 'Files: 123.45 K Links: 1.20 K Folders: 12.34 K Size: 123.45 GiB '],
308
+ ids=['removal', 'listing', 'large-counts'])
309
+ def test_a_frame_never_ends_inside_a_field_at_any_width(prefix, suffix):
310
+ # hpcp's lines at 20 to 200 columns: the end gives way a field at a time, after what is left of the prefix. 61cedd0 cut at
311
+ # any blank, and ended on a label without its number ( 'Removed:' ) and on a number without its unit
312
+ suffix = '| ' + suffix
313
+ whole = ' iteration:7 ' + suffix
314
+ for columns in range(20, 201):
315
+ frame = _genrate_progress_bar(7, 0, prefix + ' |', suffix, columns)
316
+ shown = frame.rstrip()
317
+ kept = shown[shown.index(' iteration:'):]
318
+ assert cells(frame) == columns - 1 and a_broken_end(kept, whole) is None, (columns, a_broken_end(kept, whole), shown)
319
+
320
+
321
+ @pytest.mark.parametrize('text, expected', [
322
+ ('', 0), ('abc', 3), ('caf\u00e9', 4), ('\u00ff\u0100\u02ff', 3),
323
+ # U+0300 is where the count by length stops: a combining mark takes none, a format character ( zero width space ) none, a Hangul
324
+ # vowel jamo none, a wide character ( Chinese, full-width ) two, an emoji two
325
+ ('\u0300', 0), ('e\u0301', 1), ('a\u200bb', 2), ('\u1160', 0), ('\u4e2d\u6587', 4), ('ab\u4e2d', 4), ('\uff21', 2), ('\U0001f600x', 3),
326
+ ('x' * 300 + '\u4e2d', 302),
327
+ ])
328
+ def test_cells_counts_a_character_by_its_unicode_width(text, expected):
329
+ # the module's own count, by Unicode's width of each character: no terminal measures it ( a tab or a newline counts one, and a
330
+ # frame draws each as a '?' before it counts: 1.69 ). ASCII and Latin-1, the usual text, is counted by length: a fast path that
331
+ # must give what the count by character gives
332
+ assert multiCMD._cells(text) == expected
333
+
334
+
335
+ def test_a_frame_counts_a_wide_character_as_two_columns_and_a_combining_mark_as_none():
336
+ frame = _genrate_progress_bar(7, 0, WIDE_PATH[-50:] + ' |', '| ' + REMOVAL, 109)
337
+ # ( padded with a blank where a wide character did not fit in the last column )
338
+ assert cells(frame) == 108 and frame.startswith('一千二百步/') and frame.endswith(REMOVAL + ' '), frame
339
+ assert _genrate_progress_bar(7, 0, WIDE_PATH[-50:] + ' |', '| ' + REMOVAL, 110).startswith('第一千二百步/'), frame
340
+ # the suffix's wide characters count too: what is left of the prefix is cut to fit them
341
+ rest = ' iteration:7 | 已删除: 1.23 K 文件夹: 45.00 '
342
+ frame = _genrate_progress_bar(7, 0, PATH[-50:] + ' |', '| 已删除: 1.23 K 文件夹: 45.00 ', 80)
343
+ assert cells(frame) == 79 and frame.rstrip() == (PATH[-50:] + ' |')[-(79 - cells(rest)):] + rest.rstrip(), frame
344
+ # with a known total, the bar is what gives way
345
+ frame = _genrate_progress_bar(5, 10, '中文前缀 |', '| 后缀', 40)
346
+ assert cells(frame) == 38 and frame.startswith('中文前缀 |') and frame.endswith('|50.0% | 后缀'), frame
347
+ # a combining mark takes none
348
+ frame = _genrate_progress_bar(7, 0, 'cafe\N{COMBINING ACUTE ACCENT} |', '| s', 40)
349
+ assert cells(frame) == 39 and len(frame) == 40, frame
350
+
351
+
352
+ def test_a_bar_of_a_known_total_at_a_terminal_too_narrow_for_it():
353
+ # 1.67 wrote the frame over six lines at 3 columns or fewer
354
+ assert [_genrate_progress_bar(5, 10, 'p |', '| s', columns) for columns in (1, 2, 3)] == ['', '', '']
355
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 5) == '\N{FULL BLOCK}\N{LOWER ONE EIGHTH BLOCK}_'
356
+
357
+
358
+ def test_a_bar_of_a_known_total_keeps_10_cells_before_its_text():
359
+ # 15 columns: the bar keeps its 10 cells, the percent goes, then the suffix, and the prefix's first field stays ( 1.68: a bar
360
+ # of 7 cells and both ). 12 columns: the bar alone, of 10; fewer: what there is
361
+ half = '\N{FULL BLOCK}' * 4 + '\N{LOWER HALF BLOCK}' + '_' * 5
362
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 15) == 'p |' + half
363
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 12) == half
364
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 8) == '\N{FULL BLOCK}' * 2 + '\N{LOWER HALF BLOCK}' + '_' * 3
365
+
366
+
367
+ def test_a_bar_of_a_known_total_drops_a_long_prefix_and_its_percent():
368
+ # 20 columns: the prefix, which the bar of a known total drops whole ( the no-total frame cuts it from its start ), and the percent
369
+ assert _genrate_progress_bar(5, 10, 'x' * 30 + ' |', '| s', 20) == '\N{FULL BLOCK}' * 7 + '\N{LOWER ONE EIGHTH BLOCK}' + '_' * 7 + '| s'
370
+
371
+
372
+ def test_a_bar_past_its_total_is_full_not_longer():
373
+ # a total that was an estimate: 1.67 drew a bar one and a half times its length, over the terminal's width
374
+ frame = _genrate_progress_bar(15, 10, 'p |', '| s', 40)
375
+ assert frame == 'p |' + '\N{FULL BLOCK}' * 24 + '|150.0% | s' and cells(frame) == 38
376
+
377
+
378
+ @pytest.mark.parametrize('columns', [40, 80, 240])
379
+ def test_the_last_frame_of_a_bar_covers_the_one_before_it(columns):
380
+ # a frame is drawn over the one before it from the line's start, and what it does not cover stays: 1.67's full bar was one
381
+ # column shorter than the others, and a bar of 10 ended '| 00:00:001' for '| 00:00:00' ( hpcp's copy bar too )
382
+ drawn = [_genrate_progress_bar(i, 10, '10 files |', '| 3.2 F/s | 00:00:0%d' % (10 - i), columns) for i in range(1, 11)]
383
+ assert [len(frame) for frame in drawn] == [columns - 2] * 10
384
+ line = []
385
+ for frame in drawn:
386
+ line[:len(frame)] = list(frame)
387
+ # ( at 40 columns '3.2 F/s' gives way, to keep a bar of 10 cells or more, and the bar takes the room: 1.68 drew '3.2 F/s' beside
388
+ # a bar of 8 cells there )
389
+ tail = '|100.0% | 3.2 F/s | 00:00:00' if columns > 40 else '| 00:00:00'
390
+ assert ''.join(line) == drawn[-1] == '10 files |' + '\N{FULL BLOCK}' * (columns - 2 - 10 - len(tail)) + tail
391
+
392
+
393
+ def test_print_progress_bar_draws_at_one_column_less_than_the_terminal(monkeypatch, capsys):
394
+ monkeypatch.setattr(multiCMD, 'get_terminal_size', lambda: os.terminal_size((80, 24)))
395
+ print_progress_bar(7, 0, PATH[-50:], REMOVAL)
396
+ assert capsys.readouterr().out == '\r' + ('tensors | iteration:7 | ' + REMOVAL).ljust(79)
397
+
398
+
399
+ # ---- 1.69: a bar with a total keeps 10 cells; a bar past its total ends its line; a control character is a '?'
400
+
401
+ BAR = re.compile('[' + multiCMD._BAR_BLOCKS + '_]+')
402
+
403
+
404
+ def parts(frame):
405
+ '''A frame of a known total as ( what is before its bar, the bar's cells, what is after it ).'''
406
+ found = BAR.search(frame)
407
+ return frame[:found.start()], found.end() - found.start(), frame[found.end():]
408
+
409
+
410
+ def a_broken_start(kept, whole):
411
+ '''Why a frame's text that keeps the end of whole, from kept on, starts badly, else None: inside a word, on a unit without
412
+ its number, on a number without its label, or on a word whose number went ( '| Files' of '1.23 M Files' ): it starts with
413
+ a number, a label or a '|' ( the mirror of a_broken_end ).'''
414
+ if not whole.endswith(kept):
415
+ return 'is not the end of the line'
416
+ before = whole[:len(whole) - len(kept)]
417
+ if before and before[-1] != ' ':
418
+ return 'starts inside a word'
419
+ before = before.split()
420
+ if before and re.fullmatch(r'\d+(\.\d+)?', before[-1]):
421
+ return 'starts on a unit without its number'
422
+ if before and before[-1].endswith(':'):
423
+ return 'starts on a number without its label'
424
+ first = kept.split()[0]
425
+ if before and not (first[0].isdigit() or first[0] == '|' or first.endswith(':')):
426
+ return 'starts on a word whose number went'
427
+ return None
428
+
429
+
430
+ @pytest.mark.parametrize('columns, suffix, shown', [
431
+ # 1.68 dropped the percent and the whole prefix: ( '', 18, '| ' + COPY ), with no count, size or percent
432
+ (80, COPY, ('123.46 KF |', 18, '| 2.35 KF/s | 2.5s: 1.10 GiB/s 2.10 KF/s | 1h2m3s')),
433
+ (80, COPY_LIMITED, ('123.46 KF |', 10, '| 2.35 KF/s | 1.00 GiB/s Limit | 5.00 KF/s Limit | 1h2m3s')),
434
+ (100, COPY, ('123.46 KF (45.60 GiB) |', 15, '| ' + COPY)),
435
+ (100, COPY_LIMITED, ('123.46 KF |', 19, '| ' + COPY_LIMITED)),
436
+ # 1.68: the whole prefix and a bar of 2 cells
437
+ (120, COPY, ('123.46 KF (45.60 GiB) Copied | 16 Scheduled |', 13, '| ' + COPY)),
438
+ (160, COPY, (COPY_PREFIX + ' |', 35, '|50.0% | ' + COPY)),
439
+ ], ids=['80', '80-limited', '100', '100-limited', '120', '160'])
440
+ def test_hpcp_copy_bar_keeps_its_count_and_its_time_left(columns, suffix, shown):
441
+ # the bar keeps 10 cells; beside it the percent gives way, then the prefix from its end down to its count, then the suffix
442
+ # from its start: the line keeps what it starts and ends with ( the count, the time left )
443
+ frame = _genrate_progress_bar(5, 10, COPY_PREFIX + ' |', '| ' + suffix, columns)
444
+ assert parts(frame) == shown and cells(frame) == columns - 2, frame
445
+
446
+
447
+ @pytest.mark.parametrize('suffix', [COPY, COPY_LIMITED, REMOVAL], ids=['copy', 'copy-limited', 'removal'])
448
+ @pytest.mark.parametrize('prefix', [COPY_PREFIX, PATH[-50:], WIDE_PATH[-50:]], ids=['copy', 'path', 'wide-path'])
449
+ def test_a_frame_of_a_known_total_keeps_whole_fields_beside_10_cells_at_any_width(prefix, suffix):
450
+ # at 12 to 200 columns: a bar of 10 cells or more, the start of the prefix and the end of the suffix, each cut only between
451
+ # fields ( a number keeps its unit, a label its number ), and the prefix's first field and the suffix's last as long as
452
+ # there is room for them
453
+ # ( a path has no blank: it is its one field )
454
+ first = '123.46 KF |' if prefix == COPY_PREFIX else prefix + ' |'
455
+ last = '| Overall: 1.23 M Files' if suffix == REMOVAL else '| 1h2m3s'
456
+ prefix, suffix = prefix + ' |', '| ' + suffix
457
+ for columns in range(12, 201):
458
+ frame = _genrate_progress_bar(5, 10, prefix, suffix, columns)
459
+ head, bar, tail = parts(frame)
460
+ if tail.startswith('|50.0% '):
461
+ tail = tail[len('|50.0% '):]
462
+ assert cells(frame) == columns - 2 and bar >= 10, (columns, frame)
463
+ assert head == '' or head == prefix or head.endswith(' |') and a_broken_end(head[:-2], prefix) is None, (columns, frame)
464
+ assert tail == '' or tail == suffix or tail.startswith('| ') and a_broken_start(tail[2:], suffix) is None, (columns, frame)
465
+ if cells(first) + 10 <= columns - 2:
466
+ assert head.startswith(first[:-2]), (columns, frame)
467
+ if cells(head) + cells(last) + 10 <= columns - 2:
468
+ assert tail.endswith(last), (columns, frame)
469
+
470
+
471
+ @pytest.mark.parametrize('suffix', [COPY, COPY_LIMITED, REMOVAL], ids=['copy', 'copy-limited', 'removal'])
472
+ @pytest.mark.parametrize('prefix', [COPY_PREFIX, PATH[-50:], WIDE_PATH[-50:]], ids=['copy', 'path', 'wide-path'])
473
+ def test_the_first_frame_of_a_known_total_has_the_place_of_its_bar_and_no_double_joint(prefix, suffix):
474
+ # iteration 0 ( hpcp's first copy bar frame ) is cut as the frames after it, and its text stands where theirs does: the bar's
475
+ # place holds ' Calculating... ' when it fits, else blanks ( 1.69 first cut it for a bar it never drew and joined prefix and
476
+ # suffix with nothing between: '0.00 F || 0.00 F/s | ∞' at 40 columns ). 1 of 1000 has a percent as long as 0's
477
+ prefix, suffix = prefix + ' |', '| ' + suffix
478
+ for columns in range(12, 201):
479
+ first = _genrate_progress_bar(0, 1000, prefix, suffix, columns)
480
+ head, bar, tail = parts(_genrate_progress_bar(1, 1000, prefix, suffix, columns))
481
+ if tail.startswith('|0.1% '):
482
+ tail = tail[len('|0.1% '):]
483
+ place = ' Calculating... ' if bar >= 16 else ' ' * bar
484
+ assert first == head + place + tail, (columns, first)
485
+ assert '||' not in first and cells(first) <= columns - 2, (columns, first)
486
+
487
+
488
+ def test_a_bar_past_its_total_ends_its_line(monkeypatch, capsys):
489
+ # 1.68 ended the line only at a frame equal to the total: a count that stepped over it left the line open, and the program's
490
+ # next output joined the bar ( '...|110.0% | snext' ). The first frame at or past the total ends it now; the frame at the
491
+ # total still ends it each time; a later frame past it is drawn on the next line and left open, so it does not scroll
492
+ monkeypatch.setattr(multiCMD, 'get_terminal_size', lambda: os.terminal_size((40, 24)))
493
+ monkeypatch.setattr(multiCMD, '_bar_done', [None])
494
+ print_progress_bar(9, 10, 'p', 's')
495
+ print_progress_bar(11, 10, 'p', 's')
496
+ print('next')
497
+ shown = capsys.readouterr().out.split('\n')
498
+ assert len(shown) == 3 and shown[0].endswith('|110.0% | s') and shown[1:] == ['next', ''], shown
499
+ for frames, lines in [
500
+ # a count that steps over the total, then goes on: one line end, after the first frame past it
501
+ ([9, 12, 13, 15], 1),
502
+ # a frame at the total, each time ( as 1.68 )
503
+ ([5, 10, 10], 2),
504
+ # at the total, then past it: as 1.68
505
+ ([9, 10, 11], 1),
506
+ # a new bar of the same total: a frame below it starts it again
507
+ ([12, 3, 12], 2),
508
+ ]:
509
+ for iteration in frames:
510
+ print_progress_bar(iteration, 10, 'p', 's')
511
+ assert capsys.readouterr().out.count('\n') == lines, frames
512
+ print_progress_bar(0, 10, 'p', 's')
513
+ capsys.readouterr()
514
+
515
+
516
+ @posix_only
517
+ def test_the_output_after_a_bar_past_its_total_starts_a_line_of_its_own():
518
+ # at a terminal of no size ( 80x24 ): the bar's line ends with the first frame past the total, and 'next' starts the line after it
519
+ code = ('import multiCMD\n'
520
+ 'for i in (5, 11): multiCMD.print_progress_bar(i, 10, "p", "s")\n'
521
+ 'print("next")')
522
+ shown = at_a_pty(code, 0, 0)
523
+ assert shown.endswith('|110.0% | s\nnext\n') and shown.count('\n') == 2, shown
524
+
525
+
526
+ CONTROL = re.compile('[\x00-\x1f\x7f-\x9f]')
527
+
528
+
529
+ @pytest.mark.parametrize('name', ['run\tlog', 'run\nlog', 'run\rlog', 'run\x1b[2Jlog', 'run\x7flog', 'run\x9b2Jlog', 'run\x00log'],
530
+ ids=['tab', 'newline', 'carriage-return', 'escape', 'delete', 'c1-csi', 'nul'])
531
+ def test_a_control_character_in_a_frame_is_a_question_mark(name):
532
+ # a file name may hold any of them ( hpcp's removal and listing lines show the end of a path ): 1.68 wrote a newline as a
533
+ # new row, so each redraw scrolled, and a tab to the next tab stop, so the frame could reach the last column and wrap
534
+ shown = CONTROL.sub('?', name)
535
+ assert shown.startswith('run?') and shown.endswith('log')
536
+ frame = _genrate_progress_bar(7, 0, '/data/' + name + ' |', '| Removed: 1.23 K', 80)
537
+ assert frame == ('/data/' + shown + ' | iteration:7 | Removed: 1.23 K').ljust(79), frame
538
+ frame = _genrate_progress_bar(5, 10, name + ' |', '| ' + name, 80)
539
+ assert not CONTROL.search(frame) and cells(frame) == 78 and frame.startswith(shown + ' |') and frame.endswith('| ' + shown)
540
+
541
+
542
+ @posix_only
543
+ def test_a_name_with_a_tab_and_a_newline_stays_on_one_row():
544
+ # at an 80-column terminal: three frames, no row of their own and no tab ( 1.68: a row more per frame, each scrolling )
545
+ code = ('import multiCMD\n'
546
+ 'for i in range(3): multiCMD.print_progress_bar(i, 0, "/data/run\\tlog\\nold", "Removed: 1.23 K")\n')
547
+ shown = at_a_pty(code, 24, 80)
548
+ assert '\n' not in shown and '\t' not in shown and len(frames(shown)) == 3, shown
549
+ assert [frame.rstrip() for frame in frames(shown)] == ['/data/run?log?old | iteration:%d | Removed: 1.23 K' % i for i in range(3)]
550
+ assert all(cells(frame) == 79 for frame in frames(shown)), shown
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes