forjar 1.6.2

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! FJ-006: Package resource handler (apt + cargo + uv + brew).
//! FJ-1398: Cross-platform resource abstraction via brew provider.

use crate::core::shell_escape::sh_squote;
use crate::core::types::Resource;

/// Generate shell script to check if packages are installed.
pub fn check_script(resource: &Resource) -> String {
    let provider = resource.provider.as_deref().unwrap_or("apt");
    let packages = &resource.packages;

    match provider {
        "apt" => {
            let checks: Vec<String> = packages
                .iter()
                .map(|p| {
                    let q = sh_squote(p);
                    format!(
                        "dpkg -l {q} 2>/dev/null | grep -q '^ii ' && echo {} || echo {}",
                        sh_squote(&format!("installed:{p}")),
                        sh_squote(&format!("missing:{p}"))
                    )
                })
                .collect();
            checks.join("\n")
        }
        "cargo" => {
            let checks: Vec<String> = packages
                .iter()
                .map(|p| {
                    let (crate_name, _) = parse_cargo_features(p);
                    let q = sh_squote(crate_name);
                    format!(
                        "command -v {q} >/dev/null 2>&1 && echo {} || echo {}",
                        sh_squote(&format!("installed:{crate_name}")),
                        sh_squote(&format!("missing:{crate_name}"))
                    )
                })
                .collect();
            checks.join("\n")
        }
        "uv" => {
            let checks: Vec<String> = packages
                .iter()
                .map(|p| {
                    format!(
                        "uv tool list 2>/dev/null | grep -q {} && echo {} || echo {}",
                        sh_squote(&format!("^{p}")),
                        sh_squote(&format!("installed:{p}")),
                        sh_squote(&format!("missing:{p}"))
                    )
                })
                .collect();
            checks.join("\n")
        }
        "brew" => {
            let checks: Vec<String> = packages
                .iter()
                .map(|p| {
                    let q = sh_squote(p);
                    format!(
                        "brew list {q} >/dev/null 2>&1 && echo {} || echo {}",
                        sh_squote(&format!("installed:{p}")),
                        sh_squote(&format!("missing:{p}"))
                    )
                })
                .collect();
            checks.join("\n")
        }
        other => format!("echo 'unsupported provider: {other}'"),
    }
}

/// Generate shell script to install packages.
pub fn apply_script(resource: &Resource) -> String {
    let provider = resource.provider.as_deref().unwrap_or("apt");
    let state = resource.state.as_deref().unwrap_or("present");

    match (provider, state) {
        ("apt", "present") => apply_apt_present(resource),
        ("apt", "absent") => apply_apt_absent(resource),
        ("apt", "latest") => apply_apt_latest(resource),
        ("cargo", "present") => apply_cargo_present(resource),
        ("uv", "present") => apply_uv_present(resource),
        ("uv", "absent") => apply_uv_absent(resource),
        ("brew", "present") => apply_brew_present(resource),
        ("brew", "absent") => apply_brew_absent(resource),
        (other_provider, other_state) => {
            format!("echo 'unsupported: provider={other_provider}, state={other_state}'")
        }
    }
}

fn apply_apt_present(resource: &Resource) -> String {
    let packages = &resource.packages;
    let version = resource.version.as_deref();
    let pkg_list: Vec<String> = packages
        .iter()
        .map(|p| match version {
            Some(v) => sh_squote(&format!("{p}={v}")),
            None => sh_squote(p),
        })
        .collect();
    let check_list: Vec<String> = packages.iter().map(|p| sh_squote(p)).collect();
    let joined = pkg_list.join(" ");
    let check_joined = check_list.join(" ");
    format!(
        "set -euo pipefail\n\
         NEED_INSTALL=0\n\
         for pkg in {check_joined}; do\n\
           dpkg -l \"$pkg\" 2>/dev/null | grep -q '^ii ' || NEED_INSTALL=1\n\
         done\n\
         if [ \"$NEED_INSTALL\" = \"1\" ]; then\n\
           if [ \"$(id -u)\" -ne 0 ]; then\n\
             sudo apt-get update -qq\n\
             DEBIAN_FRONTEND=noninteractive sudo apt-get install -y -qq {joined}\n\
           else\n\
             apt-get update -qq\n\
             DEBIAN_FRONTEND=noninteractive apt-get install -y -qq {joined}\n\
           fi\n\
         fi\n\
         # Postcondition: all packages installed\n\
         for pkg in {check_joined}; do\n\
           dpkg -l \"$pkg\" 2>/dev/null | grep -q '^ii '\n\
         done"
    )
}

