gen-cargo 0.1.8

gen — Cargo adapter. Parses Cargo.toml + Cargo.lock + workspace shape into gen_types::Manifest. The cargo half of the universal package-manager engine; one of N adapters (gen-npm, gen-bundler, gen-pip, gen-gomod, gen-helm, …) that share the typed core. See theory/GEN.md for the full design.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! `GitPrefetcher` — Rust-native git prefetch primitive.
//!
//! Replaces the brittle `nix-prefetch-git` shell-script call chain
//! that gen-cargo previously shelled out to. The hash side is
//! pure-Rust: `nix-nar` streamed into `Sha256`, then base64 SRI
//! encoded. The clone side is a single `Command::new("git")`
//! subprocess — one load-bearing binary, no shell script, no
//! transitive-tool dependency tree. The previous nix-prefetch-git
//! shell-script chain (bash + git + nix-hash + nix-prefetch-git
//! itself + coreutils) is reduced to: git.
//!
//! Destination: pure-`gix` (zero subprocess). Wired 2026-05-29 but
//! deferred — `gix`'s transport features pull `ring` (rustls path,
//! substrate build-script env-var bug) or `curl-sys`/`libgit2-sys`
//! (substrate `propagatedBuildInputs` not bubbled through
//! `buildRustCrate` to consumers). Both are focused substrate-side
//! fixes scheduled in a follow-up; see `theory/RUST-NATIVE-PREFETCH.md`.
//!
//! Architecture: typed trait + Mock for hermetic testing + production
//! `GitCliPrefetcher` impl. The build-spec generator depends on the
//! trait object so unit tests swap in `MockPrefetcher` with hand-
//! authored `(url, rev) → sha256` mappings — no network, no tempdirs,
//! no flakiness.

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Mutex;

use sha2::{Digest, Sha256};

// ── Typed surface ──────────────────────────────────────────────────

/// Typed git-prefetch primitive. Production impl clones via `gix`
/// and hashes via streaming NAR-sha256 (in-Rust). Tests inject a
/// `MockPrefetcher` with hand-authored `(url, rev) → hash` mappings
/// for hermetic verification.
pub trait GitPrefetcher: Send + Sync {
    /// Fetch the tree at `rev` from `url` and return its NAR-sha256
    /// digest, SRI-encoded. The result MUST be reproducible — a
    /// given `(url, rev)` ALWAYS produces the same hash.
    fn prefetch(&self, url: &str, rev: &str) -> Result<PrefetchedHash, PrefetchError>;
}

/// Typed prefetched-hash value. Carries the SRI-formatted digest +
/// the underlying raw 32-byte sha256 (so consumers can re-encode).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrefetchedHash {
    /// SRI: `sha256-<base64>`. The fetchgit-accepted form.
    pub sri: String,
    /// Raw 32-byte digest. Useful for round-trip property tests.
    pub raw: [u8; 32],
}

impl PrefetchedHash {
    /// Construct from a raw 32-byte sha256 digest. SRI is derived
    /// mechanically via base64 of the digest.
    #[must_use]
    pub fn from_digest(raw: [u8; 32]) -> Self {
        use base64::Engine;
        let b64 = base64::engine::general_purpose::STANDARD.encode(raw);
        Self {
            sri: format!("sha256-{b64}"),
            raw,
        }
    }
}

/// Typed prefetcher errors. Catalog-registered via the
/// `#[gen_macros::fsm]` attribute so operator reflection (`gen
/// dispatchers catalog`) lists every prefetcher failure class —
/// future remediations (Shigoto retry policies, drift-detector
/// dispatch tables, alert-on-fetch-failure controllers) consume the
/// catalog mechanically. The enum is the typed surface; the macro
/// bundles serde tag + Clone/PartialEq + Discriminant/IsVariant +
/// TypedDispatcher + register_dispatcher! in one line.
#[derive(thiserror::Error)]
#[gen_macros::fsm(label = "gen.cargo.prefetch-error")]
pub enum PrefetchError {
    #[error("git fetch failed for {url}#{rev}: {reason}")]
    Fetch {
        url: String,
        rev: String,
        reason: String,
    },
    #[error("NAR serialization/hash failed for {url}#{rev}: {reason}")]
    NarHash {
        url: String,
        rev: String,
        reason: String,
    },
    #[error("temp dir creation failed: {reason}")]
    TempDir { reason: String },
    #[error("MockPrefetcher: no mapping registered for {url}#{rev}")]
    MockMappingMissing { url: String, rev: String },
}

