diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index 8983b9c8d6..c1e78c550a 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -1,15 +1,21 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. //! -//! On every other target this does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A +//! On every other target the Windows part does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A //! missing resource compiler is a warning, so a cross-compile from macOS or Linux still links, //! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a //! build error. +#[path = "../photocraft/git_checkout.rs"] +mod git_checkout; + /// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272). fn main() -> std::io::Result<()> { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=../photocraft/git_checkout.rs"); + git_checkout::emit(); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return Ok(()); } diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index 6e21c2ac44..5113c2c04a 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -3,6 +3,9 @@ fn main() { // May re-execute this process with glibc tuned to return freed document memory (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` (build.rs, #5247). Before `run`: + // clap reads the version string once. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap, // not panic before anything is printed (issue #1108). let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index a4bcba0756..f49abe6a17 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -1,9 +1,12 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft.exe`. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a +//! On every other target the Windows part does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +mod git_checkout; + #[path = "src/build_channel.rs"] mod build_channel; @@ -27,6 +30,8 @@ fn main() { println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=git_checkout.rs"); + git_checkout::emit(); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION"); let built_version = if nightly { match std::env::var("PHOTOCRAFT_VERSION") { diff --git a/apps/photocraft/git_checkout.rs b/apps/photocraft/git_checkout.rs new file mode 100644 index 0000000000..38cfa185ec --- /dev/null +++ b/apps/photocraft/git_checkout.rs @@ -0,0 +1,71 @@ +//! Build-script helper shared by the `photocraft` and `photocraft-cli` binaries: the git commit +//! of the source checkout, so a plain `cargo build` from git reports `0.8.2 (dev build, 6f8505421)` +//! (#5247). Release builds set `PHOTOCRAFT_BUILD_SHA` instead and are left alone; without git or +//! outside a checkout of this workspace (a source tarball) nothing is set and the build stays +//! `(dev build)`. The binaries pass the value to `photocraft_engine::build_info::set_checkout`. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Runs `git ` in `dir`; its trimmed output when it succeeds. +fn git(dir: &Path, args: &[&str]) -> Option { + let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?; + let s = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (out.status.success() && !s.is_empty()).then_some(s) +} + +/// Emits `PHOTOCRAFT_CHECKOUT_SHA` for the crate whose build script calls it. +pub fn emit() { + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_SHA"); + if std::env::var("PHOTOCRAFT_BUILD_SHA").is_ok_and(|s| !s.trim().is_empty()) { + return; + } + let Some(manifest) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else { return }; + // apps/ → the workspace root. A tarball unpacked inside some other repository must not + // report that repository's commit. + let Some(root) = manifest.parent().and_then(Path::parent).and_then(|r| r.canonicalize().ok()) else { return }; + let Some(top) = git(&root, &["rev-parse", "--show-toplevel"]).and_then(|t| PathBuf::from(t).canonicalize().ok()) else { return }; + if top != root { + return; + } + // Watch before asking for the commit: on an unborn branch `rev-parse HEAD` fails, and the + // first commit must still re-run this script. + for path in watch_paths(&root) { + println!("cargo:rerun-if-changed={}", path.display()); + } + let Some(sha) = git(&root, &["rev-parse", "HEAD"]) else { return }; + println!("cargo:rustc-env=PHOTOCRAFT_CHECKOUT_SHA={sha}"); +} + +/// The git files whose change means HEAD moved: a commit or checkout changes HEAD (detached) or the +/// branch's ref. Cargo treats a watched path that does not exist as always changed (it re-runs the +/// build script and recompiles the binary on every build), so only existing paths are returned. +pub(crate) fn watch_paths(root: &Path) -> Vec { + let mut paths = Vec::new(); + if let Some(dir) = git(root, &["rev-parse", "--absolute-git-dir"]) { + let head = Path::new(&dir).join("HEAD"); + paths.extend(watched(&head, &head)); + } + let Some(common) = git(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"]) else { return paths }; + let common = Path::new(&common); + if git(root, &["rev-parse", "--show-ref-format"]).as_deref() == Some("reftable") { + // Every ref update in a reftable repository rewrites the table stack. + let tables = common.join("reftable").join("tables.list"); + paths.extend(watched(&tables, &tables)); + return paths; + } + if let Some(head_ref) = git(root, &["symbolic-ref", "-q", "HEAD"]) { + // A packed or unborn branch has no loose ref file; the first commit on it creates one, + // which changes the nearest existing directory above it under `refs/`. + paths.extend(watched(&common.join(&head_ref), &common.join("refs"))); + } + let packed = common.join("packed-refs"); + paths.extend(watched(&packed, &packed)); + paths +} + +/// The path Cargo should watch for `path`: `path` itself when it exists, else its nearest existing +/// ancestor that is still inside `stop`; `None` when neither exists. +pub(crate) fn watched(path: &Path, stop: &Path) -> Option { + path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf) +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 85f44aa191..b8e0a15926 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -495,6 +495,8 @@ fn main() -> eframe::Result { // Before anything starts a thread: may re-execute this process with glibc tuned to return // the memory of closed documents (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` and About (build.rs, #5247). + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // Then, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); diff --git a/apps/photocraft/tests/it/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs index a0d8377638..116e1440c8 100644 --- a/apps/photocraft/tests/it/command_line_usage.rs +++ b/apps/photocraft/tests/it/command_line_usage.rs @@ -88,6 +88,9 @@ fn help_wins_over_later_arguments() { fn version_prints_the_long_version() { let Run { status, stdout, .. } = run_photocraft(&["--version", "--safegpu"]); assert_eq!(status.code(), Some(0)); + // The binary records its checkout's commit at startup (#5247); the build script hands the + // same value to this test. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); assert_eq!(stdout, format!("photocraft {}\n", photocraft_engine::build_info::long_version())); } diff --git a/apps/photocraft/tests/it/git_checkout.rs b/apps/photocraft/tests/it/git_checkout.rs new file mode 100644 index 0000000000..8b05503e78 --- /dev/null +++ b/apps/photocraft/tests/it/git_checkout.rs @@ -0,0 +1,152 @@ +//! The build-script helper `git_checkout.rs` (#5247): Cargo re-runs a build script on every build +//! when a `rerun-if-changed` path is missing, so only existing paths may be watched. + +#[allow(dead_code)] +#[path = "../../git_checkout.rs"] +mod helper; + +use helper::{watch_paths, watched}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-git-checkout-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +#[test] +fn an_existing_path_is_watched_itself() { + let git = scratch("exists"); + let packed = git.join("packed-refs"); + fs::write(&packed, "").expect("write"); + assert_eq!(watched(&packed, &packed), Some(packed.clone())); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_missing_file_with_no_room_to_climb_is_not_watched() { + let git = scratch("missing"); + let packed = git.join("packed-refs"); + assert_eq!(watched(&packed, &packed), None); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_packed_branch_watches_the_nearest_existing_ref_directory() { + let git = scratch("packed-branch"); + let refs = git.join("refs"); + fs::create_dir_all(refs.join("heads")).expect("refs/heads"); + // `refs/heads/fix/5247` with no `fix/` directory yet: watch `refs/heads`. + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads"))); + // Once the loose ref exists it is watched directly. + fs::create_dir_all(refs.join("heads/fix")).expect("refs/heads/fix"); + fs::write(refs.join("heads/fix/5247"), "abc\n").expect("loose ref"); + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads/fix/5247"))); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn the_search_never_leaves_the_stop_directory() { + let git = scratch("stop"); + // `refs/` itself is missing: its parent (the git dir) exists but is outside `stop`. + assert_eq!(watched(&git.join("refs/heads/main"), &git.join("refs")), None); + let _ = fs::remove_dir_all(&git); +} + +/// `git` with the variables that point it at another repository or pick its ref format removed, +/// so a fixture is the repository in its own directory whatever the environment says. +fn git() -> Command { + let mut c = Command::new("git"); + for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_DEFAULT_REF_FORMAT"] { + c.env_remove(var); + } + c +} + +/// `git init` in a fresh scratch directory with `args`; `None` when this git cannot do it. The +/// files ref format unless `args` ask for another, whatever `init.defaultRefFormat` says (older +/// git ignores the setting). +fn init(name: &str, args: &[&str]) -> Option { + let dir = scratch(name); + let mut cmd = git(); + if !args.iter().any(|a| a.starts_with("--ref-format")) { + cmd.args(["-c", "init.defaultRefFormat=files"]); + } + let ok = cmd.arg("init").arg("-q").args(args).arg(&dir).status().is_ok_and(|s| s.success()); + if ok { + dir.canonicalize().ok() + } else { + let _ = fs::remove_dir_all(&dir); + None + } +} + +fn git_dir(root: &Path) -> PathBuf { + root.join(".git") +} + +/// `watch_paths(root)` canonicalised, so git's `C:/…` output compares equal to the scratch path on +/// Windows and `/var` to `/private/var` on macOS. Panics if any watched path is missing. +fn watched_in(root: &Path) -> Vec { + watch_paths(root).iter().map(|p| p.canonicalize().unwrap_or_else(|e| panic!("{} is watched but missing: {e}", p.display()))).collect() +} + +#[test] +fn an_unborn_branch_still_watches_head_and_the_ref_directory() { + // Before the first commit `rev-parse HEAD` fails; the first commit creates refs/heads/main, + // which must re-run the build script. + let Some(root) = init("unborn", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + assert!(paths.iter().any(|p| p.starts_with(git.join("refs"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_reftable_checkout_watches_the_table_stack() { + // Branch updates in a reftable repository rewrite reftable/tables.list, not a loose ref or + // packed-refs. Needs git 2.45 or newer; older git cannot create the repository. + let Some(root) = init("reftable", &["-b", "main", "--ref-format=reftable"]) else { + eprintln!("git without reftable support, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("reftable").join("tables.list")), "{paths:?}"); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_files_checkout_watches_the_branch_ref_and_not_a_table_stack() { + let Some(root) = init("files", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + fs::write(git_dir(&root).join("packed-refs"), "").expect("packed-refs"); + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("packed-refs")), "{paths:?}"); + assert!(!paths.iter().any(|p| p.starts_with(git.join("reftable"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn outside_a_repository_nothing_is_watched() { + let dir = scratch("no-repo"); + // GIT_CEILING_DIRECTORIES is not set here, so a scratch dir inside a checkout would find it; + // the system temp dir is not inside one on CI or on a developer machine. + if git().arg("-C").arg(&dir).args(["rev-parse", "--git-dir"]).output().is_ok_and(|o| o.status.success()) { + eprintln!("temp dir is inside a git repository, skipped"); + } else { + assert!(watched_in(&dir).is_empty()); + } + let _ = fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs index 73bea9196a..f0248ad210 100644 --- a/apps/photocraft/tests/it/main.rs +++ b/apps/photocraft/tests/it/main.rs @@ -2,6 +2,7 @@ mod command_line_usage; mod control_exit_code; +mod git_checkout; mod startup_without_display; /// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. diff --git a/crates/engine-core/src/build_info.rs b/crates/engine-core/src/build_info.rs index 3ad4da1aba..76267af92a 100644 --- a/crates/engine-core/src/build_info.rs +++ b/crates/engine-core/src/build_info.rs @@ -8,7 +8,11 @@ //! - `PHOTOCRAFT_BUILD_DATE`: the build date, conventionally `YYYY-MM-DD` //! //! Without them (a plain `cargo build`) the build reports itself as a dev build. Nothing here -//! shells out to git, so builds work from a source tarball and for wasm. +//! shells out to git, so builds work from a source tarball and for wasm. The desktop and CLI +//! binaries' build scripts do read the commit of a git checkout and hand it over with +//! [`set_checkout`] at startup, so a dev build from git says which commit it is +//! (`0.1.0 (dev build, 3f2a9c1d0)`); keeping it out of this crate means a commit doesn't rebuild +//! the engine. /// The workspace version, such as `0.1.0` or `0.2.0-rc.1`. pub const VERSION: &str = match option_env!("PHOTOCRAFT_OVERRIDE_VERSION") { @@ -31,12 +35,30 @@ pub fn build_date() -> Option<&'static str> { /// The commit shortened for display. pub fn short_sha() -> Option<&'static str> { - git_sha().map(|s| &s[..s.len().min(9)]) + git_sha().map(shorten) } -/// `0.1.0 (3f2a9c1d0, 2026-10-01)`, or `0.1.0 (dev build)` without provenance. +fn shorten(sha: &str) -> &str { + sha.get(..9).unwrap_or(sha) +} + +static CHECKOUT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Records the git commit of the checkout a dev build was compiled from (the binaries' build +/// scripts read it; `None` or empty from a source tarball). Only the first call counts. +pub fn set_checkout(sha: Option<&str>) { + if let Some(sha) = sha.map(str::trim).filter(|s| !s.is_empty()) { + let _ = CHECKOUT.set(sha.to_string()); + } +} + +/// `0.1.0 (3f2a9c1d0, 2026-10-01)`; a dev build `0.1.0 (dev build, 3f2a9c1d0)` from a git +/// checkout, or `0.1.0 (dev build)` without provenance. pub fn long_version() -> String { - format_long(VERSION, short_sha(), build_date()) + match short_sha() { + Some(s) => format_long(VERSION, Some(s), build_date()), + None => format_dev(VERSION, CHECKOUT.get().map(|s| shorten(s)), build_date()), + } } /// [`long_version`] worked out once, for a `&'static str` such as clap's `version`. @@ -54,6 +76,14 @@ fn format_long(version: &str, sha: Option<&str>, date: Option<&str>) -> String { } } +/// A build without `PHOTOCRAFT_BUILD_SHA`: the checkout's commit, when known, marked as a dev build. +fn format_dev(version: &str, checkout: Option<&str>, date: Option<&str>) -> String { + match checkout { + Some(c) => format!("{version} (dev build, {c})"), + None => format_long(version, None, date), + } +} + #[cfg(test)] mod tests { use super::*; @@ -64,6 +94,11 @@ mod tests { assert_eq!(format_long("1.2.3", Some("abc"), None), "1.2.3 (abc)"); assert_eq!(format_long("1.2.3", None, Some("2026-10-01")), "1.2.3 (2026-10-01)"); assert_eq!(format_long("1.2.3-rc.1", None, None), "1.2.3-rc.1 (dev build)"); + // #5247: a dev build from a git checkout names its commit. + assert_eq!(format_dev("0.8.2", Some(shorten("6f8505421abcdef")), None), "0.8.2 (dev build, 6f8505421)"); + assert_eq!(format_dev("0.8.2", None, None), "0.8.2 (dev build)"); + assert_eq!(format_dev("0.8.2", None, Some("2026-10-01")), "0.8.2 (2026-10-01)"); + assert_eq!(shorten("abc"), "abc"); } #[test] diff --git a/docs/releasing.md b/docs/releasing.md index 24da185b40..eda7a7fd30 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -128,7 +128,8 @@ are recorded in this procedure. Every binary reports its version, the commit and the build date: `photocraft --version`, `photocraft-cli --version`, and *Help › About PhotoCraft*. CI sets `PHOTOCRAFT_BUILD_SHA` and `PHOTOCRAFT_BUILD_DATE`, and `crates/engine-core/src/build_info.rs` reads them at compile time. A plain -`cargo build` doesn't set them and reports `0.2.0 (dev build)`. +`cargo build` doesn't set them and reports `0.2.0 (dev build)`; from a git checkout the desktop and CLI +build scripts add the commit, `0.2.0 (dev build, 3f2a9c1d0)` (a source tarball stays `(dev build)`). Every desktop build job (macOS, Windows, Linux, FreeBSD) also checks out [craft-fonts](https://github.com/storytold/craft-fonts) at the `craft-fonts-ref` commit in `.github/workflows/release.yml` and builds with `CRAFT_FONTS_DIR` and