// PMAT-161: state=latest semantics — refresh package lists then run
// `apt-get install`, which installs missing packages or upgrades to the
// newest available version (no-op if already current). Unlike `present`,
// this is not guarded by a `dpkg -l` presence check, since the goal is
// to converge on the latest available version regardless of what is
// currently installed.
//
// FJ-PMAT-161-1: `apt-get update` is tolerated as best-effort (`|| true`).
// In production, hosts routinely have one or two unreachable third-party
// PPAs, masked PackageKit units, or stale arm64 entries on x86_64 boxes
// that make `apt-get update` exit non-zero even when the repos we
// actually care about refreshed cleanly. Failing hard there blocks
// upgrades that should succeed. The subsequent `apt-get install` fails
// loud and clear if the requested package can't be resolved against the
// (possibly partially-stale) cache, so correctness of the postcondition
// is preserved. This matches canonical Dockerfile / Ansible practice.
fn apply_apt_latest(resource: &Resource) -> String {
    let packages = &resource.packages;
    let pkg_list: Vec<String> = packages.iter().map(|p| sh_squote(p)).collect();
    let joined = pkg_list.join(" ");
    let check_joined = pkg_list.join(" ");
    format!(
        "set -euo pipefail\n\
         if [ \"$(id -u)\" -ne 0 ]; then\n\
           sudo apt-get update -qq || true\n\
           DEBIAN_FRONTEND=noninteractive sudo apt-get install -y -qq {joined}\n\
         else\n\
           apt-get update -qq || true\n\
           DEBIAN_FRONTEND=noninteractive apt-get install -y -qq {joined}\n\
         fi\n\
         # Postcondition: all packages installed (at latest available)\n\
         for pkg in {check_joined}; do\n\
           dpkg -l \"$pkg\" 2>/dev/null | grep -q '^ii '\n\
         done"
    )
}

fn apply_apt_absent(resource: &Resource) -> String {
    let packages = &resource.packages;
    let pkg_list: Vec<String> = packages.iter().map(|p| sh_squote(p)).collect();
    let joined = pkg_list.join(" ");
    format!(
        "set -euo pipefail\n\
         NEED_REMOVE=0\n\
         for pkg in {joined}; do\n\
           dpkg -l \"$pkg\" 2>/dev/null | grep -q '^ii ' && NEED_REMOVE=1\n\
         done\n\
         if [ \"$NEED_REMOVE\" = \"1\" ]; then\n\
           if [ \"$(id -u)\" -ne 0 ]; then\n\
             DEBIAN_FRONTEND=noninteractive sudo apt-get remove -y -qq {joined}\n\
           else\n\
             DEBIAN_FRONTEND=noninteractive apt-get remove -y -qq {joined}\n\
           fi\n\
         fi"
    )
}

/// Parse a cargo package spec into (crate_name, features).
///
/// Supports `crate[feat1,feat2]` syntax for specifying cargo features inline.
/// Example: `"whisper-apr[cli]"` → `("whisper-apr", vec!["cli"])`
pub(crate) fn parse_cargo_features(pkg: &str) -> (&str, Vec<&str>) {
    if let Some(bracket_start) = pkg.find('[') {
        let crate_name = &pkg[..bracket_start];
        let rest = &pkg[bracket_start + 1..];
        let features_str = rest.trim_end_matches(']');
        let features: Vec<&str> = features_str
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();
        (crate_name, features)
    } else {
        (pkg, vec![])
    }
}

