]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Add back parse_bytes() function as config_parse_bytes()
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Sun, 1 Oct 2023 18:04:33 +0000 (20:04 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 2 Oct 2023 08:01:27 +0000 (10:01 +0200)
mkosi/config.py
tests/test_config.py

index ddf4d2b5f9ff90cb3748a741158a5266902e80ff..7bbdfc6c5dde70071cc537a6ebc957ea0f724246 100644 (file)
@@ -11,6 +11,7 @@ import functools
 import graphlib
 import inspect
 import logging
+import math
 import operator
 import os.path
 import platform
@@ -500,6 +501,33 @@ def match_systemd_version(value: str) -> bool:
     return config_match_version(value, version)
 
 
+def config_parse_bytes(value: Optional[str], old: Optional[int] = None) -> Optional[int]:
+    if not value:
+        return None
+
+    if value.endswith("G"):
+        factor = 1024**3
+    elif value.endswith("M"):
+        factor = 1024**2
+    elif value.endswith("K"):
+        factor = 1024
+    else:
+        factor = 1
+
+    if factor > 1:
+        value = value[:-1]
+
+    result = math.ceil(float(value) * factor)
+    if result <= 0:
+        die("Size out of range")
+
+    rem = result % 4096
+    if rem != 0:
+        result += 4096 - rem
+
+    return result
+
+
 @dataclasses.dataclass(frozen=True)
 class MkosiConfigSetting:
     dest: str
index f2e1519cbeeaf7389ca686c480a1ebc17f4ecbbc..89fa124d6f1a59cffebfc52a1ec0bdfdc5a157d9 100644 (file)
@@ -16,6 +16,7 @@ from mkosi.config import (
     ConfigFeature,
     OutputFormat,
     Verb,
+    config_parse_bytes,
     parse_config,
     parse_ini,
 )
@@ -609,3 +610,24 @@ def test_wrong_section_warning(
             parse_config(args)
 
         assert len(caplog.records) == warning_count
+
+
+def test_config_parse_bytes() -> None:
+    assert config_parse_bytes(None) is None
+    assert config_parse_bytes("1") == 4096
+    assert config_parse_bytes("8000") == 8192
+    assert config_parse_bytes("8K") == 8192
+    assert config_parse_bytes("4097") == 8192
+    assert config_parse_bytes("1M") == 1024**2
+    assert config_parse_bytes("1.9M") == 1994752
+    assert config_parse_bytes("1G") == 1024**3
+    assert config_parse_bytes("7.3G") == 7838318592
+
+    with pytest.raises(SystemExit):
+        config_parse_bytes("-1")
+    with pytest.raises(SystemExit):
+        config_parse_bytes("-2K")
+    with pytest.raises(SystemExit):
+        config_parse_bytes("-3M")
+    with pytest.raises(SystemExit):
+        config_parse_bytes("-4G")