diff --git a/src/poetry/puzzle/provider.py b/src/poetry/puzzle/provider.py index e6d6b2cddf8..d8d6802b9ef 100644 --- a/src/poetry/puzzle/provider.py +++ b/src/poetry/puzzle/provider.py @@ -13,6 +13,7 @@ from tempfile import mkdtemp from typing import TYPE_CHECKING from typing import Any +from typing import Callable from typing import Iterable from typing import Iterator @@ -58,8 +59,14 @@ class Indicator(ProgressIndicator): CONTEXT: str | None = None @staticmethod - def set_context(context: str | None) -> None: - Indicator.CONTEXT = context + @contextmanager + def context() -> Iterator[Callable[[str | None], None]]: + def _set_context(context: str | None) -> None: + Indicator.CONTEXT = context + + yield _set_context + + _set_context(None) def _formatter_context(self) -> str: if Indicator.CONTEXT is None: diff --git a/src/poetry/utils/helpers.py b/src/poetry/utils/helpers.py index 3aa79a26824..2ea091debae 100644 --- a/src/poetry/utils/helpers.py +++ b/src/poetry/utils/helpers.py @@ -102,32 +102,33 @@ def download_file( response.raise_for_status() set_indicator = False - if "Content-Length" in response.headers: - try: - total_size = int(response.headers["Content-Length"]) - except ValueError: - total_size = 0 - - fetched_size = 0 - last_percent = 0 - - Indicator.set_context(f"Downloading {url}") - # if less than 1MB, we simply show that we're downloading but skip the updating - set_indicator = total_size > 1024 * 1024 - - with open(dest, "wb") as f: - for chunk in response.iter_content(chunk_size=chunk_size): - if chunk: - f.write(chunk) - - if set_indicator: - fetched_size += len(chunk) - percent = (fetched_size * 100) // total_size - if percent > last_percent: - last_percent = percent - Indicator.set_context(f"Downloading {url} {percent:3}%") - - Indicator.set_context(None) + with Indicator.context() as update_context: + update_context(f"Downloading {url}") + + if "Content-Length" in response.headers: + try: + total_size = int(response.headers["Content-Length"]) + except ValueError: + total_size = 0 + + fetched_size = 0 + last_percent = 0 + + # if less than 1MB, we simply show that we're downloading + # but skip the updating + set_indicator = total_size > 1024 * 1024 + + with open(dest, "wb") as f: + for chunk in response.iter_content(chunk_size=chunk_size): + if chunk: + f.write(chunk) + + if set_indicator: + fetched_size += len(chunk) + percent = (fetched_size * 100) // total_size + if percent > last_percent: + last_percent = percent + update_context(f"Downloading {url} {percent:3}%") def get_package_version_display_string(