/// FJ-51: Cargo binary cache — skip recompilation when cached binary exists.
///
/// Cache layout: `$FORJAR_CACHE_DIR/<pkg>-<version>-<arch>/bin/`
/// Default cache dir: `~/.forjar/cache/cargo`
/// Disable: `FORJAR_NO_CARGO_CACHE=1`
///
/// Supports `crate[feat1,feat2]` syntax in package names to pass `--features`
/// to `cargo install`. Example: `packages: ["whisper-apr[cli]"]`.
/// True if a cargo crate name / feature uses only the cargo-legal charset
/// (`[A-Za-z0-9._-]`). Used to reject names that would otherwise be
/// interpolated into the double-quoted cache key, where `$(...)`/backticks
/// would otherwise be live.
fn is_safe_cargo_token(tok: &str) -> bool {
    !tok.is_empty()
        && tok
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

/// True if `version` is a safe cargo version requirement charset.
fn is_safe_cargo_version(ver: &str) -> bool {
    !ver.is_empty()
        && ver.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+' | '*' | '~' | '^')
        })
}

/// Validate every cargo package spec (crate name + features) and the optional
/// version against the cargo-legal charset. Returns the offending token on
/// the first failure.
fn first_unsafe_cargo_token<'a>(
    packages: &'a [String],
    version: Option<&'a str>,
) -> Option<&'a str> {
    if let Some(v) = version {
        if !is_safe_cargo_version(v) {
            return Some(v);
        }
    }
    for p in packages {
        let (crate_name, features) = parse_cargo_features(p);
        if !is_safe_cargo_token(crate_name) {
            return Some(crate_name);
        }
        if let Some(bad) = features.into_iter().find(|f| !is_safe_cargo_token(f)) {
            return Some(bad);
        }
    }
    None
}

fn apply_cargo_present(resource: &Resource) -> String {
    let packages = &resource.packages;
    let version = resource.version.as_deref();
    let source = resource.source.as_deref();

    // FJ-154: reject crate/feature/version tokens that aren't cargo-legal,
    // since they flow into a double-quoted cache key where command
    // substitution would otherwise be live. Path installs (source set) skip
    // the cache, so they only need the install arg escaped (done below).
    if source.is_none() {
        if let Some(bad) = first_unsafe_cargo_token(packages, version) {
            return format!(
                "echo {} >&2; exit 1",
                sh_squote(&format!("ERROR: unsafe cargo package/version token: {bad}"))
            );
        }
    }

    let installs: Vec<String> = packages
        .iter()
        .map(|p| match (source, version) {
            // Local path installs — no caching, always rebuild
            (Some(s), _) => {
                let (_, features) = parse_cargo_features(p);
                let features_arg = if features.is_empty() {
                    String::new()
                } else {
                    format!(" --features {}", sh_squote(&features.join(",")))
                };
                format!(
                    "cargo install --force --locked --path {}{features_arg}",
                    sh_squote(s)
                )
            }
            (None, ver) => cargo_cached_install(p, ver),
        })
        .collect();
    // Limit build parallelism to avoid OOM on high-core-count machines.
    // Respects CARGO_BUILD_JOBS if already set; defaults to min(nproc/2, 8).
    format!(
        "set -euo pipefail\n\
         command -v cargo >/dev/null 2>&1 || {{\n\
           RUSTUP_INIT=$(mktemp /tmp/rustup-init.XXXXXX)\n\
           curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs -o \"$RUSTUP_INIT\"\n\
           chmod +x \"$RUSTUP_INIT\"\n\
           \"$RUSTUP_INIT\" -y --no-modify-path\n\
           rm -f \"$RUSTUP_INIT\"\n\
           export PATH=\"$HOME/.cargo/bin:$PATH\"\n\
         }}\n\
         if [ -z \"${{CARGO_BUILD_JOBS:-}}\" ]; then\n\
           _nproc=$(nproc 2>/dev/null || echo 4)\n\
           _half=$(( _nproc / 2 ))\n\
           [ \"$_half\" -lt 1 ] && _half=1\n\
           [ \"$_half\" -gt 8 ] && _half=8\n\
           export CARGO_BUILD_JOBS=$_half\n\
         fi\n\
         _CARGO_BIN=\"${{CARGO_HOME:-$HOME/.cargo}}/bin\"\n\
         {}",
        installs.join("\n")
    )
}

