Skip to content

Commit da92c8d

Browse files
authored
Merge pull request #232 from MichalHaluza/absorb_humanize
Reimplement naturalsize as part of pubtools-pulplib [RHELDST-29440]
2 parents c8b2330 + 58b411d commit da92c8d

File tree

4 files changed

+51
-3
lines changed

4 files changed

+51
-3
lines changed

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,4 @@ attrs
66
frozenlist2
77
frozendict; python_version >= '3.6'
88
pubtools>=0.3.0
9-
humanize
109
monotonic; python_version < '3.3'

src/pubtools/pulplib/_impl/client/client.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,11 @@
2424
Task,
2525
)
2626
from ..log import TimedLogger
27-
from ..util import dict_put
27+
from ..util import dict_put, naturalsize
2828
from .search import search_for_criteria
2929
from .errors import PulpException
3030
from .poller import TaskPoller
3131
from . import retry
32-
from humanize import naturalsize
3332

3433
from .ud_mappings import compile_ud_mappings
3534
from .copy import CopyOptions

src/pubtools/pulplib/_impl/util.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
ABSENT = object()
2+
SUFFIXES = ("k", "M", "G", "T", "P", "E")
23

34

45
def lookup(value, key, default=ABSENT):
@@ -47,3 +48,30 @@ def dict_put(out, key, value):
4748
else:
4849
# Not the last key, so ensure there's a sub-dict.
4950
out = out.setdefault(next_key, {})
51+
52+
53+
def naturalsize(value):
54+
"""
55+
Format a number of bytes like a human-readable filesize.
56+
Uses SI system (metric), so e.g. 10000 B = 10 kB.
57+
"""
58+
base = 1000
59+
60+
if isinstance(value, str):
61+
size_bytes = float(value)
62+
else:
63+
size_bytes = value
64+
abs_bytes = abs(size_bytes)
65+
66+
if abs_bytes == 1:
67+
return f"{size_bytes} Byte"
68+
if abs_bytes < base:
69+
return f"{int(size_bytes)} Bytes"
70+
71+
suffix = ""
72+
for power, suffix in enumerate(SUFFIXES, 2):
73+
unit = base**power
74+
if abs_bytes < unit:
75+
break
76+
size_natural = base * (size_bytes / unit)
77+
return f"{size_natural:.1f} {suffix}B"

tests/util/test_naturalsize.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import pytest
2+
3+
from pubtools.pulplib._impl.util import naturalsize
4+
5+
6+
@pytest.mark.parametrize(
7+
"input,output",
8+
[
9+
(1, "1 Byte"),
10+
("10", "10 Bytes"),
11+
(1234, "1.2 kB"),
12+
(1234567, "1.2 MB"),
13+
(678909876543, "678.9 GB"),
14+
(1000000000000, "1.0 TB"),
15+
("874365287928728746529431", "874365.3 EB"),
16+
],
17+
)
18+
def test_naturalsize(input, output):
19+
"""
20+
Format a number of bytes like a human-readable filesize.
21+
"""
22+
assert naturalsize(input) == output

0 commit comments

Comments
 (0)