Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(version): tolerate missing VERGEN_GIT_DESCRIBE on crates.io builds (#3124)
Worktrunk Botaa1a5cd98ba4
diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yamlindex 02a77b19f..89e76ffa4 100644--- a/.github/workflows/nightly.yaml+++ b/.github/workflows/nightly.yaml@@ -7,6 +7,7 @@ name: nightly# - check-unused-dependencies: cargo-udeps on nightly toolchain# - minimal-versions: cargo check against minimum-version dep resolution# - nix-flake: nix flake check (packaging-environment bugs, motivated by #2624)+# - crate-build: build the crates.io archive with no `.git` (faithful #3123 repro)## Runs daily on cron, on demand via workflow_dispatch, on pushes to main that# touch dependency or toolchain files, and on PRs that either (a) touch the@@ -304,6 +305,29 @@ jobs:- name: cargo checkrun: cargo check --workspace --all-targets+ crate-build:+ # Faithful end-to-end guard for #3123: build the crates.io *source archive*+ # in a directory with no ancestor `.git` and confirm `wt` both compiles and+ # reports the cargo version (the `option_env!("VERGEN_GIT_DESCRIBE")`+ # fallback). ci.yaml's fast `vergen_env_vars_are_read_optionally` guard+ # catches the mechanism (`env!` vs `option_env!`) on every PR by scanning+ # source; this reproduces the actual `cargo install` condition β a full+ # from-scratch build (~minutes), which is why it's `#[ignore]`d and run here+ # via `--ignored`. A regression that an in-tree build can't see (git+ # describe ascends to the outer repo) surfaces only on this no-git build.+ needs: gate+ if: needs.gate.outputs.run == 'true'+ runs-on: ubuntu-24.04+ steps:+ - name: π Checkout code+ uses: actions/checkout@v6++ - name: π° Cache+ uses: Swatinem/rust-cache@v2++ - name: π§ͺ Build crates.io archive without .git+ run: cargo test --test integration crate_io_archive_builds_and_versions_without_git -- --ignored+nix-flake:# Build and test under the nix sandbox so packaging-environment bugs# surface before a release / nixpkgs maintainer hits them. See #2624 for@@ -341,6 +365,7 @@ jobs:- check-unused-dependencies- minimal-versions- nix-flake+ - crate-buildif: always() && contains(needs.*.result, 'failure') && github.repository_owner == 'max-sixty' && github.event_name == 'schedule'runs-on: ubuntu-24.04permissions:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 79baa247c..db10fc762 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -165,17 +165,30 @@ fn apply_help_template_recursive(mut cmd: Command, path: &str) -> Command {pub(crate) fn version_str() -> &'static str {static VERSION: OnceLock<String> = OnceLock::new();VERSION.get_or_init(|| {- let git_version = env!("VERGEN_GIT_DESCRIBE");- let cargo_version = env!("CARGO_PKG_VERSION");-- if git_version.contains("IDEMPOTENT") {- cargo_version.to_string()- } else {- git_version.to_string()- }+ // `option_env!`, not `env!`: when building from the crates.io package+ // archive there is no git worktree, so the build script can't set+ // `VERGEN_GIT_DESCRIBE` and the variable is undefined at compile time.+ // `env!` fails to compile in that case (see #3123); `option_env!`+ // yields `None` and we fall back to the cargo package version.+ resolve_version(+ option_env!("VERGEN_GIT_DESCRIBE"),+ env!("CARGO_PKG_VERSION"),+ )})}+/// Choose between the git-describe version and the cargo package version.+///+/// Falls back to `cargo_version` when git describe is unavailable (`None`,+/// from a non-git build) or idempotent (vergen's placeholder for a+/// non-reproducible build).+fn resolve_version(git_version: Option<&str>, cargo_version: &str) -> String {+ match git_version {+ Some(git_version) if !git_version.contains("IDEMPOTENT") => git_version.to_string(),+ _ => cargo_version.to_string(),+ }+}+/// Output format for commands with text + JSON modes (e.g., `wt switch`).#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub(crate) enum SwitchFormat {@@ -2187,3 +2200,32 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge#[command(external_subcommand)]Custom(Vec<OsString>),}++#[cfg(test)]+mod tests {+ use super::resolve_version;++ #[test]+ fn resolve_version_uses_git_describe_when_available() {+ assert_eq!(+ resolve_version(Some("v0.8.5-3-gabcdef"), "0.8.5"),+ "v0.8.5-3-gabcdef"+ );+ }++ #[test]+ fn resolve_version_falls_back_when_git_describe_idempotent() {+ // vergen emits an IDEMPOTENT placeholder for non-reproducible builds.+ assert_eq!(+ resolve_version(Some("VERGEN_IDEMPOTENT_OUTPUT"), "0.8.5"),+ "0.8.5"+ );+ }++ #[test]+ fn resolve_version_falls_back_when_git_describe_absent() {+ // Building from the crates.io package archive: no git worktree, so the+ // build script never sets VERGEN_GIT_DESCRIBE (#3123).+ assert_eq!(resolve_version(None, "0.59.0"), "0.59.0");+ }+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 99465e22f..940880454 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -67,3 +67,4 @@ pub mod switch;pub mod switch_picker;pub mod switch_picker_dry_run;pub mod user_hooks;+pub mod version_build;diff --git a/tests/integration_tests/version_build.rs b/tests/integration_tests/version_build.rsnew file mode 100644index 000000000..da9179e79--- /dev/null+++ b/tests/integration_tests/version_build.rs@@ -0,0 +1,169 @@+//! Guard test: build-script env vars must be read with `option_env!`, never `env!`+//!+//! `cargo install worktrunk` builds the crates.io source archive, which has no+//! `.git`. The `vergen_gitcl` build script can only set `VERGEN_GIT_DESCRIBE`+//! when `git describe` succeeds, so on that archive the variable is undefined+//! at compile time.+//!+//! `env!("VERGEN_GIT_DESCRIBE")` then **fails to compile** ("environment+//! variable not defined at compile time"), which broke `cargo install`+//! (#3123). `option_env!` yields `None` instead, letting `version_str()` fall+//! back to the cargo package version.+//!+//! This couldn't be caught by a build test that compiles inside the repo:+//! `git describe` searches ancestors, so a `cargo package` / `cargo publish`+//! verify build run from the worktree finds the *outer* `.git` and succeeds β+//! exactly why the broken release shipped. The failure only reproduces where+//! no ancestor is a git repo (a user's `~/.cargo/registry`). Rather than+//! recreate that (slow, requires building outside the tree), this guards the+//! mechanism directly: forbid `env!` on any build-script-provided `VERGEN_*`+//! variable, since none are guaranteed to exist on the crates.io archive.++use std::fs;+use std::path::Path;+use std::process::Command;++use path_slash::PathExt as _;++#[test]+fn vergen_env_vars_are_read_optionally() {+ let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");++ let mut violations = Vec::new();+ scan_directory(&src_dir, &src_dir, &mut violations);++ assert!(+ violations.is_empty(),+ "Found `env!` on a build-script `VERGEN_*` variable:\n\n{}\n\n\+ These variables are absent when building the crates.io source archive \+ (no `.git`), so `env!` fails to compile and breaks `cargo install` \+ (#3123). Use `option_env!` and fall back to a default instead.",+ violations.join("\n")+ );+}++fn scan_directory(dir: &Path, src_dir: &Path, violations: &mut Vec<String>) {+ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ scan_directory(&path, src_dir, violations);+ } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {+ check_file(&path, src_dir, violations);+ }+ }+}++fn check_file(path: &Path, src_dir: &Path, violations: &mut Vec<String>) {+ let Ok(contents) = fs::read_to_string(path) else {+ return;+ };+ let relative = path.strip_prefix(src_dir).unwrap_or(path).to_slash_lossy();++ for (i, line) in contents.lines().enumerate() {+ if has_bare_env_vergen(line) {+ violations.push(format!("{relative}:{}: {}", i + 1, line.trim()));+ }+ }+}++/// True if the line reads a `VERGEN_*` variable with `env!` but not the safe+/// `option_env!` form. Matching `env!("VERGEN_` alone would also flag every+/// `option_env!("VERGEN_` since it ends in that substring, so we require the+/// `env!` to not be the tail of `option_env!`.+fn has_bare_env_vergen(line: &str) -> bool {+ line.match_indices("env!(\"VERGEN_")+ .any(|(idx, _)| !line[..idx].ends_with("option_"))+}++/// End-to-end reproduction of #3123: build the *actual* crates.io source+/// archive in a directory with no ancestor `.git`, and confirm the `wt` binary+/// both compiles and reports the cargo package version (the fallback).+///+/// The sibling `vergen_env_vars_are_read_optionally` guard is fast and runs on+/// every PR, but it only checks the *mechanism* (`env!` vs `option_env!`) by+/// scanning source. This test is the faithful integration version the+/// maintainer asked for: it packages the crate exactly as `cargo publish`+/// would, extracts it where `git describe` can find no repository, and builds+/// it β the precise condition of a user's `~/.cargo/registry`. Before the fix+/// this failed to *compile* (`VERGEN_GIT_DESCRIBE` not defined); after it, the+/// build succeeds and `wt --version` falls back to `CARGO_PKG_VERSION`.+///+/// `#[ignore]` because it runs a full from-scratch crate build (several+/// minutes, downloads every dependency). CI runs it in the `crate-build`+/// nightly job via `cargo test β¦ -- --ignored`. Linux/macOS only β it shells+/// out to `tar` and relies on `GIT_CEILING_DIRECTORIES` path semantics.+#[test]+#[ignore = "slow: full from-scratch crate build; run in the nightly workflow via --ignored"]+fn crate_io_archive_builds_and_versions_without_git() {+ let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));+ // `CARGO` points at the cargo that launched the test; fall back for manual+ // `--ignored` runs that don't set it.+ let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());+ let pkg_version = env!("CARGO_PKG_VERSION");++ // 1. Produce the crates.io source archive exactly as `cargo publish` does.+ // `--no-verify`: the default verify build compiles *in-tree*, where+ // `git describe` ascends to the outer repo's `.git` and masks the bug β+ // the very reason the broken release shipped. We run our own no-git+ // build below instead. `--allow-dirty`: tolerate local edits while+ // iterating on the branch.+ let status = Command::new(&cargo)+ .args(["package", "-p", "worktrunk", "--no-verify", "--allow-dirty"])+ .current_dir(manifest_dir)+ .status()+ .expect("spawn cargo package");+ assert!(status.success(), "cargo package failed");++ let crate_file = manifest_dir+ .join("target/package")+ .join(format!("worktrunk-{pkg_version}.crate"));+ assert!(crate_file.exists(), "expected archive at {crate_file:?}");++ // 2. Extract into a temp dir that has no ancestor `.git`.+ let temp = tempfile::tempdir().expect("create tempdir");+ let untar = Command::new("tar")+ .arg("xzf")+ .arg(&crate_file)+ .arg("-C")+ .arg(temp.path())+ .status()+ .expect("spawn tar");+ assert!(untar.success(), "tar extraction failed");+ let extracted = temp.path().join(format!("worktrunk-{pkg_version}"));+ assert!(extracted.is_dir(), "extracted dir missing: {extracted:?}");++ // 3. Build `wt` (default features β `cli` is on) with no `.git` reachable.+ // `GIT_CEILING_DIRECTORIES` stops `git describe` from ascending past the+ // temp dir, so the build sees the same no-repository state as+ // `~/.cargo/registry` even if the temp root happened to sit under one.+ // `VERGEN_GIT_DESCRIBE` is removed so a packager-style override (the+ // workaround Homebrew/conda-forge/nix all ship) can't mask the failure.+ let build = Command::new(&cargo)+ .args(["build", "--bin", "wt"])+ .current_dir(&extracted)+ .env("GIT_CEILING_DIRECTORIES", temp.path())+ .env_remove("VERGEN_GIT_DESCRIBE")+ .status()+ .expect("spawn cargo build");+ assert!(+ build.success(),+ "building the crates.io archive without `.git` failed (this is #3123)"+ );++ // 4. The built binary must report the cargo package version β proof the+ // `option_env!` fallback fired rather than baking a git-describe string.+ let wt = extracted.join("target/debug/wt");+ let version = Command::new(&wt)+ .arg("--version")+ .output()+ .expect("spawn wt --version");+ assert!(version.status.success(), "`wt --version` exited non-zero");+ let stdout = String::from_utf8_lossy(&version.stdout);+ assert!(+ stdout.contains(pkg_version),+ "expected `wt --version` to fall back to {pkg_version}, got: {stdout:?}"+ );+}