/// Generate a cached cargo install script for a single crate.
///
/// On cache hit: copy pre-built binaries from cache, skip compilation entirely.
/// On cache miss: `cargo install --root <staging>`, then populate cache + install.
///
/// Supports `crate[feat1,feat2]` syntax — features are passed via `--features`
/// and included in the cache key to avoid feature-set collisions.
///
/// Detects empty staging bin dir (no binaries produced) and emits a clear error
/// with a hint about `--features`, instead of failing on `cp` with a cryptic message.
fn cargo_cached_install(pkg: &str, version: Option<&str>) -> String {
    let (crate_name, features) = parse_cargo_features(pkg);
    let ver_tag = version.unwrap_or("latest");
    let install_arg = match version {
        Some(v) => sh_squote(&format!("{crate_name}@{v}")),
        None => sh_squote(crate_name),
    };
    let features_arg = if features.is_empty() {
        String::new()
    } else {
        format!(" --features {}", sh_squote(&features.join(",")))
    };
    let cache_suffix = if features.is_empty() {
        String::new()
    } else {
        format!("+{}", features.join(","))
    };
    format!(
        "_CACHE_KEY=\"{crate_name}-{ver_tag}{cache_suffix}-$(uname -m)\"\n\
         _CACHE_DIR=\"${{FORJAR_CACHE_DIR:-$HOME/.forjar/cache/cargo}}/$_CACHE_KEY\"\n\
         if [ -z \"${{FORJAR_NO_CARGO_CACHE:-}}\" ] && \
            [ -d \"$_CACHE_DIR/bin\" ] && \
            ls \"$_CACHE_DIR/bin/\"* >/dev/null 2>&1; then\n\
           cp \"$_CACHE_DIR/bin/\"* \"$_CARGO_BIN/\"\n\
           echo \"forjar: cache-hit {crate_name} [$_CACHE_KEY]\"\n\
         else\n\
           _STAGING=$(mktemp -d /tmp/forjar-cargo.XXXXXX)\n\
           cargo install --force --locked --root \"$_STAGING\"{features_arg} {install_arg}\n\
           if [ ! -d \"$_STAGING/bin\" ] || ! ls \"$_STAGING/bin/\"* >/dev/null 2>&1; then\n\
             echo \"ERROR: cargo install {crate_name} produced no binaries\" >&2\n\
             echo \"HINT: does the crate need --features? Use packages: [\\\"{crate_name}[feature_name]\\\"]\" >&2\n\
             rm -rf \"$_STAGING\"\n\
             exit 1\n\
           fi\n\
           if [ -z \"${{FORJAR_NO_CARGO_CACHE:-}}\" ]; then\n\
             mkdir -p \"$_CACHE_DIR\"\n\
             cp -a \"$_STAGING/bin\" \"$_CACHE_DIR/\"\n\
           fi\n\
           cp \"$_STAGING/bin/\"* \"$_CARGO_BIN/\"\n\
           rm -rf \"$_STAGING\"\n\
           echo \"forjar: cached {crate_name} [$_CACHE_KEY]\"\n\
         fi"
    )
}

