返回 CodeWhale
lib.rs
1 //! Shared build-script helpers for the `codewhale-cli`, `codewhale-tui`, and
2 //! `codewhale-telemetry` build scripts: rerun-condition declarations, the
3 //! embedded `CODEWHALE_BUILD_VERSION` metadata, and the release-only build sha.
4 //! Only call these functions from a build script — they emit `cargo:`
5 //! directives on stdout.
6 //!
7 //! Two different shas live here and they are not interchangeable.
8 //! `CODEWHALE_BUILD_VERSION`/`CODEWHALE_BUILD_COMMIT` describe *the build the
9 //! environment asked for* (`CODEWHALE_BUILD_SHA`/`DEEPSEEK_BUILD_SHA`/`GITHUB_SHA`,
10 //! or `CODEWHALE_LOCAL_BUILD_SHA` from `scripts/dev-cargo.sh` on clean local
11 //! release builds); an unstamped local checkout renders `(dev)`; an unstamped
12 //! Cargo source package displays its package version without claiming a
13 //! release-binary SHA.
14 //! `CODEWHALE_RELEASE_BUILD_SHA` describes a *published* binary: it reads only
15 //! the explicit release variables (never the ambient `GITHUB_SHA` or
16 //! `CODEWHALE_LOCAL_BUILD_SHA`) and has no fallback at all, because it leaves
17 //! the machine.
18 //!
19 //! ## Why the stamp never reads the local checkout (#5245)
20 //!
21 //! These helpers used to watch `.git/HEAD`/refs and fall back to
22 //! `git rev-parse HEAD`, so every local commit invalidated the two largest
23 //! compile units in the workspace (a ~14-minute release rebuild with zero
24 //! code changes). And the alternative — resolving the sha at *runtime* —
25 //! would lie: the binary runs inside users' repositories, and a stale binary
26 //! would report whatever the checkout's HEAD is *now*, which breaks the
27 //! dogfood-receipt identity `scripts/release/install-dogfood.sh` verifies.
28 //! So the contract is: a sha appears in the version string only when the
29 //! build environment supplied one (`CODEWHALE_BUILD_SHA` wins over
30 //! `GITHUB_SHA`, which wins over `CODEWHALE_LOCAL_BUILD_SHA`), the build script
31 //! reruns only when those variables change, and an unstamped checkout says
32 //! `(dev)`. Cargo source packages use the plain package version. CI and
33 //! release builds are byte-identical to the old behavior; dogfood builds
34 //! pass the sha explicitly or build cleanly via `scripts/dev-cargo.sh`.
35
36 use std::path::Path;
37
38 /// Main-thread stack reserve shared by the Windows CLI and TUI entrypoints.
39 /// `RUST_MIN_STACK` only sizes spawned threads; the CLI's default 1 MiB main
40 /// stack overflowed in `model resolve`. Reuse the TUI's existing 8 MiB reserve.
41 pub const WINDOWS_MAIN_STACK_BYTES: u64 = 8 * 1024 * 1024;
42
43 /// The linker directive that reserves [`WINDOWS_MAIN_STACK_BYTES`] for
44 /// `bin_name`, or `None` when the target is not Windows.
45 ///
46 /// The environment is injected so the decision is testable on any host without
47 /// mutating the process, matching [`release_build_sha`].
48 ///
49 /// `cargo:rustc-link-arg-bin` only reaches binaries in the *calling* package,
50 /// so each package that ships an entrypoint must emit its own — which is why
51 /// this lives here instead of being stated once.
52 #[must_use]
53 pub fn windows_main_stack_link_arg(
54 bin_name: &str,
55 read_env: impl Fn(&str) -> Option<String>,
56 ) -> Option<String> {
57 if read_env("CARGO_CFG_TARGET_OS").as_deref() != Some("windows") {
58 return None;
59 }
60 let bytes = WINDOWS_MAIN_STACK_BYTES;
61 match read_env("CARGO_CFG_TARGET_ENV").as_deref() {
62 Some("msvc") => Some(format!(
63 "cargo:rustc-link-arg-bin={bin_name}=/STACK:{bytes}"
64 )),
65 Some("gnu") => Some(format!(
66 "cargo:rustc-link-arg-bin={bin_name}=-Wl,--stack,{bytes}"
67 )),
68 _ => None,
69 }
70 }
71
72 /// Emit the reserve for one binary in the calling package.
73 pub fn configure_windows_main_stack(bin_name: &str) {
74 if let Some(directive) = windows_main_stack_link_arg(bin_name, |name| std::env::var(name).ok())
75 {
76 println!("{directive}");
77 }
78 }
79
80 /// Declare the rerun conditions for the build-metadata directives: the two
81 /// SHA-override environment variables, and deliberately nothing about the
82 /// local checkout — watching `.git` files is what made every local commit
83 /// rebuild the whole crate (#5245).
84 ///
85 /// `manifest_dir` is accepted (and ignored) so build scripts keep one call
86 /// shape; it documents that the decision is per-crate, not global state.
87 pub fn declare_rerun_conditions(_manifest_dir: &Path) {
88 println!("cargo:rerun-if-env-changed=CODEWHALE_BUILD_SHA");
89 println!("cargo:rerun-if-env-changed=DEEPSEEK_BUILD_SHA");
90 println!("cargo:rerun-if-env-changed=GITHUB_SHA");
91 println!("cargo:rerun-if-env-changed=CODEWHALE_LOCAL_BUILD_SHA");
92 }
93
94 /// Emit `cargo:rustc-env=CODEWHALE_BUILD_VERSION=...` — the package version,
95 /// suffixed with the short build SHA when the environment supplied one
96 /// (`CODEWHALE_BUILD_SHA`, then `DEEPSEEK_BUILD_SHA`, then `GITHUB_SHA`, then
97 /// `CODEWHALE_LOCAL_BUILD_SHA`).
98 /// Unstamped Cargo source packages show the plain package version; unpackaged
99 /// checkouts retain `(dev)`. `CODEWHALE_BUILD_COMMIT` is emitted only when stamped.
100 ///
101 /// `package_version` is the calling build script's `CARGO_PKG_VERSION`;
102 /// Cargo writes `Cargo.toml.orig` when normalizing a distributable package.
103 /// Its presence classifies the source layout, not release provenance: no VCS
104 /// metadata is read and no additional commit value is emitted.
105 pub fn emit_build_version(manifest_dir: &Path, package_version: &str) {
106 let commit = build_commit();
107 let build_version = format_build_version(
108 package_version,
109 commit.as_deref(),
110 manifest_dir.join("Cargo.toml.orig").is_file(),
111 );
112
113 println!("cargo:rustc-env=CODEWHALE_BUILD_VERSION={build_version}");
114 // Keep the pre-rebrand compile-time name through the 0.9.x compatibility
115 // window for downstream crates that still use `env!` with it.
116 println!("cargo:rustc-env=DEEPSEEK_BUILD_VERSION={build_version}");
117 if let Some(commit) = commit {
118 println!("cargo:rustc-env=CODEWHALE_BUILD_COMMIT={commit}");
119 }
120 }
121
122 fn format_build_version(
123 package_version: &str,
124 commit: Option<&str>,
125 packaged_source: bool,
126 ) -> String {
127 match commit.and_then(|sha| short_sha(sha.to_string())) {
128 Some(sha) => format!("{package_version} ({sha})"),
129 None if packaged_source => package_version.to_string(),
130 None => format!("{package_version} (dev)"),
131 }
132 }
133
134 /// Declare the rerun conditions for [`emit_release_build_sha`] alone: the two
135 /// explicit release-build SHA variables, and nothing about the local checkout.
136 ///
137 /// Deliberately not [`declare_rerun_conditions`]: watching `.git/HEAD` would
138 /// make the build script rerun on every local commit, for a value that is
139 /// `None` on every local build by design.
140 pub fn declare_release_sha_rerun() {
141 println!("cargo:rerun-if-env-changed=CODEWHALE_BUILD_SHA");
142 println!("cargo:rerun-if-env-changed=DEEPSEEK_BUILD_SHA");
143 }
144
145 /// Emit `cargo:rustc-env=CODEWHALE_RELEASE_BUILD_SHA=...` — the first 12 hex
146 /// characters of the build sha — **only** when the build environment supplied
147 /// one.
148 ///
149 /// This is provenance for a *published* binary, and it is the only sha a
150 /// telemetry payload may carry. There is deliberately no fallback to the local
151 /// checkout:
152 ///
153 /// - `CODEWHALE_BUILD_COMMIT` historically fell back to the builder's own
154 /// private `HEAD` on every local build; since #5245 it is env-only too,
155 /// but this value keeps its own name and rule because it is the only sha
156 /// a telemetry payload may carry.
157 /// - The "was this a published release" gate proposed earlier cannot be built:
158 /// `codewhale_release::latest_release_tag_{async,blocking}` are **network
159 /// calls** to `api.github.com` that return *tag names*, not shas, so the only
160 /// available comparison is version-vs-version — and a private tree at the
161 /// same version compares equal.
162 ///
163 /// Build-time provenance is deterministic, network-free, and verifiable from
164 /// the repository. Absent the release environment the value is simply absent,
165 /// and `option_env!` in the consuming crate yields `None`.
166 pub fn emit_release_build_sha() {
167 if let Some(sha) = release_build_sha(|name| std::env::var(name).ok()) {
168 println!("cargo:rustc-env=CODEWHALE_RELEASE_BUILD_SHA={sha}");
169 }
170 }
171
172 /// The decision behind [`emit_release_build_sha`], with the environment
173 /// injected so it can be tested without mutating the process.
174 ///
175 /// `CODEWHALE_BUILD_SHA` wins over the legacy `DEEPSEEK_BUILD_SHA`; each must
176 /// be a full 40-hex sha to be believed, and the result is the first 12
177 /// characters.
178 ///
179 /// Never `GITHUB_SHA`. Every GitHub Actions job sets it — pull-request CI,
180 /// forks, any workflow that happens to build — so it proves only "built on
181 /// Actions", not "published release". Every release, nightly, and CNB build
182 /// exports `CODEWHALE_BUILD_SHA` explicitly, so dropping the ambient fallback
183 /// leaves published binaries unchanged. The display stamp
184 /// ([`emit_build_version`]) still accepts `GITHUB_SHA`: it is a version
185 /// string, not provenance.
186 #[must_use]
187 pub fn release_build_sha(read_env: impl Fn(&str) -> Option<String>) -> Option<String> {
188 read_env("CODEWHALE_BUILD_SHA")
189 .and_then(full_sha)
190 .or_else(|| read_env("DEEPSEEK_BUILD_SHA").and_then(full_sha))
191 .and_then(short_sha)
192 }
193
194 fn build_commit() -> Option<String> {
195 build_commit_with(|name| std::env::var(name).ok())
196 }
197
198 /// The stamping decision with the environment injected, so the no-local-
199 /// fallback contract is testable without mutating the process (#5245).
200 fn build_commit_with(read_env: impl Fn(&str) -> Option<String>) -> Option<String> {
201 read_env("CODEWHALE_BUILD_SHA")
202 .and_then(full_sha)
203 .or_else(|| read_env("DEEPSEEK_BUILD_SHA").and_then(full_sha))
204 .or_else(|| read_env("GITHUB_SHA").and_then(full_sha))
205 .or_else(|| read_env("CODEWHALE_LOCAL_BUILD_SHA").and_then(full_sha))
206 }
207
208 fn full_sha(value: String) -> Option<String> {
209 let trimmed = value.trim().to_ascii_lowercase();
210 if trimmed.len() != 40 || !trimmed.bytes().all(|byte| byte.is_ascii_hexdigit()) {
211 return None;
212 }
213 Some(trimmed)
214 }
215
216 fn short_sha(value: String) -> Option<String> {
217 let trimmed = value.trim();
218 if trimmed.is_empty() {
219 return None;
220 }
221 Some(trimmed.chars().take(12).collect())
222 }
223
224 #[cfg(test)]
225 mod tests {
226 use super::{
227 WINDOWS_MAIN_STACK_BYTES, full_sha, release_build_sha, short_sha,
228 windows_main_stack_link_arg,
229 };
230
231 fn windows_target(env: &'static str) -> impl Fn(&str) -> Option<String> {
232 move |name| match name {
233 "CARGO_CFG_TARGET_OS" => Some("windows".to_string()),
234 "CARGO_CFG_TARGET_ENV" => Some(env.to_string()),
235 _ => None,
236 }
237 }
238
239 /// Every Codewhale entrypoint must reserve its Windows main-thread stack.
240 ///
241 /// `codewhale` shipped without it while `codewhale-tui` had it, so
242 /// `codewhale model resolve` ran `fn main` on the 1 MiB linker default and
243 /// aborted with `thread 'main' has overflowed its stack` on hosted Windows.
244 /// `cargo:rustc-link-arg-bin` reaches only the calling package's binaries,
245 /// so each entrypoint needs its own directive and neither covers the other.
246 #[test]
247 fn every_windows_entrypoint_reserves_the_same_main_stack() {
248 for bin in ["codewhale", "codewhale-tui"] {
249 assert_eq!(
250 windows_main_stack_link_arg(bin, windows_target("msvc")),
251 Some(format!(
252 "cargo:rustc-link-arg-bin={bin}=/STACK:{WINDOWS_MAIN_STACK_BYTES}"
253 ))
254 );
255 assert_eq!(
256 windows_main_stack_link_arg(bin, windows_target("gnu")),
257 Some(format!(
258 "cargo:rustc-link-arg-bin={bin}=-Wl,--stack,{WINDOWS_MAIN_STACK_BYTES}"
259 ))
260 );
261 }
262 // Keep the previously shipped TUI reserve.
263 assert_eq!(WINDOWS_MAIN_STACK_BYTES, 8 * 1024 * 1024);
264 }
265
266 /// The directive is Windows-only and names one binary. A non-Windows target
267 /// emits nothing, so this never becomes a workspace-wide stack change.
268 #[test]
269 fn no_stack_directive_is_emitted_off_windows() {
270 for os in ["linux", "macos"] {
271 assert_eq!(
272 windows_main_stack_link_arg("codewhale", |name| (name == "CARGO_CFG_TARGET_OS")
273 .then(|| os.to_string())),
274 None
275 );
276 }
277 // An unknown Windows ABI gets no guessed linker syntax.
278 assert_eq!(
279 windows_main_stack_link_arg("codewhale", windows_target("sgx")),
280 None
281 );
282 assert_eq!(windows_main_stack_link_arg("codewhale", |_| None), None);
283 }
284
285 #[test]
286 fn packaged_sources_do_not_claim_to_be_unreleased_or_stamped() {
287 assert_eq!(super::format_build_version("0.9.13", None, true), "0.9.13");
288 assert_eq!(
289 super::format_build_version("0.9.13", None, false),
290 "0.9.13 (dev)"
291 );
292 let sha = "abcdef0123456789abcdef0123456789abcdef01";
293 for packaged in [true, false] {
294 assert_eq!(
295 super::format_build_version("0.9.13", Some(sha), packaged),
296 "0.9.13 (abcdef012345)"
297 );
298 }
299 // Source packaging must not create a telemetry/release provenance SHA.
300 assert_eq!(release_build_sha(|_| None), None);
301 }
302
303 #[test]
304 fn full_commit_requires_exact_forty_hex_characters() {
305 assert_eq!(
306 full_sha("ABCDEF0123456789ABCDEF0123456789ABCDEF01".to_string()),
307 Some("abcdef0123456789abcdef0123456789abcdef01".to_string())
308 );
309 assert_eq!(full_sha("abc123".to_string()), None);
310 assert_eq!(
311 full_sha("gggggggggggggggggggggggggggggggggggggggg".to_string()),
312 None
313 );
314 assert_eq!(
315 short_sha("abcdef0123456789abcdef0123456789abcdef01".to_string()),
316 Some("abcdef012345".to_string())
317 );
318 }
319
320 #[test]
321 fn the_release_build_sha_is_absent_for_every_local_build() {
322 // No release environment: nothing is emitted, so `option_env!` in the
323 // consuming crate is `None` and a telemetry payload carries `git_sha:
324 // null`. This is the property that keeps a maintainer's private HEAD
325 // out of a shipped binary.
326 assert_eq!(release_build_sha(|_| None), None);
327 }
328
329 #[test]
330 fn the_release_build_sha_comes_only_from_a_release_environment() {
331 let ci = "abcdef0123456789abcdef0123456789abcdef01";
332 // Audit R02-m1: an ordinary Actions build (PR CI, a fork) has
333 // `GITHUB_SHA` and nothing else; that is not release provenance.
334 assert_eq!(
335 release_build_sha(|name| (name == "GITHUB_SHA").then(|| ci.to_string())),
336 None
337 );
338 // The canonical Codewhale variable wins over the legacy
339 // DeepSeek-era one; `GITHUB_SHA` never participates.
340 assert_eq!(
341 release_build_sha(|name| match name {
342 "CODEWHALE_BUILD_SHA" => Some("e".repeat(40)),
343 "DEEPSEEK_BUILD_SHA" => Some("f".repeat(40)),
344 "GITHUB_SHA" => Some(ci.to_string()),
345 _ => None,
346 }),
347 Some("e".repeat(12))
348 );
349 // The legacy name still stamps during the 0.9.x compatibility
350 // window, so existing release tooling keeps working.
351 assert_eq!(
352 release_build_sha(|name| match name {
353 "DEEPSEEK_BUILD_SHA" => Some("f".repeat(40)),
354 "GITHUB_SHA" => Some(ci.to_string()),
355 _ => None,
356 }),
357 Some("f".repeat(12))
358 );
359 // A value that is not a full sha is not believed, and does not fall
360 // through to the local checkout.
361 assert_eq!(
362 release_build_sha(|name| (name == "DEEPSEEK_BUILD_SHA").then(|| "abc123".to_string())),
363 None
364 );
365 // `CODEWHALE_BUILD_COMMIT` and `CODEWHALE_LOCAL_BUILD_SHA` are display/
366 // receipt stamps with a different rule and are never sources here.
367 assert_eq!(
368 release_build_sha(|name| (name == "CODEWHALE_BUILD_COMMIT").then(|| ci.to_string())),
369 None
370 );
371 assert_eq!(
372 release_build_sha(|name| (name == "CODEWHALE_LOCAL_BUILD_SHA").then(|| ci.to_string())),
373 None
374 );
375 }
376
377 /// #5245 contract: the version stamp reads ONLY the environment
378 /// variables. There is no fallback to the local checkout, so a plain
379 /// local build renders `(dev)` and — the actual point — the build script
380 /// declares no `.git` rerun paths, meaning `git commit` no longer
381 /// invalidates the two largest compile units in the workspace.
382 #[test]
383 fn the_build_commit_never_reads_the_local_checkout() {
384 // This test runs inside the real repository; if a git fallback still
385 // existed it would resolve a sha here. Absent env vars must mean
386 // absent commit, in the repo or out of it.
387 assert_eq!(super::build_commit_with(|_| None), None);
388 let ci = "abcdef0123456789abcdef0123456789abcdef01";
389 assert_eq!(
390 super::build_commit_with(
391 |name| (name == "CODEWHALE_LOCAL_BUILD_SHA").then(|| "c".repeat(40))
392 ),
393 Some("c".repeat(40))
394 );
395 assert_eq!(
396 super::build_commit_with(|name| match name {
397 "GITHUB_SHA" => Some(ci.to_string()),
398 "CODEWHALE_LOCAL_BUILD_SHA" => Some("c".repeat(40)),
399 _ => None,
400 }),
401 Some(ci.to_string())
402 );
403 assert_eq!(
404 super::build_commit_with(|name| match name {
405 "DEEPSEEK_BUILD_SHA" => Some("f".repeat(40)),
406 "GITHUB_SHA" => Some(ci.to_string()),
407 _ => None,
408 }),
409 Some("f".repeat(40))
410 );
411 assert_eq!(
412 super::build_commit_with(|name| match name {
413 "CODEWHALE_BUILD_SHA" => Some("e".repeat(40)),
414 "DEEPSEEK_BUILD_SHA" => Some("f".repeat(40)),
415 _ => None,
416 }),
417 Some("e".repeat(40))
418 );
419 }
420 }
421
421 lines RUST