Skip to main content

greentic_bundle/catalog/
resolve.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result, bail};
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6
7use super::cache;
8use super::client::{CatalogArtifactClient, DistributorCatalogClient};
9use super::registry::{CatalogEntry, parse_catalog};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CatalogResolveOptions {
13    pub offline: bool,
14    pub write_cache: bool,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct CatalogLockEntry {
19    pub requested_ref: String,
20    pub resolved_ref: String,
21    pub digest: String,
22    pub source: String,
23    pub item_count: usize,
24    pub item_ids: Vec<String>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub cache_path: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct CatalogResolution {
31    pub entries: Vec<CatalogLockEntry>,
32    pub cache_writes: Vec<String>,
33    pub discovered_items: Vec<CatalogEntry>,
34}
35
36impl CatalogResolution {
37    pub fn empty() -> Self {
38        Self {
39            entries: Vec::new(),
40            cache_writes: Vec::new(),
41            discovered_items: Vec::new(),
42        }
43    }
44}
45
46pub fn resolve_catalogs(
47    root: &Path,
48    references: &[String],
49    options: &CatalogResolveOptions,
50) -> Result<CatalogResolution> {
51    resolve_catalogs_with_client(root, references, options, &DistributorCatalogClient)
52}
53
54pub fn resolve_catalogs_with_client(
55    root: &Path,
56    references: &[String],
57    options: &CatalogResolveOptions,
58    client: &dyn CatalogArtifactClient,
59) -> Result<CatalogResolution> {
60    let mut entries = Vec::new();
61    let mut cache_writes = Vec::new();
62    let mut discovered_items = Vec::new();
63
64    let mut refs = references.to_vec();
65    refs.sort();
66    refs.dedup();
67
68    let total = refs.len();
69    for (index, reference) in refs.iter().enumerate() {
70        eprintln!("  [{}/{}] Resolving: {reference}", index + 1, total);
71        let resolved = resolve_one(root, reference, options, client)?;
72        cache_writes.extend(resolved.1);
73        discovered_items.extend(resolved.2);
74        entries.push(resolved.0);
75    }
76
77    cache_writes.sort();
78    cache_writes.dedup();
79    discovered_items.sort_by(|left, right| {
80        left.id
81            .cmp(&right.id)
82            .then(left.reference.cmp(&right.reference))
83    });
84    discovered_items
85        .dedup_by(|left, right| left.id == right.id && left.reference == right.reference);
86
87    Ok(CatalogResolution {
88        entries,
89        cache_writes,
90        discovered_items,
91    })
92}
93
94fn resolve_one(
95    root: &Path,
96    reference: &str,
97    options: &CatalogResolveOptions,
98    client: &dyn CatalogArtifactClient,
99) -> Result<(CatalogLockEntry, Vec<String>, Vec<CatalogEntry>)> {
100    if let Some(local_path) = parse_local_reference(root, reference) {
101        let resolved_path = if local_path.is_absolute() {
102            local_path
103        } else {
104            root.join(local_path)
105        };
106        let bytes = std::fs::read(&resolved_path)
107            .with_context(|| format!("read catalog {}", resolved_path.display()))?;
108        let digest = digest_hex(&bytes);
109        let source = resolved_path.display().to_string();
110        let parsed = parse_catalog(&bytes, &source)?;
111        let cache_paths = if options.write_cache {
112            cache::cache_catalog_bytes(root, reference, &digest, &bytes)?
113        } else {
114            Vec::new()
115        };
116        return Ok((
117            CatalogLockEntry {
118                requested_ref: reference.to_string(),
119                resolved_ref: source,
120                digest,
121                source: "local_file".to_string(),
122                item_count: parsed.summary.item_count,
123                item_ids: parsed.summary.item_ids,
124                cache_path: cache::resolve_cached_path(root, reference)?
125                    .map(|path| relative_display(root, &path)),
126            },
127            cache_paths
128                .into_iter()
129                .map(|path| relative_display(root, &path))
130                .collect(),
131            parsed.entries,
132        ));
133    }
134
135    if let Some(cached_path) = cache::resolve_cached_path(root, reference)? {
136        let bytes = std::fs::read(&cached_path)
137            .with_context(|| format!("read cached catalog {}", cached_path.display()))?;
138        let digest = digest_hex(&bytes);
139        let source = cached_path.display().to_string();
140        let parsed = parse_catalog(&bytes, &source)?;
141        return Ok((
142            CatalogLockEntry {
143                requested_ref: reference.to_string(),
144                resolved_ref: reference.to_string(),
145                digest,
146                source: "workspace_cache".to_string(),
147                item_count: parsed.summary.item_count,
148                item_ids: parsed.summary.item_ids,
149                cache_path: Some(relative_display(root, &cached_path)),
150            },
151            Vec::new(),
152            parsed.entries,
153        ));
154    }
155
156    if options.offline {
157        bail!(
158            "catalog {reference} is not cached in {} and offline mode is enabled; seed the workspace-local cache first or rerun without --offline",
159            root.join(super::CACHE_ROOT_DIR).display()
160        );
161    }
162
163    let fetched = client.fetch_catalog(root, reference)?;
164    let parsed = parse_catalog(&fetched.bytes, reference)?;
165    let cache_paths = if options.write_cache {
166        cache::cache_catalog_bytes(root, reference, &fetched.digest, &fetched.bytes)?
167    } else {
168        Vec::new()
169    };
170    Ok((
171        CatalogLockEntry {
172            requested_ref: reference.to_string(),
173            resolved_ref: fetched.resolved_ref,
174            digest: fetched.digest,
175            source: "remote".to_string(),
176            item_count: parsed.summary.item_count,
177            item_ids: parsed.summary.item_ids,
178            cache_path: cache::resolve_cached_path(root, reference)?
179                .map(|path| relative_display(root, &path)),
180        },
181        cache_paths
182            .into_iter()
183            .map(|path| relative_display(root, &path))
184            .collect(),
185        parsed.entries,
186    ))
187}
188
189fn parse_local_reference(root: &Path, reference: &str) -> Option<PathBuf> {
190    if let Some(path) = reference.strip_prefix("file://") {
191        let trimmed = path.trim();
192        if trimmed.is_empty() {
193            return None;
194        }
195        return Some(PathBuf::from(trimmed));
196    }
197    if reference.contains("://") {
198        return None;
199    }
200    let candidate = PathBuf::from(reference);
201    if candidate.is_absolute() || candidate.exists() || root.join(&candidate).exists() {
202        return Some(candidate);
203    }
204    None
205}
206
207fn digest_hex(bytes: &[u8]) -> String {
208    let mut hasher = Sha256::new();
209    hasher.update(bytes);
210    let digest = hasher.finalize();
211    let mut out = String::from("sha256:");
212    for byte in digest {
213        out.push_str(&format!("{byte:02x}"));
214    }
215    out
216}
217
218fn relative_display(root: &Path, path: &Path) -> String {
219    path.strip_prefix(root)
220        .unwrap_or(path)
221        .display()
222        .to_string()
223}