From ed9e65d9f94afb3226cbcbfd9639e561482ccdd6 Mon Sep 17 00:00:00 2001 From: Daan De Meyer Date: Sun, 1 Oct 2023 20:04:33 +0200 Subject: [PATCH] Add back parse_bytes() function as config_parse_bytes() --- mkosi/config.py | 28 ++++++++++++++++++++++++++++ tests/test_config.py | 22 ++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/mkosi/config.py b/mkosi/config.py index ddf4d2b5f..7bbdfc6c5 100644 --- a/mkosi/config.py +++ b/mkosi/config.py @@ -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 diff --git a/tests/test_config.py b/tests/test_config.py index f2e1519cb..89fa124d6 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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") -- 2.47.3