Skip to content

Commit 7e7127e

Browse files
committed
Reimplement naturalsize as part of pubtools-pulplib [RHELDST-29440]
This commit pulls out the naturalsize function from humanize module and strips it to the bare minimum we need in pubtools-pulplib. The humanize module is then removed from dependencies as it's not used anywhere else. This is done to reduce the dependency bloat and make the RPM packaging easier on RHEL 9 which doesn't ship python-humanize.
1 parent c8b2330 commit 7e7127e

File tree

4 files changed

+47
-3
lines changed

4 files changed

+47
-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: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,28 @@ def dict_put(out, key, value):
4747
else:
4848
# Not the last key, so ensure there's a sub-dict.
4949
out = out.setdefault(next_key, {})
50+
51+
52+
def naturalsize(value):
53+
"""
54+
Format a number of bytes like a human-readable filesize.
55+
Uses SI system (metric), so e.g. 10000 B = 10 kB.
56+
"""
57+
base = 1000
58+
59+
if isinstance(value, str):
60+
bytes_ = float(value)
61+
else:
62+
bytes_ = value
63+
abs_bytes = abs(bytes_)
64+
65+
if abs_bytes == 1:
66+
return f"{bytes_} Byte"
67+
if abs_bytes < base:
68+
return f"{int(bytes_)} Bytes"
69+
70+
for i, s in enumerate(("k", "M", "G", "T", "P", "E"), 2):
71+
unit = base**i
72+
if abs_bytes < unit:
73+
break
74+
return f"{base * (bytes_ / unit):.1f} {s}B"

tests/util/test_naturalsize.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
],
16+
)
17+
def test_naturalsize(input, output):
18+
"""
19+
Format a number of bytes like a human-readable filesize.
20+
"""
21+
assert naturalsize(input) == output

0 commit comments

Comments
 (0)