nomograph-kit 0.7.0

Verified tool registry manager -- manages developer toolchains from git-based registries
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Phase 1: Check upstream releases and compute checksums.
//!
//! Deterministic work only -- no LLM calls. For each tool in the registry:
//! 1. Query the upstream release API for the latest stable version
//! 2. If newer than pinned, download release assets for both platforms
//! 3. Compute SHA256 checksums of downloaded assets
//! 4. Verify against upstream-published checksum files where available
//! 5. Query GitHub Advisory Database for known CVEs on the pinned version
//!
//! Output: updates.json with update candidates for Phase 2.

use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use anyhow::{Context, Result};
use sha2::{Digest, Sha256};
use std::io::Read;

use crate::platform::Platform;
use crate::tool::{self, ChecksumFormat, Source, ToolDef};
use crate::verify;

use super::{Advisory, CheckOutput, UpdateCandidate};

const PLATFORMS: [Platform; 2] = [Platform::MacosArm64, Platform::LinuxX64];

/// Run the check phase: scan all tools for upstream updates.
///
/// `registry_dir` is the path to the registry root (containing `tools/`).
/// Results are written to `output` as JSON.
pub fn check(registry_dir: &Path, output: &Path) -> Result<()> {
    let tools = tool::load_registry_tools(registry_dir)?;
    let total = tools.len();

    eprintln!("kit check: scanning {} tools for updates\n", total);

    let mut updates: Vec<UpdateCandidate> = Vec::new();
    let mut errors: Vec<String> = Vec::new();
    let mut advisories: HashMap<String, Vec<Advisory>> = HashMap::new();

    for def in &tools {
        match check_tool(def) {
            Ok(Some(candidate)) => {
                // Checksum mismatches during a version bump are expected -- the old
                // checksum file may not match the new binary, or asset naming may have
                // changed. Record the status in the candidate for the evaluate step
                // to assess. Do NOT treat this as an error.
                for (platform, verified) in &candidate.verified {
                    if *verified == Some(false) {
                        eprintln!(
                            "    note: {} {} checksum mismatch on version bump -- flagged for review",
                            candidate.name, platform
                        );
                    }
                }
                eprintln!(
                    "  {}: {} -> {}",
                    candidate.name, candidate.current_version, candidate.new_version
                );
                updates.push(candidate);
            }
            Ok(None) => {
                eprintln!("  {}: {} (up to date)", def.name, def.version);
            }
            Err(e) => {
                eprintln!("  error checking {}: {e:#}", def.name);
                errors.push(format!("{}: {e}", def.name));
            }
        }

        // Check for known vulnerabilities on the current pinned version
        match check_advisories(def) {
            Ok(advs) if !advs.is_empty() => {
                for a in &advs {
                    eprintln!(
                        "  ADVISORY: {} {} -- {} ({}): {}",
                        def.name, def.version, a.id, a.severity, a.summary
                    );
                }
                advisories.insert(def.name.clone(), advs);
            }
            Ok(_) => {}
            Err(e) => {
                eprintln!("  warning: advisory check failed for {}: {e}", def.name);
            }
        }
    }

    let result = CheckOutput {
        updates_found: updates.len(),
        updates,
        errors,
        advisories,
        tools_checked: total,
    };

    let json = serde_json::to_string_pretty(&result).context("failed to serialize updates.json")?;
    std::fs::write(output, &json)
        .with_context(|| format!("failed to write {}", output.display()))?;

    eprintln!("\n{}", "=".repeat(60));
    eprintln!("Checked: {total}");
    eprintln!("Updates: {}", result.updates_found);
    eprintln!("Advisories: {}", result.advisories.len());
    eprintln!("Errors:  {}", result.errors.len());

    // Checksum mismatches during version bumps are NOT fatal. They are recorded
    // in the report for the evaluate/sense step to classify. The sense pipeline
    // only fails on infrastructure errors (network failures, auth issues).
    let mismatches: usize = result
        .updates
        .iter()
        .flat_map(|u| u.verified.values())
        .filter(|v| **v == Some(false))
        .count();

    if mismatches > 0 {
        eprintln!(
            "\n  note: {} checksum mismatch(es) on version bumps -- flagged for review",
            mismatches
        );
    }

    Ok(())
}

