Skip to content

Commit 1bc6da6

Browse files
committed
fix(build): invalidate Git versions and respect archive ownership
Track packed and loose Git refs across linked worktrees and preserve source archive version ownership. Keep version refresh independent of reflog availability. Closes #4186 Signed-off-by: Shiju <[email protected]>
1 parent c92c2c7 commit 1bc6da6

4 files changed

Lines changed: 468 additions & 77 deletions

File tree

‎CONTRIBUTING.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,11 @@ openshell sandbox create -- codex
322322

323323
### Rust build cache
324324

325+
The `openshell-core` build script embeds a version derived from Git. It
326+
reruns when HEAD, local branches or tags change, in clones and linked
327+
worktrees, even if no Rust source changed. Source archives without Git
328+
metadata use the package version.
329+
325330
Mise preserves an existing `SCCACHE_DIR` so each environment can choose where
326331
to store compiler cache entries. When `SCCACHE_DIR` is unset, OpenShell uses
327332
the worktree-local `.cache/sccache` directory. To make cache entries available

‎crates/openshell-core/build.rs‎

Lines changed: 5 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use std::env;
55
use std::path::{Path, PathBuf};
66

7+
mod build_git;
78
mod build_version;
89

910
const PROTO_REL: &str = "../../proto";
@@ -35,11 +36,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
3536
// Docker/CI builds where .git is absent, this silently does nothing and
3637
// the binary falls back to CARGO_PKG_VERSION (which is already sed-patched
3738
// by the build pipeline).
38-
for path in git_rerun_paths() {
39-
println!("cargo:rerun-if-changed={}", path.display());
40-
}
41-
42-
if let Some(version) = git_version() {
39+
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
40+
let source_root = manifest_dir.ancestors().nth(2).unwrap_or(&manifest_dir);
41+
build_git::emit_rerun_if_changed(source_root);
42+
if let Some(version) = build_git::version(source_root) {
4343
println!("cargo:rustc-env=OPENSHELL_GIT_VERSION={version}");
4444
}
4545

@@ -59,7 +59,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
5959
None
6060
};
6161

62-
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
6362
let proto_root = manifest_dir.join(PROTO_REL);
6463
let mut proto_files = Vec::new();
6564
collect_proto_files(&proto_root, &mut proto_files)?;
@@ -104,74 +103,3 @@ fn collect_proto_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()
104103
}
105104
Ok(())
106105
}
107-
108-
/// Git metadata files whose changes affect [`git_version`].
109-
///
110-
/// In a linked worktree `.git` is a file, so `HEAD` and `logs/HEAD` live in the
111-
/// per-worktree git dir while branch and tag refs live in the common git dir. Cargo treats a
112-
/// missing `rerun-if-changed` path as always stale, so only existing paths are
113-
/// returned. Without git metadata nothing is returned.
114-
fn git_rerun_paths() -> Vec<PathBuf> {
115-
let resolve = |args: &[&str]| {
116-
let dir = PathBuf::from(git_output(args)?);
117-
// Relative output is relative to the build script's working directory.
118-
Some(env::current_dir().ok()?.join(dir))
119-
};
120-
let mut paths = Vec::new();
121-
if let Some(git_dir) = resolve(&["rev-parse", "--git-dir"]) {
122-
paths.push(git_dir.join("HEAD"));
123-
paths.push(git_dir.join("logs/HEAD"));
124-
}
125-
if let Some(common_dir) = resolve(&["rev-parse", "--git-common-dir"]) {
126-
paths.push(common_dir.join("refs/tags"));
127-
paths.push(common_dir.join("packed-refs"));
128-
// A new worktree has no `logs/HEAD` until its first ref update, so also
129-
// watch the checked-out branch ref, which moves on every commit.
130-
if let Some(branch) = git_output(&["symbolic-ref", "-q", "HEAD"]) {
131-
paths.push(common_dir.join(branch));
132-
}
133-
}
134-
paths.retain(|path| path.exists());
135-
paths
136-
}
137-
138-
/// Derive the release or development version from git metadata.
139-
///
140-
/// Implements the "guess-next-dev" convention used by the release pipeline
141-
/// (`tasks/scripts/release.py`): exact stable and prerelease tags retain their
142-
/// version. Otherwise, the latest merged stable release gets a patch bump and
143-
/// `-dev.<N>+g<sha>` is appended.
144-
///
145-
/// Examples:
146-
/// on tag v0.1.0-pre.1 → "0.1.0-pre.1"
147-
/// 3 commits past v0.0.3 → "0.0.4-dev.3+g2bf9969ab"
148-
///
149-
/// Returns `None` when git metadata cannot be read.
150-
fn git_version() -> Option<String> {
151-
let exact_tags = git_output(&["tag", "--points-at", "HEAD"])?;
152-
if let Some(version) = build_version::exact_release_version(exact_tags.lines()) {
153-
return Some(version);
154-
}
155-
156-
let merged_tags = git_output(&["tag", "--merged", "HEAD", "--list", "v*.*.*"])?;
157-
let latest_tag = build_version::latest_stable_tag(merged_tags.lines());
158-
let revision_range = latest_tag
159-
.as_deref()
160-
.map_or_else(|| "HEAD".to_string(), |tag| format!("{tag}..HEAD"));
161-
let distance = git_output(&["rev-list", "--count", &revision_range])?
162-
.parse()
163-
.ok()?;
164-
let sha = git_output(&["rev-parse", "--short=9", "HEAD"])?;
165-
166-
build_version::next_dev_version(latest_tag.as_deref(), distance, &sha)
167-
}
168-
169-
fn git_output(args: &[&str]) -> Option<String> {
170-
let output = std::process::Command::new("git").args(args).output().ok()?;
171-
if !output.status.success() {
172-
return None;
173-
}
174-
String::from_utf8(output.stdout)
175-
.ok()
176-
.map(|output| output.trim().to_string())
177-
}