// ── Production impl: `git` subprocess + nix-nar + sha256 ───────────

/// Production prefetcher. One `git` subprocess for the fetch + checkout,
/// pure-Rust `nix-nar` Encoder streamed into `Sha256` for the digest.
/// No shell script, no transitive-tool dependency tree — `git` is the
/// single load-bearing binary.
///
/// **Destination**: pure-Rust via `gix` (zero subprocess). Deferred
/// behind a substrate-side fix for *-sys propagation in
/// `buildRustCrate`. See `theory/RUST-NATIVE-PREFETCH.md`.
pub struct GitCliPrefetcher;

impl GitCliPrefetcher {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Default for GitCliPrefetcher {
    fn default() -> Self {
        Self::new()
    }
}

impl GitPrefetcher for GitCliPrefetcher {
    fn prefetch(&self, url: &str, rev: &str) -> Result<PrefetchedHash, PrefetchError> {
        // Strip cargo's `?branch=...` / `?tag=...` / `?rev=...` query
        // suffix — git URLs don't carry the query form.
        let clean_url = url.split('?').next().unwrap_or(url);

        let tmp = tempfile::Builder::new()
            .prefix("gen-cargo-prefetch-")
            .tempdir()
            .map_err(|e| PrefetchError::TempDir {
                reason: e.to_string(),
            })?;
        let work = tmp.path();

        git_clone_at_rev(clean_url, rev, work).map_err(|reason| PrefetchError::Fetch {
            url: clean_url.into(),
            rev: rev.into(),
            reason,
        })?;

        // Drop `.git` before NAR-hashing — matches `nix-prefetch-git`
        // default (`deepClone=false`). Without this the digest would
        // include git's mutable index/objects/refs and re-runs would
        // produce different hashes.
        let dot_git = work.join(".git");
        if dot_git.exists() {
            std::fs::remove_dir_all(&dot_git).map_err(|e| PrefetchError::NarHash {
                url: clean_url.into(),
                rev: rev.into(),
                reason: format!("remove .git: {e}"),
            })?;
        }

        let digest = nar_sha256(work).map_err(|reason| PrefetchError::NarHash {
            url: clean_url.into(),
            rev: rev.into(),
            reason,
        })?;
        Ok(PrefetchedHash::from_digest(digest))
    }
}

/// Clone `url` and check out `rev` into `dest`. Uses the `git` CLI
/// binary directly — no shell, no nix-prefetch-git wrapper. Strategy:
///
/// 1. `git init` the dest (empty repo).
/// 2. `git fetch --depth=1 origin <rev>` — pulls only the rev's
///    objects, not history. `<rev>` can be a full SHA, tag, or
///    branch name. Shallow-clone for speed.
/// 3. `git -c advice.detachedHead=false checkout FETCH_HEAD` to
///    materialize the worktree.
///
/// This mirrors what nix-prefetch-git does internally without the
/// surrounding bash + nix-hash + json-formatting machinery.
fn git_clone_at_rev(url: &str, rev: &str, dest: &Path) -> Result<(), String> {
    use std::process::Command;

    let run = |args: &[&str], cwd: Option<&Path>| -> Result<(), String> {
        let mut cmd = Command::new("git");
        cmd.args(args);
        if let Some(c) = cwd {
            cmd.current_dir(c);
        }
        let output = cmd
            .output()
            .map_err(|e| format!("spawn `git {}`: {e}", args.join(" ")))?;
        if !output.status.success() {
            return Err(format!(
                "`git {}` exited {}: {}",
                args.join(" "),
                output.status,
                String::from_utf8_lossy(&output.stderr).trim()
            ));
        }
        Ok(())
    };

    run(&["init", "--quiet", dest.to_str().unwrap()], None)?;
    run(&["remote", "add", "origin", url], Some(dest))?;
    // --depth=1 keeps the fetch minimal — only the rev's tree, no
    // history. Some servers reject shallow fetches by SHA; fall back
    // to a full fetch + checkout if the shallow attempt fails.
    let shallow_fetch =
        run(&["fetch", "--quiet", "--depth=1", "origin", rev], Some(dest));
    if shallow_fetch.is_err() {
        run(&["fetch", "--quiet", "origin", rev], Some(dest))?;
    }
    run(
        &[
            "-c",
            "advice.detachedHead=false",
            "checkout",
            "--quiet",
            "FETCH_HEAD",
        ],
        Some(dest),
    )?;
    Ok(())
}

/// Stream-encode `path` as a NAR via the battle-tested `nix-nar`
/// crate (same one `sui-compat::nar::NarWriter::write_path` wraps —
/// fleet-aligned semantics) and Sha256 the byte stream.
///
/// Streaming matters: cloned repos can be huge. Materializing the
/// NAR into memory before hashing would balloon RAM use; copying
/// through a hash-writer keeps the working set to the I/O buffer.
fn nar_sha256(path: &Path) -> Result<[u8; 32], String> {
    let encoder =
        nix_nar::Encoder::new(path).map_err(|e| format!("nix-nar Encoder: {e}"))?;
    let mut reader = std::io::BufReader::new(encoder);
    let mut writer = Sha256Writer::new();
    std::io::copy(&mut reader, &mut writer).map_err(|e| format!("nar copy: {e}"))?;
    Ok(writer.finalize())
}

/// `io::Write` adapter that feeds bytes into a `Sha256` hasher. Lets
/// `std::io::copy` (or any other byte-stream consumer) drive the
/// hash without materializing the NAR.
struct Sha256Writer {
    hasher: Sha256,
}

impl Sha256Writer {
    fn new() -> Self {
        Self {
            hasher: Sha256::new(),
        }
    }