/// Check a single tool for upstream updates.
/// Returns `Ok(None)` if already up to date.
fn check_tool(def: &ToolDef) -> Result<Option<UpdateCandidate>> {
    match def.source {
        Source::Github => check_github(def),
        Source::Gitlab => check_gitlab(def),
        Source::Npm => check_npm(def),
        Source::Crates => check_crates(def),
        Source::Direct => {
            eprintln!(
                "  {}: {} (skip -- direct source has no upstream release API to check)",
                def.name, def.version
            );
            Ok(None)
        }
        Source::Rustup => {
            eprintln!(
                "  {}: {} (skip -- version managed by rustup, not a registry release)",
                def.name, def.version
            );
            Ok(None)
        }
    }
}

// ---------------------------------------------------------------------------
// Source-specific checkers
// ---------------------------------------------------------------------------

fn check_github(def: &ToolDef) -> Result<Option<UpdateCandidate>> {
    let repo = def
        .repo
        .as_deref()
        .context("github source requires 'repo' field")?;

    let tag = match gh_latest_stable_tag(repo)? {
        Some(t) => t,
        None => return Ok(None),
    };

    let latest = extract_version(&tag, &def.tag_prefix);
    if latest == def.version {
        return Ok(None);
    }

    let mut candidate = UpdateCandidate {
        name: def.name.clone(),
        current_version: def.version.clone(),
        new_version: latest.clone(),
        tag: tag.clone(),
        checksums: HashMap::new(),
        verified: HashMap::new(),
        note: None,
    };

    let tmp = tempfile::tempdir().context("failed to create temp dir")?;

    for platform in &PLATFORMS {
        download_and_verify(def, &latest, &tag, *platform, tmp.path(), &mut candidate)?;
    }

    Ok(Some(candidate))
}

fn check_gitlab(def: &ToolDef) -> Result<Option<UpdateCandidate>> {
    let project_ref = if let Some(pid) = def.project_id {
        pid.to_string()
    } else if let Some(ref repo) = def.repo {
        repo.replace('/', "%2F")
    } else {
        anyhow::bail!("gitlab source requires project_id or repo");
    };

    let output = run_cmd(
        "glab",
        &["api", &format!("projects/{project_ref}/releases?per_page=5")],
        None,
    )?;

    let releases: Vec<serde_json::Value> =
        serde_json::from_str(&output).context("failed to parse gitlab releases JSON")?;

    if releases.is_empty() {
        return Ok(None);
    }

    // Find latest non-upcoming release
    let release = releases
        .iter()
        .find(|r| !r["upcoming_release"].as_bool().unwrap_or(false))
        .unwrap_or(&releases[0]);

    let tag = release["tag_name"]
        .as_str()
        .context("missing tag_name in release")?
        .to_string();

    let latest = extract_version(&tag, &def.tag_prefix);
    if latest == def.version {
        return Ok(None);
    }

    let mut candidate = UpdateCandidate {
        name: def.name.clone(),
        current_version: def.version.clone(),
        new_version: latest.clone(),
        tag: tag.clone(),
        checksums: HashMap::new(),
        verified: HashMap::new(),
        note: None,
    };

    let tmp = tempfile::tempdir().context("failed to create temp dir")?;

    // For own tools with project_id, resolve asset URLs from the release links
    if def.project_id.is_some() {
        for platform in &PLATFORMS {
            let asset_name = match asset_name_for(def, &latest, *platform) {
                Some(n) => n,
                None => continue,
            };

            // Search release asset links -- match exact name first,
            // then fall back to URL ending with the asset name.
            // Must not match .bundle, .sha256, or .sbom variants.
            let links = release["assets"]["links"].as_array();
            let url = links.and_then(|ls| {
                // Exact name match first
                ls.iter()
                    .find_map(|link| {
                        let name = link["name"].as_str().unwrap_or("");
                        let link_url = link["direct_asset_url"]
                            .as_str()
                            .or_else(|| link["url"].as_str());
                        if name == asset_name {
                            link_url.map(|s| s.to_string())
                        } else {
                            None
                        }
                    })
                    // Fall back to URL ending with exact asset name
                    .or_else(|| {
                        ls.iter().find_map(|link| {
                            let link_url = link["direct_asset_url"]
                                .as_str()
                                .or_else(|| link["url"].as_str());
                            if link_url.is_some_and(|u| u.ends_with(&format!("/{asset_name}"))) {
                                link_url.map(|s| s.to_string())
                            } else {
                                None
                            }
                        })
                    })
            });

            match url {
                Some(u) => {
                    download_and_verify_url(
                        def,
                        &latest,
                        &tag,
                        *platform,
                        &asset_name,
                        &u,
                        tmp.path(),
                        &mut candidate,
                    )?;
                }
                None => {
                    eprintln!(
                        "    {}: no download link found in release for {}",
                        platform.key(),
                        asset_name
                    );
                }
            }
        }
    } else {
        // Third-party gitlab tool -- standard release download URLs
        for platform in &PLATFORMS {
            download_and_verify(def, &latest, &tag, *platform, tmp.path(), &mut candidate)?;
        }
    }

    Ok(Some(candidate))
}

