From: Joerg Behrmann Date: Sat, 3 Sep 2022 18:35:37 +0000 (+0200) Subject: support floats for parse_bytes X-Git-Tag: v14~46 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7e372af9669d754034478eaf3a560d08e26bec36;p=thirdparty%2Fmkosi.git support floats for parse_bytes Fixes: #1168 --- diff --git a/mkosi/__init__.py b/mkosi/__init__.py index 6ef2c0b11..7d48cfc7c 100644 --- a/mkosi/__init__.py +++ b/mkosi/__init__.py @@ -23,6 +23,7 @@ import http.server import importlib.resources import itertools import json +import math import os import platform import re @@ -5930,9 +5931,10 @@ def parse_args_file_group( return create_parser().parse_args(config_files + argv) -def parse_bytes(num_bytes: Optional[str]) -> Optional[int]: +def parse_bytes(num_bytes: Optional[str], *, sector_size: int = 512) -> Optional[int]: + """Convert a string for a number of bytes into a number rounding up to sector size.""" if num_bytes is None: - return num_bytes + return None if num_bytes.endswith("G"): factor = 1024 ** 3 @@ -5946,12 +5948,13 @@ def parse_bytes(num_bytes: Optional[str]) -> Optional[int]: if factor > 1: num_bytes = num_bytes[:-1] - result = int(num_bytes) * factor + result = math.ceil(float(num_bytes) * factor) if result <= 0: raise ValueError("Size out of range") - if result % 512 != 0: - raise ValueError("Size not a multiple of 512") + rem = result % sector_size + if rem != 0: + result += sector_size - rem return result diff --git a/tests/test_init.py b/tests/test_init.py index 019a12ce2..2281e1c8d 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -30,6 +30,7 @@ def test_strip_suffixes() -> None: assert mkosi.strip_suffixes(Path("home.xz/test")) == Path("home.xz/test") assert mkosi.strip_suffixes(Path("home.xz/test.txt")) == Path("home.xz/test.txt") + def test_copy_file(tmpdir: Path) -> None: dir_path = Path(tmpdir) file_1 = Path(dir_path) / "file_1.txt" @@ -54,3 +55,24 @@ def test_copy_file(tmpdir: Path) -> None: file_2.write_text("Testing copying content from file_1 to file_2, with previous data.") mkosi.copy_file(file_1, file_2) assert filecmp.cmp(file_1, file_2) + + +def test_parse_bytes() -> None: + assert mkosi.parse_bytes(None) is None + assert mkosi.parse_bytes("1") == 512 + assert mkosi.parse_bytes("1000") == 1024 + assert mkosi.parse_bytes("1K") == 1024 + assert mkosi.parse_bytes("1025") == 1536 + assert mkosi.parse_bytes("1M") == 1024**2 + assert mkosi.parse_bytes("1.9M") == 1992704 + assert mkosi.parse_bytes("1G") == 1024**3 + assert mkosi.parse_bytes("7.3G") == 7838315520 + + with pytest.raises(ValueError): + mkosi.parse_bytes("-1") + with pytest.raises(ValueError): + mkosi.parse_bytes("-2K") + with pytest.raises(ValueError): + mkosi.parse_bytes("-3M") + with pytest.raises(ValueError): + mkosi.parse_bytes("-4G")