    fn finalize(self) -> [u8; 32] {
        self.hasher.finalize().into()
    }
}

impl std::io::Write for Sha256Writer {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.hasher.update(buf);
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

// ── Mock impl for hermetic tests ───────────────────────────────────

/// Test-only mock. Construct, register `(url, rev) → hash` mappings,
/// inject as `&dyn GitPrefetcher`. Every prefetch call MUST hit a
/// registered mapping; an unregistered call returns a typed
/// `PrefetchError::MockMappingMissing` so test failures point at the
/// missing fixture, not at a vague "MockPrefetcher panicked."
#[derive(Default)]
pub struct MockPrefetcher {
    mappings: Mutex<BTreeMap<(String, String), PrefetchedHash>>,
}

impl MockPrefetcher {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a `(url, rev) → hash` mapping.
    pub fn insert(
        &self,
        url: impl Into<String>,
        rev: impl Into<String>,
        hash: PrefetchedHash,
    ) {
        self.mappings
            .lock()
            .expect("MockPrefetcher mutex poisoned")
            .insert((url.into(), rev.into()), hash);
    }
}

impl GitPrefetcher for MockPrefetcher {
    fn prefetch(&self, url: &str, rev: &str) -> Result<PrefetchedHash, PrefetchError> {
        // Strip cargo query suffix — match the production normalization.
        let clean_url = url.split('?').next().unwrap_or(url);
        let key = (clean_url.to_string(), rev.to_string());
        self.mappings
            .lock()
            .expect("MockPrefetcher mutex poisoned")
            .get(&key)
            .cloned()
            .ok_or_else(|| PrefetchError::MockMappingMissing {
                url: clean_url.into(),
                rev: rev.into(),
            })
    }
}

// ── Default factory ────────────────────────────────────────────────

/// Construct the production prefetcher. Wrapped in a factory so
/// downstream consumers don't bind to the concrete impl directly —
/// trait-dispatched, swap-friendly for the eventual gix migration.
#[must_use]
pub fn default_prefetcher() -> Box<dyn GitPrefetcher> {
    Box::new(GitCliPrefetcher::new())
}

// ── Tests ──────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn sri_encoding_is_canonical() {
        // Zero digest → known SRI string.
        let zero = PrefetchedHash::from_digest([0u8; 32]);
        assert_eq!(
            zero.sri,
            "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
        );
    }