‎crates/openshell-core/build_git.rs‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
use std::collections::BTreeSet;
5+
use std::path::Path;
6+
use std::process::Command;
7+
8+
use crate::build_version;
9+
10+
/// Track Git's resolved metadata, including creation of previously packed refs.
11+
///
12+
/// `source_root` is the source checkout. Git metadata is used only when that
13+
/// directory has its own `.git`, so an archive nested in another repository
14+
/// neither adopts nor watches that repository.
15+
pub fn emit_rerun_if_changed(source_root: &Path) {
16+
// Ref directories must be watched whole: a packed branch has no loose file
17+
// until its next update. Watching only existing individual refs misses it.
18+
// Only heads and tags feed the version; remotes and stash would rebuild
19+
// on every fetch or stash. reftable/ covers that ref backend.
20+
let mut paths = BTreeSet::new();
21+
for name in [
22+
"HEAD",
23+
"refs/heads",
24+
"refs/tags",
25+
"packed-refs",
26+
"reftable",
27+
"shallow",
28+
] {
29+
let Some(path) = git_output(source_root, &["rev-parse", "--git-path", name]) else {
30+
continue;
31+
};
32+
paths.insert(source_root.join(path));
33+
}
34+
// A linked worktree's reftable holds its private refs, including HEAD.
35+
// Shared branches and tags live in the common directory's separate table.
36+
if let Some(common_dir) = git_output(source_root, &["rev-parse", "--git-common-dir"]) {
37+
paths.insert(source_root.join(common_dir).join("reftable"));
38+
}
39+
for path in paths {
40+
// Missing Git metadata is normal in archives and container builds.
41+
// Cargo reruns indefinitely for a watched file that never exists.
42+
if path.exists() {
43+
println!("cargo:rerun-if-changed={}", path.display());
44+
}
45+
}
46+
}
47+
48+
/// Derive the release or development version from git metadata.
49+
///
50+
/// Implements the "guess-next-dev" convention used by the release pipeline
51+
/// (`tasks/scripts/release.py`): exact stable and prerelease tags retain their
52+
/// version. Otherwise, the latest merged stable release gets a patch bump and
53+
/// `-dev.<N>+g<sha>` is appended.
54+
///
55+
/// Examples:
56+
/// on tag v0.1.0-pre.1 → "0.1.0-pre.1"
57+
/// 3 commits past v0.0.3 → "0.0.4-dev.3+g2bf9969ab"
58+
///
59+
/// Returns `None` when `source_root` has no `.git` of its own or its metadata
60+
/// cannot be read.
61+
pub fn version(source_root: &Path) -> Option<String> {
62+
let exact_tags = git_output(source_root, &["tag", "--points-at", "HEAD"])?;
63+
if let Some(version) = build_version::exact_release_version(exact_tags.lines()) {
64+
return Some(version);
65+
}
66+
67+
let merged_tags = git_output(
68+
source_root,
69+
&["tag", "--merged", "HEAD", "--list", "v*.*.*"],
70+
)?;
71+
let latest_tag = build_version::latest_stable_tag(merged_tags.lines());
72+
let revision_range = latest_tag
73+
.as_deref()
74+
.map_or_else(|| "HEAD".to_string(), |tag| format!("{tag}..HEAD"));
75+
let distance = git_output(source_root, &["rev-list", "--count", &revision_range])?
76+
.parse()
77+
.ok()?;
78+
let sha = git_output(source_root, &["rev-parse", "--short=9", "HEAD"])?;
79+
80+
build_version::next_dev_version(latest_tag.as_deref(), distance, &sha)
81+
}
82+
83+
fn git_output(source_root: &Path, args: &[&str]) -> Option<String> {
84+
// A linked worktree has a `.git` file and a regular checkout a directory.
85+
// Without either, Git would search upward into an enclosing repository.
86+
if !source_root.join(".git").exists() {
87+
return None;
88+
}
89+
let output = Command::new("git")
90+
.args(args)
91+
.current_dir(source_root)
92+
.output()
93+
.ok()?;
94+
if !output.status.success() {
95+
return None;
96+
}
97+
String::from_utf8(output.stdout)
98+
.ok()
99+
.map(|output| output.trim().to_string())
100+
}

0 commit comments

Comments
 (0)