fn apply_uv_present(resource: &Resource) -> String {
    let packages = &resource.packages;
    let version = resource.version.as_deref();
    let installs: Vec<String> = packages
        .iter()
        .map(|p| match version {
            Some(v) => format!(
                "uv tool install --force {}",
                sh_squote(&format!("{p}=={v}"))
            ),
            None => format!("uv tool install --force {}", sh_squote(p)),
        })
        .collect();
    format!("set -euo pipefail\n{}", installs.join("\n"))
}

fn apply_uv_absent(resource: &Resource) -> String {
    let packages = &resource.packages;
    let removals: Vec<String> = packages
        .iter()
        .map(|p| format!("uv tool uninstall {} 2>/dev/null || true", sh_squote(p)))
        .collect();
    format!("set -euo pipefail\n{}", removals.join("\n"))
}

/// FJ-1398: Homebrew install (macOS/Linux cross-platform).
fn apply_brew_present(resource: &Resource) -> String {
    let packages = &resource.packages;
    let version = resource.version.as_deref();
    let check_list: Vec<String> = packages.iter().map(|p| sh_squote(p)).collect();
    let installs: Vec<String> = packages
        .iter()
        .map(|p| match version {
            Some(v) => format!("brew install {}", sh_squote(&format!("{p}@{v}"))),
            None => format!("brew install {}", sh_squote(p)),
        })
        .collect();
    let check_joined = check_list.join(" ");
    format!(
        "set -euo pipefail\n\
         NEED_INSTALL=0\n\
         for pkg in {check_joined}; do\n\
           brew list \"$pkg\" >/dev/null 2>&1 || NEED_INSTALL=1\n\
         done\n\
         if [ \"$NEED_INSTALL\" = \"1\" ]; then\n\
           {}\n\
         fi",
        installs.join("\n  ")
    )
}

fn apply_brew_absent(resource: &Resource) -> String {
    let packages = &resource.packages;
    let removals: Vec<String> = packages
        .iter()
        .map(|p| format!("brew uninstall {} 2>/dev/null || true", sh_squote(p)))
        .collect();
    format!("set -euo pipefail\n{}", removals.join("\n"))
}

/// Generate shell to query installed versions (for state hashing).
pub fn state_query_script(resource: &Resource) -> String {
    let provider = resource.provider.as_deref().unwrap_or("apt");
    let packages = &resource.packages;

    match provider {
        "apt" => {
            let queries: Vec<String> = packages
                .iter()
                .map(|p| {
                    format!(
                        "dpkg-query -W -f '${{Package}}=${{Version}}\\n' {} 2>/dev/null || echo {}",
                        sh_squote(p),
                        sh_squote(&format!("{p}=MISSING"))
                    )
                })
                .collect();
            queries.join("\n")
        }
        "cargo" => {
            let queries: Vec<String> = packages
                .iter()
                .map(|p| {
                    let (crate_name, _) = parse_cargo_features(p);
                    format!(
                        "command -v {} >/dev/null 2>&1 && echo {} || echo {}",
                        sh_squote(crate_name),
                        sh_squote(&format!("{crate_name}=installed")),
                        sh_squote(&format!("{crate_name}=MISSING"))
                    )
                })
                .collect();
            queries.join("\n")
        }
        "uv" => {
            let queries: Vec<String> = packages
                .iter()
                .map(|p| {
                    format!(
                        "uv tool list 2>/dev/null | grep -q {} && echo {} || echo {}",
                        sh_squote(&format!("^{p}")),
                        sh_squote(&format!("{p}=installed")),
                        sh_squote(&format!("{p}=MISSING"))
                    )
                })
                .collect();
            queries.join("\n")
        }
        "brew" => {
            let queries: Vec<String> = packages
                .iter()
                .map(|p| {
                    format!(
                        "brew list --versions {} 2>/dev/null || echo {}",
                        sh_squote(p),
                        sh_squote(&format!("{p}=MISSING"))
                    )
                })
                .collect();
            queries.join("\n")
        }
        other => format!("echo 'unsupported provider: {other}'"),
    }
}