ctb_formats_docker/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! CLI runner for docker image archive validation.
21
22use crate::{ValidationReport, validate_docker_archive};
23use anyhow::{Context, Result, anyhow};
24use ctb_utilities::ToolResult;
25use std::fmt::Write;
26use std::path::Path;
27
28/// Formats the validation report as user-facing text.
29fn format_report(report: &ValidationReport, strict: bool) -> Result<String> {
30    let success = report.is_success(strict);
31    let mut out = String::new();
32
33    if success {
34        out.push_str("Docker image validation successful:\n");
35    } else {
36        out.push_str("Docker image validation failed:\n");
37    }
38
39    out.push_str("  Metadata files:\n");
40    if report.validated_metadata.contains("manifest.json") {
41        out.push_str("    ✓ manifest.json (valid JSON)\n");
42    } else {
43        out.push_str("    ✗ manifest.json (missing or invalid JSON)\n");
44    }
45    if report.validated_metadata.contains("index.json") {
46        out.push_str("    ✓ index.json (valid JSON)\n");
47    }
48    if report.validated_metadata.contains("oci-layout") {
49        out.push_str("    ✓ oci-layout (valid JSON)\n");
50    }
51    if report.validated_metadata.contains("repositories") {
52        out.push_str("    ✓ repositories (valid JSON)\n");
53    }
54
55    out.push_str("  Blobs:\n");
56    if report.missing_blobs.is_empty() {
57        writeln!(
58            out,
59            "    ✓ {}/{} referenced blobs present",
60            report.referenced_blobs_count, report.referenced_blobs_count
61        )
62        .map_err(|e| anyhow!("{e}"))?;
63    } else {
64        writeln!(
65            out,
66            "    ✗ {} referenced blob(s) missing:",
67            report.missing_blobs.len()
68        )
69        .map_err(|e| anyhow!("{e}"))?;
70        for b in &report.missing_blobs {
71            writeln!(out, "        - {b}").map_err(|e| anyhow!("{e}"))?;
72        }
73    }
74
75    if report.checksum_mismatches.is_empty() {
76        writeln!(
77            out,
78            "    ✓ {} blob checksum(s) verified (SHA-256)",
79            report.valid_blobs_count
80        )
81        .map_err(|e| anyhow!("{e}"))?;
82    } else {
83        writeln!(
84            out,
85            "    ✗ {} blob checksum mismatch(es):",
86            report.checksum_mismatches.len()
87        )
88        .map_err(|e| anyhow!("{e}"))?;
89        for m in &report.checksum_mismatches {
90            writeln!(
91                out,
92                "        - {}: expected {}, computed {}",
93                m.blob_path, m.expected_hash, m.computed_hash
94            )
95            .map_err(|e| anyhow!("{e}"))?;
96        }
97    }
98
99    if !report.unreferenced_blobs.is_empty() {
100        if strict {
101            writeln!(
102                out,
103                "    ✗ {} unreferenced blob(s) found (strict mode):",
104                report.unreferenced_blobs.len()
105            )
106            .map_err(|e| anyhow!("{e}"))?;
107            for b in &report.unreferenced_blobs {
108                writeln!(out, "        - {b}").map_err(|e| anyhow!("{e}"))?;
109            }
110        } else {
111            writeln!(
112                out,
113                "    ℹ {} unreferenced blob(s) present",
114                report.unreferenced_blobs.len()
115            )
116            .map_err(|e| anyhow!("{e}"))?;
117        }
118    }
119
120    Ok(out)
121}
122
123/// Runs validation on a docker image archive file or standard input.
124pub fn run_validate_docker_image(
125    file: Option<&Path>,
126    strict: bool,
127) -> Result<ToolResult> {
128    let report = match file {
129        Some(p) if p.to_str() != Some("-") => {
130            let f = std::fs::File::open(p)
131                .with_context(|| format!("Failed to open {}", p.display()))?;
132            let reader = std::io::BufReader::new(f);
133            validate_docker_archive(reader, strict)?
134        }
135        _ => {
136            let stdin = std::io::stdin();
137            let reader = std::io::BufReader::new(stdin.lock());
138            validate_docker_archive(reader, strict)?
139        }
140    };
141
142    let success = report.is_success(strict);
143    let output_text = format_report(&report, strict)?;
144
145    if success {
146        Ok(ToolResult::immediate_ok(output_text.into_bytes()))
147    } else {
148        Ok(ToolResult::immediate_err(output_text.into_bytes(), 1))
149    }
150}