Skip to content

Commit

Permalink
switch to using a context manager instead
Browse files Browse the repository at this point in the history
  • Loading branch information
tgolsson committed Apr 28, 2022
1 parent efb30e1 commit 8b636a6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 28 deletions.
11 changes: 9 additions & 2 deletions src/poetry/puzzle/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
53 changes: 27 additions & 26 deletions src/poetry/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 8b636a6

Please sign in to comment.