]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Rework version bumping 3696/head
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Tue, 15 Apr 2025 18:28:25 +0000 (20:28 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 16 Apr 2025 09:57:37 +0000 (11:57 +0200)
Currently, --auto-bump= bumps the version after finishing a build.
Effectively this means the version in mkosi.version doesn't reflect
the actual version of the image which seems weird. Instead, let's
generate the new version upfront so that it's used by the build but
only write it to mkosi.version when we do a successful build.

Additionally, look for a mkosi.bump script and use it if it exists
to generate the new version so we can generate a timestamp as the
version in particleos.

mkosi/__init__.py
mkosi/config.py
mkosi/resources/man/mkosi.1.md

index 82a860b0e80d15c2655a9421f5e36305d262177f..fdb0215538fb6f4a1ae7b079ba700aad988744dd 100644 (file)
@@ -4518,29 +4518,11 @@ def generate_key_cert_pair(args: Args) -> None:
     )  # fmt: skip
 
 
-def bump_image_version() -> None:
-    """Write current image version plus one to mkosi.version"""
-
-    version_file = Path("mkosi.version")
-    if not version_file.exists():
-        die(f"Cannot bump image version, '{version_file}' not found")
-
-    if os.access(version_file, os.X_OK):
-        die(f"Cannot bump image version, '{version_file}' is executable")
-
-    version = version_file.read_text().strip()
-    v = version.split(".")
-
-    try:
-        v[-1] = str(int(v[-1]) + 1)
-    except ValueError:
-        v += ["2"]
-        logging.warning("Last component of current version is not a decimal integer, appending '.2'")
-
-    new_version = ".".join(v)
-
-    logging.info(f"Bumping version: '{version}' → '{new_version}'")
-    version_file.write_text(f"{new_version}\n")
+def finalize_image_version(args: Args, config: Config) -> None:
+    p = finalize_configdir(args) / "mkosi.version"
+    assert config.image_version
+    p.write_text(config.image_version)
+    logging.info(f"Wrote new version {config.image_version} to {p}")
 
 
 def check_workspace_directory(config: Config) -> None:
@@ -4965,9 +4947,6 @@ def run_verb(args: Args, tools: Optional[Config], images: Sequence[Config], *, r
     if args.verb == Verb.genkey:
         return generate_key_cert_pair(args)
 
-    if args.verb == Verb.bump:
-        return bump_image_version()
-
     if args.verb == Verb.dependencies:
         _, _, [deps] = parse_config(
             ["--directory=", "--repositories=", *args.cmdline, "--include=mkosi-tools", "build"],
@@ -5008,6 +4987,10 @@ def run_verb(args: Args, tools: Optional[Config], images: Sequence[Config], *, r
     # The images array has been modified so we need to reevaluate last again.
     last = images[-1]
 
+    if args.verb == Verb.bump:
+        finalize_image_version(args, last)
+        return
+
     if args.verb == Verb.clean:
         if tools and args.force > 0:
             run_clean(args, tools)
@@ -5255,7 +5238,7 @@ def run_verb(args: Args, tools: Optional[Config], images: Sequence[Config], *, r
                 logging.info("All images have already been built and do not have any build scripts")
 
         if args.auto_bump:
-            bump_image_version()
+            finalize_image_version(args, last)
 
     if args.verb == Verb.build:
         return
index 8c7b13ecf4e8952e966b615dd1d9c060e0234d5b..cb1a520c6a11887358e525bddea2335762ecef97 100644 (file)
@@ -31,7 +31,7 @@ from pathlib import Path
 from typing import Any, Callable, ClassVar, Generic, Optional, Protocol, TypeVar, Union, cast
 
 from mkosi.distributions import Distribution, detect_distribution
-from mkosi.log import ARG_DEBUG, ARG_DEBUG_SANDBOX, ARG_DEBUG_SHELL, die
+from mkosi.log import ARG_DEBUG, ARG_DEBUG_SANDBOX, ARG_DEBUG_SHELL, complete_step, die
 from mkosi.pager import page
 from mkosi.run import SandboxProtocol, find_binary, nosandbox, run, sandbox_cmd, workdir
 from mkosi.sandbox import Style, __version__
@@ -5012,6 +5012,36 @@ def finalize_configdir(args: Args) -> Path:
     return Path.cwd()
 
 
+def bump_image_version(configdir: Path) -> str:
+    version_file = configdir / "mkosi.version"
+    if os.access(version_file, os.X_OK):
+        die(f"Cannot bump image version, '{version_file}' is executable")
+
+    if version_file.exists():
+        version = version_file.read_text().strip()
+    else:
+        version = None
+
+    if (bump := configdir / "mkosi.bump").exists():
+        with complete_step(f"Running bump script {bump}"):
+            new_version = run([bump], stdout=subprocess.PIPE).stdout.strip()
+    elif version is not None:
+        v = version.split(".")
+
+        try:
+            v[-1] = str(int(v[-1]) + 1)
+        except ValueError:
+            v += ["2"]
+            logging.warning("Last component of current version is not a decimal integer, appending '.2'")
+
+        new_version = ".".join(v)
+    else:
+        new_version = "1"
+
+    logging.info(f"Bumping version: '{none_to_na(version)}' → '{new_version}'")
+    return new_version
+
+
 def parse_config(
     argv: Sequence[str] = (),
     *,
@@ -5090,6 +5120,13 @@ def parse_config(
 
     configdir = finalize_configdir(args)
 
+    if (
+        (args.auto_bump and args.verb.needs_build())
+        or args.verb == Verb.bump
+        and context.cli.get("image_version") is not None
+    ):
+        context.cli["image_version"] = bump_image_version(configdir)
+
     # Parse the global configuration unless the user explicitly asked us not to.
     if args.directory is not None:
         with chdir(configdir):
index 100dc0f303ee4cc886f882e03173902e2721942b..20914f550a9389e10957c9ce1ba2fd6cce97c0c7 100644 (file)
@@ -178,7 +178,11 @@ The following command line verbs are known:
     simple versioning scheme: each time this verb is called the version is
     bumped in preparation for the subsequent build. Note that
     `--auto-bump`/`-B` may be used to automatically bump the version
-    after each successful build.
+    as part of a build. The new version is only written to
+    `mkosi.version` if the build succeeds in that case.
+
+    If `mkosi.bump` exists, it is invoked to generate the new version to
+    be used instead of using mkosi's own logic.
 
 `genkey`
 :   Generate a pair of SecureBoot keys for usage with the
@@ -281,11 +285,14 @@ Those settings cannot be configured in the configuration files.
     Defaults to two years (730 days).
 
 `--auto-bump=`, `-B`
-:   If specified, after each successful build the version is bumped in a
-    fashion equivalent to the `bump` verb, in preparation for the next
-    build. This is useful for simple, linear version management: each
-    build in a series will have a version number one higher then the
-    previous one.
+:   If specified, the version is bumped and if the build succeeds, the
+    version is written to `mkosi.version` in a fashion equivalent to the
+    `bump` verb. This is useful for simple, linear version management:
+    each build in a series will have a version number one higher then
+    the previous one.
+
+    If `mkosi.bump` exists, it is invoked to generate the new version to
+    be used instead of using mkosi's own logic.
 
 `--doc-format`
 :   The format to show the documentation in. Supports the values `markdown`,