Skip to content

Commit 212b912

Browse files
authored
Merge pull request #336 from wolph/fix/stream-multibar-regressions
Fix relabelling, triple flush and lost text regressions from 4.7.0
2 parents 12f734a + 1b21ef8 commit 212b912

6 files changed

Lines changed: 365 additions & 23 deletions

File tree

‎CHANGES.rst‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,24 @@
22
Changelog
33
=========
44

5+
Unreleased
6+
----------
7+
8+
A bar that leaves a ``MultiBar``, through ``pop``, ``del``, ``clear``,
9+
a replacement under the same label or ``remove_finished``, takes its
10+
generated label widgets with it. Adding it again labels it once. 4.7.0
11+
left the old labels in ``bar.widgets`` and labelled it twice.
12+
13+
The ``stop_capturing()`` that brings the count to zero flushes the
14+
original stream once, as 4.6.0 did. 4.7.0 flushed it three times. A
15+
``StreamWrapper`` subclass whose ``update_capturing()`` calls ``super()``
16+
gets two flushes, the second one on an empty buffer.
17+
18+
A ``WrappingIO.flush()`` replacement that raises no longer costs the
19+
captured text. The text goes back in front of anything written since,
20+
and the next flush delivers it in order. 4.7.0 drained the buffer first
21+
and lost the text.
22+
523
4.7.0 - 2026-11-05
624
------------------
725

‎SECURITY.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ That keeps the report out of the public issue tracker until a fix is
1515
available. If you cannot use the form, mail <Wolph@Wol.ph> instead.
1616

1717
Please include the progressbar2 version, the configuration that triggers the
18-
issue and a minimal reproduction. Expect an acknowledgement within a week.
18+
issue and a minimal reproduction. Expect an acknowledgement within a week.

‎progressbar/multi.py‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939

4040
SortKeyFunc = collections.abc.Callable[[bar.ProgressBar], typing.Any]
4141
_NO_LABEL: object = object()
42+
#: The label widgets a `MultiBar` inserted into one bar: the prefix and
43+
#: the suffix, `None` for the end that got no label.
44+
_Labels = tuple[str | None, str | None]
4245

4346