fn check_npm(def: &ToolDef) -> Result<Option<UpdateCandidate>> {
    let package = def.package.as_deref().unwrap_or(&def.name);

    let output = match run_cmd("npm", &["view", package, "version"], None) {
        Ok(o) => o,
        Err(_) => {
            eprintln!("  {}: {} (skip -- npm not available)", def.name, def.version);
            return Ok(None);
        }
    };
    let latest = output.trim().to_string();

    if latest.is_empty() || latest == def.version {
        return Ok(None);
    }

    Ok(Some(UpdateCandidate {
        name: def.name.clone(),
        current_version: def.version.clone(),
        new_version: latest,
        tag: String::new(),
        checksums: HashMap::new(),
        verified: HashMap::new(),
        note: Some("npm package -- integrity verified by npm on install".to_string()),
    }))
}

fn check_crates(def: &ToolDef) -> Result<Option<UpdateCandidate>> {
    let crate_name = def.crate_name.as_deref().unwrap_or(&def.name);

    let output = match run_cmd("cargo", &["search", crate_name, "--limit", "1"], None) {
        Ok(o) => o,
        Err(_) => {
            eprintln!("  {}: {} (skip -- cargo not available)", def.name, def.version);
            return Ok(None);
        }
    };

    // Parse: crate_name = "version"
    let latest = output
        .lines()
        .find(|line| line.split('=').next().map(|name| name.trim() == crate_name).unwrap_or(false))
        .and_then(|line| {
            let start = line.find('"')?;
            let end = line[start + 1..].find('"')?;
            Some(line[start + 1..start + 1 + end].to_string())
        });

    let latest = match latest {
        Some(v) if v != def.version => v,
        _ => return Ok(None),
    };

    Ok(Some(UpdateCandidate {
        name: def.name.clone(),
        current_version: def.version.clone(),
        new_version: latest,
        tag: String::new(),
        checksums: HashMap::new(),
        verified: HashMap::new(),
        note: Some("cargo crate -- checksums verified by cargo on install".to_string()),
    }))
}

// ---------------------------------------------------------------------------
// Download and verification helpers
// ---------------------------------------------------------------------------

/// Resolve the asset filename for a tool at a given version and platform.
fn asset_name_for(def: &ToolDef, version: &str, platform: Platform) -> Option<String> {
    let pattern = def.assets.get(platform.key())?;
    Some(pattern.replace("{version}", version))
}

/// Build the download URL for an asset.
fn asset_url_for(def: &ToolDef, version: &str, tag: &str, platform: Platform) -> Option<String> {
    let asset = asset_name_for(def, version, platform)?;

    match def.source {
        Source::Github => {
            let repo = def.repo.as_ref()?;
            Some(format!(
                "https://github.com/{repo}/releases/download/{tag}/{asset}"
            ))
        }
        Source::Gitlab => {
            if let Some(pid) = def.project_id {
                Some(format!(
                    "https://gitlab.com/api/v4/projects/{pid}/packages/generic/{name}/{tag}/{asset}",
                    name = def.name
                ))
            } else {
                let repo = def.repo.as_ref()?;
                Some(format!(
                    "https://gitlab.com/{repo}/-/releases/{tag}/downloads/{asset}"
                ))
            }
        }
        Source::Direct => Some(asset),
        _ => None,
    }
}

/// Build the checksum file URL for a tool at a given version and tag.
fn checksum_url_for(
    def: &ToolDef,
    version: &str,
    tag: &str,
    platform: Platform,
) -> Option<String> {
    let cfg = def.checksum.as_ref()?;
    let file = cfg.file.as_ref()?;

    let filename = if cfg.format == ChecksumFormat::Sha256PerAsset {
        let asset = asset_name_for(def, version, platform)?;
        format!("{asset}.sha256")
    } else {
        file.replace("{version}", version)
    };

    match def.source {
        Source::Github => {
            let repo = def.repo.as_ref()?;
            Some(format!(
                "https://github.com/{repo}/releases/download/{tag}/{filename}"
            ))
        }
        Source::Gitlab => {
            if let Some(pid) = def.project_id {
                Some(format!(
                    "https://gitlab.com/api/v4/projects/{pid}/packages/generic/{name}/{tag}/{filename}",
                    name = def.name
                ))
            } else {
                let repo = def.repo.as_ref()?;
                Some(format!(
                    "https://gitlab.com/{repo}/-/releases/{tag}/downloads/{filename}"
                ))
            }
        }
        _ => None,
    }
}

