From c10aa7124d505f9c48bf819da4c66a32aa9f4f8d Mon Sep 17 00:00:00 2001 From: Daan De Meyer Date: Thu, 9 Nov 2023 19:30:14 +0100 Subject: [PATCH] Add proper parser for sector size --- mkosi/__init__.py | 2 +- mkosi/config.py | 24 +++++++++++++++++++++--- mkosi/util.py | 4 ++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/mkosi/__init__.py b/mkosi/__init__.py index 5f3b17b05..5f2abc64c 100644 --- a/mkosi/__init__.py +++ b/mkosi/__init__.py @@ -1993,7 +1993,7 @@ def make_image( if split: cmdline += ["--split=yes"] if state.config.sector_size: - cmdline += ["--sector-size", state.config.sector_size] + cmdline += ["--sector-size", str(state.config.sector_size)] if definitions: for d in definitions: diff --git a/mkosi/config.py b/mkosi/config.py index ae78396fb..9dde626e2 100644 --- a/mkosi/config.py +++ b/mkosi/config.py @@ -33,7 +33,7 @@ from mkosi.pager import page from mkosi.run import run from mkosi.types import PathString, SupportsRead -from mkosi.util import INVOKING_USER, StrEnum, chdir, flatten +from mkosi.util import INVOKING_USER, StrEnum, chdir, flatten, is_power_of_2 from mkosi.versioncomp import GenericVersion __version__ = "18" @@ -572,6 +572,24 @@ def parse_drive(value: str) -> QemuDrive: return QemuDrive(id=id, size=size, directory=directory, options=options) +def config_parse_sector_size(value: Optional[str], old: Optional[int]) -> Optional[int]: + if not value: + return None + + try: + size = int(value) + except ValueError: + die(f"'{value}' is not a valid number") + + if size < 512 or size > 4096: + die(f"Sector size not between 512 and 4096: {size}") + + if not is_power_of_2(size): + die(f"Sector size not power of 2: {size}") + + return size + + @dataclasses.dataclass(frozen=True) class MkosiConfigSetting: dest: str @@ -797,7 +815,7 @@ class MkosiConfig: image_version: Optional[str] split_artifacts: bool repart_dirs: list[Path] - sector_size: Optional[str] + sector_size: Optional[int] overlay: bool use_subvolumes: ConfigFeature seed: Optional[uuid.UUID] @@ -1333,7 +1351,7 @@ def parse_ini(path: Path, only_sections: Collection[str] = ()) -> Iterator[tuple MkosiConfigSetting( dest="sector_size", section="Output", - parse=config_parse_string, + parse=config_parse_sector_size, help="Set the disk image sector size", ), MkosiConfigSetting( diff --git a/mkosi/util.py b/mkosi/util.py index 050f67dcc..6521e6b13 100644 --- a/mkosi/util.py +++ b/mkosi/util.py @@ -166,3 +166,7 @@ def umask(mask: int) -> Iterator[None]: yield finally: os.umask(old) + + +def is_power_of_2(x: int) -> bool: + return x > 0 and (x & x - 1 == 0)