4447
class _Update(typing.Protocol):
@@ -176,6 +179,7 @@ class MultiBar(dict[str, bar.ProgressBar]):
176179
_previous_output: list[str]
177180
_finished_at: _identity.IdentityMap[bar.ProgressBar, float]
178181
_labeled: _identity.IdentitySet[bar.ProgressBar]
182+
_labels: _identity.IdentityMap[bar.ProgressBar, _Labels]
179183
_custom_labels: bool
180184
_membership_box: utils._SharedLock # pyright: ignore[reportPrivateUsage]
181185
_print_lock: threading.RLock
@@ -237,6 +241,7 @@ def __init__(
237241

238242
self._custom_labels = False
239243
self._labeled = _identity.IdentitySet[bar.ProgressBar]()
244+
self._labels = _identity.IdentityMap()
240245
self._finished_at = _identity.IdentityMap()
241246
self._previous_output = []
242247
self._buffer = io.StringIO()
@@ -344,6 +349,35 @@ def _forget_bar(self, progress: bar.ProgressBar | None) -> None:
344349
if progress is not None:
345350
self._finished_at.pop(progress, None)
346351
self._labeled.discard(progress)
352+
self._remove_labels(
353+
progress, self._labels.pop(progress, (None, None))
354+
)
355+
356+
@staticmethod
357+
def _remove_labels(progress: bar.ProgressBar, labels: _Labels) -> None:
358+
"""Take the generated label widgets out of a bar that leaves.
359+
360+
The widgets are matched by identity: the bar keeps a label of
361+
its own that happens to render the same text. The prefix is
362+
searched from the front and the suffix from the back, because
363+
`label_format` can return an object the bar also holds as a
364+
widget of its own (`'{label}'` returns the key itself).
365+
"""
366+
widgets: collections.abc.MutableSequence[typing.Any] = progress.widgets
367+
prefix: str | None
368+
suffix: str | None
369+
prefix, suffix = labels
370+
index: int
371+
if prefix is not None:
372+
for index in range(len(widgets)):
373+
if widgets[index] is prefix:
374+
del widgets[index]
375+
break
376+
if suffix is not None:
377+
for index in reversed(range(len(widgets))):
378+
if widgets[index] is suffix:
379+
del widgets[index]
380+
break
347381

348382
def __delitem__(self, key: str) -> None:
349383
"""Remove a progressbar and its tracking."""
@@ -424,9 +458,12 @@ def clear(self) -> None:
424458
removed = list(super().values())
425459
removed.extend(self._finished_at)
426460
removed.extend(self._labeled)
461+
for progress in self._labels:
462+
self._remove_labels(progress, self._labels[progress])
427463
super().clear()
428464
self._finished_at.clear()
429465
self._labeled.clear()
466+
self._labels.clear()
430467
# `removed` keeps the bars alive until this method returns, so
431468
# their finalisers run after the membership guard is released.
432469

@@ -445,11 +482,25 @@ def _label_bar(
445482
if self.prepend_label or self.append_label:
446483
self._labeled.add(bar)
447484

485+
prefix: str | None = None
486+
suffix: str | None = None
448487
if self.prepend_label: # pragma: no branch
449-
widgets.insert(0, self.label_format.format(label=label))
488+
prefix = self.label_format.format(label=label)
489+
widgets.insert(0, prefix)
450490
if self.append_label: # pragma: no branch
451-
widgets.append(self.label_format.format(label=label))
452-
return True
491+
suffix = self.label_format.format(label=label)
492+
widgets.append(suffix)
493+
if prefix is None and suffix is None:
494+
return True
495+
labels: _Labels = (prefix, suffix)
496+
with self._membership_guard(label):
497+
if bar in self._labeled:
498+
self._labels[bar] = labels
499+
return True
500+
# The bar left while its labels were being formatted. Take them
501+
# out again, so a later insertion labels it once.
502+
self._remove_labels(bar, labels)
503+
return not require_member
453504

454505
def render(self, flush: bool = True, force: bool = False) -> None:
455506
"""Redraw every bar, only touching lines that actually changed.

‎progressbar/utils.py‎

Lines changed: 51 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -449,12 +449,33 @@ def _deliver(self, value: str) -> None:
449449
if value:
450450
# A replacement flush() may log. Call it only during
451451
# delivery, outside both the buffer and transition locks.
452-
self.flush()
452+
try:
453+
self.flush()
454+
except BaseException:
455+
# The text was taken already. Put it back in front of
456+
# anything written since, so a flush() that fails once
457+
# (a handler that is not ready yet) costs no output.
458+
self._restore(value)
459+
raise
453460
if value and not self.target.closed:
454461
self.target.write(value)
455462
# when explicitly flushing, always flush the target as well
456463
self.flush_target()
457464

465+
def _restore(self, value: str) -> None:
466+
"""Put text taken by `_take()` back, ahead of later writes."""
467+
with (
468+
self._buffer_box.lock
469+
if self._native_buffer()
470+
else contextlib.nullcontext()
471+
):
472+
rest: str = self.buffer.getvalue()
473+
self.buffer.seek(0)
474+
self.buffer.truncate(0)
475+
self.buffer.write(value + rest)
476+
if '\n' in value:
477+
self.needs_clear = True
478+
458479
def flush_target(self) -> None: # pragma: no cover
459480
"""Flush `target` itself, if it's open and flushable."""
460481
if not self.target.closed and getattr(self.target, 'flush', None):
@@ -681,6 +702,11 @@ def stop_capturing(self, bar: _ProgressListener | None = None) -> None:
681702
"""
682703
pending: list[_Pending] = []
683704
failure: BaseException | None = None
705+
# The default hook drains and delivers through `flush()`, as
706+
# 4.6.0 did, so the original stream is flushed once. Only a
707+
# replaced hook, which may not call `super()`, needs this stop
708+
# to deliver its own text before the hook runs.
709+
deliver: bool = not self._default_capture_hook()
684710
with self.lock:
685711
if bar: # pragma: no branch
686712
with self.listeners_lock, contextlib.suppress(KeyError):
@@ -690,16 +716,24 @@ def stop_capturing(self, bar: _ProgressListener | None = None) -> None:
690716
# the next start_capturing() a no-op
691717
self.capturing = max(self.capturing - 1, 0)
692718
try:
693-
pending = self._apply_capturing()
719+
if deliver:
720+
pending = self._apply_capturing()
721+
else:
722+
self._propagate_capturing()
694723
except BaseException as exception: # noqa: BLE001
695724
failure = exception
696-
if failure is None:
725+
if failure is None and pending:
697726
try:
698727
self._deliver(pending)
699728
except BaseException as exception: # noqa: BLE001
700729
failure = exception
701730
self._notify_capturing(failure)
702731

732+
def _default_capture_hook(self) -> bool:
733+
"""Return whether `update_capturing` is the one defined here."""
734+
hook: object = getattr(self.update_capturing, '__func__', None)
735+
return hook is StreamWrapper.update_capturing
736+
703737
def _notify_capturing(self, failure: BaseException | None) -> None:
704738
"""Notify the public hook without replacing an earlier failure."""
705739
if failure is None:
@@ -720,22 +754,28 @@ def update_capturing(self) -> None: # pragma: no cover
720754
until something else happens to trigger a flush.
721755
722756
Start and stop invoke overrides after the state propagation
723-
attempt. Stop also attempts delivery before invoking the hook,
724-
even if that attempt fails. Calling `super()` reconciles the
725-
current state again and can flush an already empty target.
757+
attempt. A stop with a replaced hook also delivers its own text
758+
before invoking it, even if that delivery fails. Calling
759+
`super()` reconciles the current state again and flushes.
726760
Concurrent transitions can change the state before the hook
727761
runs, so it can observe a later transition's count and flags.
728762
"""
729763
with self.lock:
730-
pending: list[_Pending] = self._apply_capturing()
731-
self._deliver(pending)
764+
self._propagate_capturing()
732765
if self.capturing <= 0:
733766
# 4.6.0 flushed through the public method here, so a
734767
# subclass that overrides `flush()` sees the last bar stop
735-
# capturing. The text itself went out above, this drains
736-
# whatever a listener wrote in between.
768+
# capturing, and the original stream is flushed once.
737769
self.flush()
738770

771+
def _propagate_capturing(self) -> None:
772+
"""Push the capture flag onto the installed wrappers, under `lock`."""
773+
if isinstance(self.stdout, WrappingIO):
774+
self.stdout.capturing = self.capturing > 0
775+
776+
if isinstance(self.stderr, WrappingIO):
777+
self.stderr.capturing = self.capturing > 0
778+
739779
def _apply_capturing(self) -> list[_Pending]:
740780
"""Push the capture state onto the wrappers, under `lock`.
741781
@@ -748,12 +788,7 @@ def _apply_capturing(self) -> list[_Pending]:
748788
same text twice, and an unwrap cannot swap the wrapper out
749789
between the type check and the drain.
750790
"""
751-
if isinstance(self.stdout, WrappingIO):
752-
self.stdout.capturing = self.capturing > 0
753-
754-
if isinstance(self.stderr, WrappingIO):
755-
self.stderr.capturing = self.capturing > 0
756-
791+
self._propagate_capturing()
757792
if self.capturing > 0:
758793
return []
759794
return self._take()

0 commit comments

Comments
 (0)