/// Download an asset and verify its checksum, populating the candidate struct.
fn download_and_verify(
    def: &ToolDef,
    version: &str,
    tag: &str,
    platform: Platform,
    tmp_dir: &Path,
    candidate: &mut UpdateCandidate,
) -> Result<()> {
    let asset_name = match asset_name_for(def, version, platform) {
        Some(n) => n,
        None => return Ok(()),
    };

    let url = match asset_url_for(def, version, tag, platform) {
        Some(u) => u,
        None => return Ok(()),
    };

    download_and_verify_url(def, version, tag, platform, &asset_name, &url, tmp_dir, candidate)
}

/// Download from a specific URL and verify checksum.
#[allow(clippy::too_many_arguments)]
fn download_and_verify_url(
    def: &ToolDef,
    version: &str,
    tag: &str,
    platform: Platform,
    asset_name: &str,
    url: &str,
    tmp_dir: &Path,
    candidate: &mut UpdateCandidate,
) -> Result<()> {
    let asset_path = tmp_dir.join(format!("{}-{asset_name}", platform.key()));

    eprintln!("    downloading {}: {asset_name}", platform.key());

    let client = https_client()?;
    match client.get(url).send() {
        Ok(resp) if resp.status().is_success() => {
            let bytes = resp.bytes().context("failed to read response body")?;
            std::fs::write(&asset_path, &bytes)
                .with_context(|| format!("failed to write {}", asset_path.display()))?;
        }
        Ok(resp) => {
            eprintln!(
                "    warning: download failed for {} (HTTP {})",
                platform.key(),
                resp.status()
            );
            candidate
                .checksums
                .insert(platform.key().to_string(), None);
            return Ok(());
        }
        Err(e) => {
            eprintln!("    warning: download failed for {}: {e}", platform.key());
            candidate
                .checksums
                .insert(platform.key().to_string(), None);
            return Ok(());
        }
    }

    // Compute SHA256 of the downloaded asset
    let computed = compute_sha256_file(&asset_path)?;
    candidate
        .checksums
        .insert(platform.key().to_string(), Some(computed.clone()));

    // Verify against upstream checksum file
    if def.checksum.is_some() {
        let checksum_url = checksum_url_for(def, version, tag, platform);
        if let Some(csum_url) = checksum_url {
            match client.get(&csum_url).send() {
                Ok(resp) if resp.status().is_success() => {
                    let body = resp.text().context("failed to read checksum body")?;

                    let format = def
                        .checksum
                        .as_ref()
                        .map(|c| &c.format)
                        .unwrap_or(&ChecksumFormat::Sha256);

                    match verify::parse_checksum_file(&body, asset_name, format) {
                        Ok(Some(expected)) => {
                            if computed == expected {
                                eprintln!("    {}: checksum VERIFIED", platform.key());
                                candidate
                                    .verified
                                    .insert(platform.key().to_string(), Some(true));
                            } else {
                                eprintln!(
                                    "    {}: checksum MISMATCH (expected={}, got={})",
                                    platform.key(),
                                    expected,
                                    computed
                                );
                                candidate
                                    .verified
                                    .insert(platform.key().to_string(), Some(false));
                            }
                        }
                        Ok(None) => {
                            eprintln!(
                                "    warning: {} not found in checksum file",
                                asset_name
                            );
                            candidate
                                .verified
                                .insert(platform.key().to_string(), None);
                        }
                        Err(e) => {
                            eprintln!(
                                "    warning: checksum parse error for {}: {e}",
                                platform.key()
                            );
                            candidate
                                .verified
                                .insert(platform.key().to_string(), None);
                        }
                    }
                }
                Ok(_) => {
                    eprintln!(
                        "    warning: could not download checksum file for {}",
                        platform.key()
                    );
                }
                Err(e) => {
                    eprintln!(
                        "    warning: checksum download failed for {}: {e}",
                        platform.key()
                    );
                }
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Advisory checking
// ---------------------------------------------------------------------------

/// Query the GitHub Advisory Database for known CVEs on the pinned version.
fn check_advisories(def: &ToolDef) -> Result<Vec<Advisory>> {
    let repo = match def.repo.as_deref() {
        Some(r) if def.source == Source::Github => r,
        _ => return Ok(vec![]),
    };

    let escaped_version = def.version.replace('.', "\\\\.");
    let jq_filter = format!(
        r#"[.[] | select(.vulnerabilities[]?.vulnerable_version_range | test("{escaped_version}"))]"#
    );

    let output = match run_cmd_opt(
        "gh",
        &[
            "api",
            &format!("repos/{repo}/security-advisories"),
            "--jq",
            &jq_filter,
        ],
        None,
    ) {
        Some(out) => out,
        None => return Ok(vec![]),
    };

    let trimmed = output.trim();
    if trimmed.is_empty() || trimmed == "[]" || trimmed == "null" {
        return Ok(vec![]);
    }

    let raw: Vec<serde_json::Value> =
        serde_json::from_str(trimmed).unwrap_or_default();

    Ok(raw
        .iter()
        .map(|a| Advisory {
            id: a["ghsa_id"].as_str().unwrap_or("?").to_string(),
            severity: a["severity"].as_str().unwrap_or("?").to_string(),
            summary: a["summary"]
                .as_str()
                .unwrap_or("?")
                .chars()
                .take(200)
                .collect(),
        })
        .collect())
}

// ---------------------------------------------------------------------------
// Upstream version query helpers
// ---------------------------------------------------------------------------

/// Get the latest stable tag from a GitHub repo using `gh`.
fn gh_latest_stable_tag(repo: &str) -> Result<Option<String>> {
    // First try `gh release view` for the latest release
    let output = run_cmd_opt(
        "gh",
        &[
            "release",
            "view",
            "--repo",
            repo,
            "--json",
            "tagName,isPrerelease",
        ],
        None,
    );

    if let Some(text) = output {
        let parsed: serde_json::Value =
            serde_json::from_str(&text).context("failed to parse gh release view output")?;

        if !parsed["isPrerelease"].as_bool().unwrap_or(true)
            && let Some(tag) = parsed["tagName"].as_str()
        {
            return Ok(Some(tag.to_string()));
        }
    }

    // Fall back to listing releases and finding the latest stable one
    let list_output = run_cmd_opt(
        "gh",
        &[
            "release",
            "list",
            "--repo",
            repo,
            "--limit",
            "10",
            "--json",
            "tagName,isPrerelease,isLatest",
        ],
        None,
    );

    if let Some(text) = list_output {
        let releases: Vec<serde_json::Value> =
            serde_json::from_str(&text).unwrap_or_default();

        // Find first non-prerelease
        for r in &releases {
            if !r["isPrerelease"].as_bool().unwrap_or(true)
                && let Some(tag) = r["tagName"].as_str()
            {
                return Ok(Some(tag.to_string()));
            }
        }
    }

    Ok(None)
}

/// Strip tag prefix to get version string.
fn extract_version(tag: &str, prefix: &str) -> String {
    if !prefix.is_empty() && tag.starts_with(prefix) {
        tag[prefix.len()..].to_string()
    } else {
        tag.to_string()
    }
}

// ---------------------------------------------------------------------------
// Infrastructure
// ---------------------------------------------------------------------------

/// Build an HTTPS-only reqwest blocking client with 60s timeout.
fn https_client() -> Result<reqwest::blocking::Client> {
    reqwest::blocking::Client::builder()
        .https_only(true)
        .timeout(Duration::from_secs(60))
        .redirect(reqwest::redirect::Policy::limited(5))
        .build()
        .context("failed to build HTTP client")
}

/// Compute SHA256 of a file, returning the hex digest.
fn compute_sha256_file(path: &Path) -> Result<String> {
    let mut file =
        std::fs::File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 8192];
    loop {
        let n = file
            .read(&mut buf)
            .with_context(|| format!("read error on {}", path.display()))?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hex::encode(hasher.finalize()))
}

/// Run a subprocess command, returning stdout on success.
fn run_cmd(program: &str, args: &[&str], cwd: Option<&Path>) -> Result<String> {
    let mut cmd = Command::new(program);
    cmd.args(args);
    if let Some(dir) = cwd {
        cmd.current_dir(dir);
    }

    let output = cmd
        .output()
        .with_context(|| format!("failed to execute {program}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!(
            "{program} {} failed (exit {}): {}",
            args.first().unwrap_or(&""),
            output.status,
            stderr.trim()
        );
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Run a subprocess command, returning None on any failure instead of an error.
fn run_cmd_opt(program: &str, args: &[&str], cwd: Option<&Path>) -> Option<String> {
    let mut cmd = Command::new(program);
    cmd.args(args);
    if let Some(dir) = cwd {
        cmd.current_dir(dir);
    }

    let output = cmd.output().ok()?;
    if !output.status.success() {
        return None;
    }

    Some(String::from_utf8_lossy(&output.stdout).to_string())
}