diff --git a/Cargo.lock b/Cargo.lock index 99d949772a..786038aeba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3603,7 +3603,7 @@ dependencies = [ [[package]] name = "minimal" -version = "0.0.1" +version = "0.5.0-rc1" dependencies = [ "anyhow", "async-compression", @@ -3630,6 +3630,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "version", ] [[package]] @@ -3640,7 +3641,7 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "minimald" -version = "0.0.1" +version = "0.5.0-rc1" dependencies = [ "args", "async-compression", @@ -3690,6 +3691,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "version", "vt100-ctt", ] @@ -3717,7 +3719,7 @@ dependencies = [ [[package]] name = "minvmd" -version = "0.0.1" +version = "0.5.0-rc1" dependencies = [ "anyhow", "clap", @@ -3740,6 +3742,7 @@ dependencies = [ "toml", "tracing", "tracing-subscriber", + "version", ] [[package]] @@ -3755,7 +3758,7 @@ dependencies = [ [[package]] name = "mip" -version = "0.4.1" +version = "0.5.0-rc1" dependencies = [ "anyhow", "args", @@ -3789,6 +3792,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "version", ] [[package]] @@ -7096,6 +7100,10 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "version" +version = "0.5.0-rc1" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index e17d4e185a..4ec049ad92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,11 +27,16 @@ members = [ "crates/sessions", "crates/stdlib", "crates/switch", + "crates/version", ] resolver = "3" package.edition = "2024" package.publish = false +# Shared base version for the workspace. This is the fallback the `version` crate +# reports when no `v*` git tag is reachable; the real release version comes from +# `git describe` at build time. See crates/version/build.rs. +package.version = "0.5.0-rc1" [profile.release] strip = true @@ -148,28 +153,31 @@ walkdir = "2.5" petgraph = "0.8" -# our crates -args = { version = "0.0.1", path = "crates/args" } -async-dialog = { version = "0.0.1", path = "crates/async-dialog" } -graph = { version = "0.0.1", path = "crates/graph" } -lcache = { version = "0.0.1", path = "crates/lcache" } -rcache = { version = "0.0.1", path = "crates/rcache" } -check = { version = "0.0.1", path = "crates/check" } -checkouts = { version = "0.0.1", path = "crates/checkouts" } -common = { version = "0.0.1", path = "crates/common" } -decode = { version = "0.0.1", path = "crates/decode" } -diagnostics = { version = "0.0.1", path = "crates/diagnostics" } -mctx = { version = "0.0.1", path = "crates/mctx" } -minimald-rpc = { version = "0.0.1", path = "crates/minimald-rpc" } -mfile = { version = "0.0.1", path = "crates/mfile" } -op = { version = "0.0.1", path = "crates/op" } -ot = { version = "0.0.1", path = "crates/ot" } -orchestrator = { version = "0.0.1", path = "crates/orchestrator" } -paths = { version = "0.0.1", path = "crates/paths" } -remote-proto = { version = "0.0.1", path = "crates/remote-proto" } -remote-client = { version = "0.0.1", path = "crates/remote-client" } -sandbox2 = { version = "0.0.1", path = "crates/sandbox2" } -sessions = { version = "0.0.1", path = "crates/sessions" } -switch = { version = "0.0.1", path = "crates/switch" } +# Our crates. These are path deps in a `publish = false` workspace, so no +# `version` requirement is needed (or used) — cargo resolves them by path. Adding +# one would just be a pin to keep in sync with each crate's own version. +args = { path = "crates/args" } +async-dialog = { path = "crates/async-dialog" } +graph = { path = "crates/graph" } +lcache = { path = "crates/lcache" } +rcache = { path = "crates/rcache" } +check = { path = "crates/check" } +checkouts = { path = "crates/checkouts" } +common = { path = "crates/common" } +decode = { path = "crates/decode" } +diagnostics = { path = "crates/diagnostics" } +mctx = { path = "crates/mctx" } +minimald-rpc = { path = "crates/minimald-rpc" } +mfile = { path = "crates/mfile" } +op = { path = "crates/op" } +ot = { path = "crates/ot" } +orchestrator = { path = "crates/orchestrator" } +paths = { path = "crates/paths" } +remote-proto = { path = "crates/remote-proto" } +remote-client = { path = "crates/remote-client" } +sandbox2 = { path = "crates/sandbox2" } +sessions = { path = "crates/sessions" } +switch = { path = "crates/switch" } +version = { path = "crates/version" } -stdlib = { version = "0.0.17", path = "crates/stdlib" } +stdlib = { path = "crates/stdlib" } diff --git a/crates/minimal/Cargo.toml b/crates/minimal/Cargo.toml index e985f6515a..e172b82f2d 100644 --- a/crates/minimal/Cargo.toml +++ b/crates/minimal/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minimal" -version = "0.0.1" +version.workspace = true edition.workspace = true publish.workspace = true @@ -42,6 +42,7 @@ sessions.workspace = true tokio.workspace = true tracing.workspace = true tracing-subscriber.workspace = true +version.workspace = true # default-features = false drops minvmd's `libkrun` feature: the CLI only uses # the client helpers (sock/lifecycle) and calls no krun code, so it must not diff --git a/crates/minimal/build.rs b/crates/minimal/build.rs deleted file mode 100644 index a350f08088..0000000000 --- a/crates/minimal/build.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::process::Command; -fn main() { - let output = Command::new("git") - .args(["rev-parse", "--short", "HEAD"]) - .output() - .unwrap(); - let git_hash = String::from_utf8(output.stdout).unwrap(); - println!("cargo:rustc-env=GIT_HASH={}", git_hash); - - let is_clean = std::process::Command::new("git") - .args(["status", "--porcelain=v1"]) - .output() - .map(|o| o.stdout.is_empty()) - .unwrap_or(false); - if !is_clean && std::env::var("PROFILE").unwrap() == "release" { - println!("cargo::warning=Building a release binary from an unclean working tree!!"); - println!("cargo::warning=Always build production binaries from a clean checkout."); - } - - println!( - "cargo:rustc-env=LONG_VERSION={} ({}{})", - std::env::var("CARGO_PKG_VERSION").unwrap().as_str(), - if is_clean { "" } else { "dirty " }, - git_hash.strip_suffix("\n").unwrap(), - ); -} diff --git a/crates/minimal/src/lib.rs b/crates/minimal/src/lib.rs index d178a75032..6b1609a6a4 100644 --- a/crates/minimal/src/lib.rs +++ b/crates/minimal/src/lib.rs @@ -18,7 +18,7 @@ pub mod git_remote; pub mod loadouts; #[derive(Parser)] -#[command(name = "min", version = env!("CARGO_PKG_VERSION"), long_version = env!("LONG_VERSION"))] +#[command(name = "min", version = version::VERSION, long_version = version::LONG_VERSION)] #[command(about = "The Minimal CLI")] pub struct Cli { #[command(subcommand)] @@ -1734,7 +1734,7 @@ pub async fn cmd_update(global: &GlobalArgs, _args: UpdateArgs) -> Result<(), mc /// not autospawn the daemon — it is a lightweight diagnostic that should /// report versions without starting a VM. pub async fn cmd_version(global: &GlobalArgs) -> Result<(), anyhow::Error> { - println!("Client: minimal {}", env!("LONG_VERSION")); + println!("Client: minimal {}", version::LONG_VERSION); let sock = match client::resolve_socket_path(global.minimal_dir.as_deref()) { Ok(p) => p, diff --git a/crates/minimald/Cargo.toml b/crates/minimald/Cargo.toml index 013e40b381..071f7491ac 100644 --- a/crates/minimald/Cargo.toml +++ b/crates/minimald/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minimald" -version = "0.0.1" +version.workspace = true edition.workspace = true publish.workspace = true @@ -70,6 +70,7 @@ sandbox2.workspace = true sessions.workspace = true switch.workspace = true stdlib.workspace = true +version.workspace = true rcgen = { workspace = true, optional = true } rustls = { workspace = true, optional = true } diff --git a/crates/minimald/build.rs b/crates/minimald/build.rs deleted file mode 100644 index a350f08088..0000000000 --- a/crates/minimald/build.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::process::Command; -fn main() { - let output = Command::new("git") - .args(["rev-parse", "--short", "HEAD"]) - .output() - .unwrap(); - let git_hash = String::from_utf8(output.stdout).unwrap(); - println!("cargo:rustc-env=GIT_HASH={}", git_hash); - - let is_clean = std::process::Command::new("git") - .args(["status", "--porcelain=v1"]) - .output() - .map(|o| o.stdout.is_empty()) - .unwrap_or(false); - if !is_clean && std::env::var("PROFILE").unwrap() == "release" { - println!("cargo::warning=Building a release binary from an unclean working tree!!"); - println!("cargo::warning=Always build production binaries from a clean checkout."); - } - - println!( - "cargo:rustc-env=LONG_VERSION={} ({}{})", - std::env::var("CARGO_PKG_VERSION").unwrap().as_str(), - if is_clean { "" } else { "dirty " }, - git_hash.strip_suffix("\n").unwrap(), - ); -} diff --git a/crates/minimald/src/main.rs b/crates/minimald/src/main.rs index f56e08fba5..a4e47000ef 100644 --- a/crates/minimald/src/main.rs +++ b/crates/minimald/src/main.rs @@ -25,7 +25,7 @@ const DEFAULT_VSOCK_PORT_BASE: u32 = 2222; const DETACHED_ENV: &str = "MINIMALD_DETACHED"; #[derive(Parser)] -#[command(name = "minimald", version = env!("CARGO_PKG_VERSION"), long_version = env!("LONG_VERSION"))] +#[command(name = "minimald", version = version::VERSION, long_version = version::LONG_VERSION)] #[command(about = "The Minimal daemon")] struct Cli { #[command(subcommand)] diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index 0be129238a..9b9d77375d 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -66,8 +66,8 @@ async fn serve_get_version(c: RuChannel) { let res = GetVersion .handle_channel(c, async |_req| { Ok(GetVersionResponse { - version: env!("CARGO_PKG_VERSION").to_string(), - long_version: env!("LONG_VERSION").to_string(), + version: version::VERSION.to_string(), + long_version: version::LONG_VERSION.to_string(), stdlib_version: stdlib::VERSION.to_string(), }) }) @@ -757,8 +757,8 @@ mod tests { let resp = client.call::(&()).await; - assert_eq!(resp.version, env!("CARGO_PKG_VERSION")); - assert_eq!(resp.long_version, env!("LONG_VERSION")); + assert_eq!(resp.version, version::VERSION); + assert_eq!(resp.long_version, version::LONG_VERSION); assert_eq!(resp.stdlib_version, stdlib::VERSION); } @@ -809,7 +809,7 @@ mod tests { for _ in 0..3 { let mut client = server.connect().await; let resp = client.call::(&()).await; - assert_eq!(resp.version, env!("CARGO_PKG_VERSION")); + assert_eq!(resp.version, version::VERSION); } } diff --git a/crates/minvmd/Cargo.toml b/crates/minvmd/Cargo.toml index 96a5b5b4aa..ddb9ea2cfb 100644 --- a/crates/minvmd/Cargo.toml +++ b/crates/minvmd/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minvmd" -version = "0.0.1" +version.workspace = true edition.workspace = true publish.workspace = true @@ -43,6 +43,7 @@ russh.workspace = true # Canonical state-dir base + provider-instance dir layout (`state`, `sock`, # `volume`). paths.workspace = true +version.workspace = true [dev-dependencies] serial_test.workspace = true diff --git a/crates/minvmd/src/main.rs b/crates/minvmd/src/main.rs index 08d7419b7c..fb36901e83 100644 --- a/crates/minvmd/src/main.rs +++ b/crates/minvmd/src/main.rs @@ -6,7 +6,7 @@ use clap_complete::Shell; use tracing_subscriber::{EnvFilter, fmt, prelude::*}; #[derive(Parser)] -#[command(name = "minvmd", version = env!("CARGO_PKG_VERSION"))] +#[command(name = "minvmd", version = version::VERSION, long_version = version::LONG_VERSION)] #[command( about = "Host daemon that brings up a Linux microVM via libkrun (macOS/HVF or Linux/KVM)" )] diff --git a/crates/mip/Cargo.toml b/crates/mip/Cargo.toml index fd1115f16c..e2676b5778 100644 --- a/crates/mip/Cargo.toml +++ b/crates/mip/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mip" -version = "0.4.1" +version.workspace = true edition.workspace = true publish.workspace = true @@ -42,6 +42,7 @@ anyhow.workspace = true petgraph.workspace = true smallvec.workspace = true +version.workspace = true [dev-dependencies] serial_test.workspace = true diff --git a/crates/mip/build.rs b/crates/mip/build.rs deleted file mode 100644 index a350f08088..0000000000 --- a/crates/mip/build.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::process::Command; -fn main() { - let output = Command::new("git") - .args(["rev-parse", "--short", "HEAD"]) - .output() - .unwrap(); - let git_hash = String::from_utf8(output.stdout).unwrap(); - println!("cargo:rustc-env=GIT_HASH={}", git_hash); - - let is_clean = std::process::Command::new("git") - .args(["status", "--porcelain=v1"]) - .output() - .map(|o| o.stdout.is_empty()) - .unwrap_or(false); - if !is_clean && std::env::var("PROFILE").unwrap() == "release" { - println!("cargo::warning=Building a release binary from an unclean working tree!!"); - println!("cargo::warning=Always build production binaries from a clean checkout."); - } - - println!( - "cargo:rustc-env=LONG_VERSION={} ({}{})", - std::env::var("CARGO_PKG_VERSION").unwrap().as_str(), - if is_clean { "" } else { "dirty " }, - git_hash.strip_suffix("\n").unwrap(), - ); -} diff --git a/crates/mip/src/main.rs b/crates/mip/src/main.rs index 70f63bc8f2..759515f5ab 100644 --- a/crates/mip/src/main.rs +++ b/crates/mip/src/main.rs @@ -44,7 +44,7 @@ mod cmd_remote_build; use cmd_remote_build::{RemoteBuildArgs, cmd_remote_build}; #[derive(Parser)] -#[command(name = "minimal", version = env!("CARGO_PKG_VERSION"), long_version = env!("LONG_VERSION"))] +#[command(name = "minimal", version = version::VERSION, long_version = version::LONG_VERSION)] #[command(about = "The Minimal CLI")] struct Cli { #[command(subcommand)] diff --git a/crates/version/Cargo.toml b/crates/version/Cargo.toml new file mode 100644 index 0000000000..8635d3b776 --- /dev/null +++ b/crates/version/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "version" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[dependencies] diff --git a/crates/version/build.rs b/crates/version/build.rs new file mode 100644 index 0000000000..eed60a963f --- /dev/null +++ b/crates/version/build.rs @@ -0,0 +1,177 @@ +//! Derive the shared human-facing version string for the minimal binaries and +//! expose it as `MINIMAL_VERSION` / `MINIMAL_LONG_VERSION` for `src/lib.rs`. +//! +//! Source of truth is `git describe` against `v*` tags (the SemVer release +//! tags), NOT the Cargo `version` field: +//! +//! - HEAD is exactly `v1.2.3` (clean) -> `1.2.3` +//! - N commits past `v1.2.3` -> `1.2.4-dev..g` +//! - N commits past a pre-release `v1.2.3-rc1` -> `1.2.3-rc1.dev..g` +//! - dirty working tree -> `+dirty` build metadata appended +//! - no `v*` tag reachable, or no git repo -> the crate's Cargo version (fallback) +//! +//! Commits past a release are encoded as a **pre-release** (`-dev..g`), +//! not build metadata, so they order correctly under SemVer 2.0: a build N +//! commits past `v1.2.3` sorts ABOVE `1.2.3` and BELOW the next release. Build +//! metadata (anything after `+`) would instead be ignored in precedence, making +//! every post-release build compare equal to the release. `` is a numeric +//! pre-release identifier, so more commits => higher version. `--match 'v*'` +//! scopes describe to version tags so the many `release-` tags this repo +//! also carries are ignored. + +use std::path::PathBuf; +use std::process::Command; + +fn main() { + emit_rerun_triggers(); + + let cargo_version = std::env::var("CARGO_PKG_VERSION").unwrap(); + let dirty = is_dirty(); + + let (version, long_version) = match describe() { + Some(desc) => { + let v = to_semver(&desc, dirty.unwrap_or(false)); + (v.clone(), v) + } + // No v* tag reachable (or no git): the version is just the Cargo version. + // The long form still carries the commit id when git is available, so a + // dev build off an untagged tree stays identifiable. + None => { + let long = match (short_hash(), dirty) { + (Some(hash), Some(d)) => { + format!("{cargo_version} ({}{hash})", if d { "dirty " } else { "" }) + } + _ => cargo_version.clone(), + }; + (cargo_version, long) + } + }; + + if dirty == Some(true) && std::env::var("PROFILE").as_deref() == Ok("release") { + println!("cargo::warning=Building a release binary from an unclean working tree!!"); + println!("cargo::warning=Always build production binaries from a clean checkout."); + } + + println!("cargo:rustc-env=MINIMAL_VERSION={version}"); + println!("cargo:rustc-env=MINIMAL_LONG_VERSION={long_version}"); +} + +/// Turn `git describe --tags --match 'v*'` output into a SemVer string that +/// orders correctly (see the module docs). +/// +/// - `v1.2.3` -> `1.2.3` +/// - `v1.2.3-5-g86ce5c3a` -> `1.2.4-dev.5.g86ce5c3a` (release base: bump patch) +/// - `v1.2.3-rc1-5-gabc123` -> `1.2.3-rc1.dev.5.gabc123` (pre-release base: extend) +/// +/// A dirty tree appends `+dirty` build metadata. Shapes that don't match the +/// `--g` describe suffix (e.g. a pre-release tag sitting exactly on +/// HEAD) pass through verbatim. +fn to_semver(describe: &str, dirty: bool) -> String { + let core = describe.strip_prefix('v').unwrap_or(describe); + let mut out = match core.rsplitn(3, '-').collect::>()[..] { + [hash, count, base] + if count.bytes().all(|b| b.is_ascii_digit()) + && hash + .strip_prefix('g') + .is_some_and(|h| !h.is_empty() && h.bytes().all(|b| b.is_ascii_hexdigit())) => + { + // A dev build `count` commits past tag `base`. Encode as a pre-release + // so it sorts above `base` but below the next release. + if base.contains('-') { + // `base` already carries a pre-release (e.g. `0.5.0-rc1`); extend it, + // so `0.5.0-rc1.dev.N` > `0.5.0-rc1` and < `0.5.0`. + format!("{base}.dev.{count}.{hash}") + } else if let Some(next) = bump_patch(base) { + // Released tag `X.Y.Z`: this build is heading toward `X.Y.(Z+1)`. + format!("{next}-dev.{count}.{hash}") + } else { + // `base` isn't a plain `X.Y.Z`; still emit a pre-release off it. + format!("{base}-dev.{count}.{hash}") + } + } + _ => core.to_string(), + }; + if dirty { + // Pre-release uses `-`, so build metadata always starts a fresh `+` group. + out.push_str("+dirty"); + } + out +} + +/// Increment the patch of a plain `X.Y.Z` (all-numeric) core, e.g. `1.2.3` -> +/// `1.2.4`. `None` if `v` isn't exactly three numeric dot-separated components. +fn bump_patch(v: &str) -> Option { + let parts: Vec<&str> = v.split('.').collect(); + let [major, minor, patch] = parts[..] else { + return None; + }; + let all_numeric = [major, minor, patch] + .iter() + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())); + let patch: u64 = patch.parse().ok()?; + all_numeric.then(|| format!("{major}.{minor}.{}", patch + 1)) +} + +/// `git describe` scoped to `v*` version tags. `None` on any failure (no matching +/// tag reachable, shallow clone with tags absent, or not a git repo). +fn describe() -> Option { + non_empty_stdout(&["describe", "--tags", "--match", "v*", "--abbrev=8"]) +} + +/// Short HEAD hash, used only to keep untagged dev builds identifiable. +fn short_hash() -> Option { + non_empty_stdout(&["rev-parse", "--short=8", "HEAD"]) +} + +/// `Some(true)`/`Some(false)` when git is available, `None` when it isn't. +fn is_dirty() -> Option { + let out = Command::new("git") + .args(["status", "--porcelain=v1"]) + .output() + .ok()?; + out.status.success().then_some(!out.stdout.is_empty()) +} + +/// Recompute when HEAD moves, a tag is added, or the index changes. Watching the +/// git dir this way keeps the version fresh without rerunning on every build. +/// Caveat: a raw *unstaged* edit touches neither HEAD nor the index, so the +/// `.dirty` marker only refreshes on the next git operation (or source change). +fn emit_rerun_triggers() { + let Some(git_dir) = absolute_git_dir() else { + // No git (e.g. a source tarball): nothing to watch; version is the fallback. + return; + }; + // `refs/tags` (a dir) catches loose tag creation; `packed-refs` catches packed + // tags; `HEAD`/`index` catch checkouts and staging. + for entry in ["HEAD", "index", "packed-refs", "refs/tags"] { + let path = git_dir.join(entry); + if path.exists() { + println!("cargo:rerun-if-changed={}", path.display()); + } + } + // The concrete ref HEAD points at (e.g. refs/heads/main) changes on each commit. + if let Ok(head) = std::fs::read_to_string(git_dir.join("HEAD")) + && let Some(target) = head.strip_prefix("ref:").map(str::trim) + { + let refp = git_dir.join(target); + if refp.exists() { + println!("cargo:rerun-if-changed={}", refp.display()); + } + } +} + +/// Absolute path to the git dir, resolving worktrees and separate git dirs. +fn absolute_git_dir() -> Option { + non_empty_stdout(&["rev-parse", "--absolute-git-dir"]).map(PathBuf::from) +} + +/// Run `git ` and return trimmed stdout, or `None` on failure/empty output. +fn non_empty_stdout(args: &[&str]) -> Option { + let out = Command::new("git").args(args).output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8(out.stdout).ok()?; + let s = s.trim(); + (!s.is_empty()).then(|| s.to_string()) +} diff --git a/crates/version/src/lib.rs b/crates/version/src/lib.rs new file mode 100644 index 0000000000..f43ac582b4 --- /dev/null +++ b/crates/version/src/lib.rs @@ -0,0 +1,11 @@ +//! Shared version identity for the minimal binaries (`min`, `mip`, `minimald`, +//! `minvmd`), derived at build time from `git describe` against `v*` tags so all +//! four report one version. See `build.rs` for the exact scheme. + +/// Compact version — a SemVer string such as `1.2.3` or `1.2.4-dev.5.g86ce5c3a`, +/// or the crate's Cargo version when no `v*` tag is reachable. Shown by `-V`. +pub const VERSION: &str = env!("MINIMAL_VERSION"); + +/// Verbose version shown by `--version`; carries the commit id for untagged dev +/// builds. Equal to [`VERSION`] once a `v*` tag is reachable. +pub const LONG_VERSION: &str = env!("MINIMAL_LONG_VERSION");