    #[test]
    fn mock_returns_registered_hash() {
        let mock = MockPrefetcher::new();
        let hash = PrefetchedHash::from_digest([1u8; 32]);
        mock.insert("https://example.com/repo", "deadbeef", hash.clone());

        let got = mock.prefetch("https://example.com/repo", "deadbeef").unwrap();
        assert_eq!(got, hash);
    }

    #[test]
    fn mock_strips_cargo_query_suffix() {
        let mock = MockPrefetcher::new();
        let hash = PrefetchedHash::from_digest([2u8; 32]);
        mock.insert("https://example.com/repo", "rev1", hash.clone());

        // Caller uses cargo's `?rev=` form; mock should normalize.
        let got = mock
            .prefetch("https://example.com/repo?rev=rev1", "rev1")
            .unwrap();
        assert_eq!(got, hash);
    }

    #[test]
    fn mock_missing_returns_typed_error() {
        let mock = MockPrefetcher::new();
        let err = mock
            .prefetch("https://example.com/repo", "rev1")
            .unwrap_err();
        matches!(
            err,
            PrefetchError::MockMappingMissing { ref url, ref rev }
                if url == "https://example.com/repo" && rev == "rev1"
        );
    }

    #[test]
    fn nar_sha256_of_empty_dir_is_deterministic() {
        let tmp = tempfile::tempdir().unwrap();
        let first = nar_sha256(tmp.path()).unwrap();
        let second = nar_sha256(tmp.path()).unwrap();
        assert_eq!(first, second);
    }

    #[test]
    fn nar_sha256_changes_when_file_added() {
        let tmp = tempfile::tempdir().unwrap();
        let empty_digest = nar_sha256(tmp.path()).unwrap();

        fs::write(tmp.path().join("hello.txt"), b"world").unwrap();
        let one_file_digest = nar_sha256(tmp.path()).unwrap();

        assert_ne!(empty_digest, one_file_digest);
    }

    #[test]
    fn nar_sha256_changes_when_contents_change() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("a.txt"), b"alpha").unwrap();
        let a = nar_sha256(tmp.path()).unwrap();

        fs::write(tmp.path().join("a.txt"), b"beta").unwrap();
        let b = nar_sha256(tmp.path()).unwrap();

        assert_ne!(a, b);
    }

    #[test]
    fn nar_sha256_independent_of_directory_walk_order() {
        // NAR canonical order is lexicographic on filename — even if
        // the filesystem reads back in insertion order, the NAR
        // output must sort. Build same logical tree two different
        // creation orders and assert digest equality.
        let tmp_a = tempfile::tempdir().unwrap();
        fs::write(tmp_a.path().join("z.txt"), b"z").unwrap();
        fs::write(tmp_a.path().join("a.txt"), b"a").unwrap();
        let da = nar_sha256(tmp_a.path()).unwrap();

        let tmp_b = tempfile::tempdir().unwrap();
        fs::write(tmp_b.path().join("a.txt"), b"a").unwrap();
        fs::write(tmp_b.path().join("z.txt"), b"z").unwrap();
        let db = nar_sha256(tmp_b.path()).unwrap();

        assert_eq!(da, db);
    }

    #[test]
    fn default_prefetcher_returns_gix() {
        // Smoke test: the factory boxes a GitCliPrefetcher without
        // panicking. Real network calls live in integration tests.
        let _: Box<dyn GitPrefetcher> = default_prefetcher();
    }
}