Skip to main content

helm_rs/repo/
mod.rs

1//! A chart repository's `index.yaml`, read natively.
2//!
3//! Mirrors `pkg/repo/v1/index.go` (Helm v4.3.0): the data model, the loader (YAML or JSON, entries
4//! sorted newest first) and the `Get` lookup, with Masterminds semver constraints
5//! ([`version`](crate::version)). One difference: entries are not validated the way Helm drops
6//! invalid ones.
7
8use std::collections::BTreeMap;
9use std::path::Path;
10
11use jiff::Timestamp;
12use serde::{Deserialize, Deserializer};
13
14use crate::chart::Metadata;
15use crate::version::{Constraints, Version};
16
17#[cfg(test)]
18mod tests;
19
20/// Everything that can go wrong reading or querying an index.
21#[derive(Debug, thiserror::Error)]
22#[non_exhaustive]
23pub enum Error {
24    /// The file could not be read.
25    #[error(transparent)]
26    Io(#[from] std::io::Error),
27
28    /// The content is neither valid YAML nor valid JSON for an index.
29    #[error(transparent)]
30    Yaml(#[from] serde_norway::Error),
31
32    /// The index file is empty (Helm's `ErrEmptyIndexYaml`).
33    #[error("empty index.yaml file")]
34    Empty,
35
36    /// The index has no `apiVersion` (Helm's `ErrNoAPIVersion`).
37    #[error("no API version specified")]
38    NoApiVersion,
39
40    /// The index has no entry for the chart (Helm's `ErrNoChartName`).
41    #[error("no chart name found: {0}")]
42    NoChartName(String),
43
44    /// The chart has no version that matches (Helm's `ErrNoChartVersion`); empty `version` means
45    /// the chart has no stable version at all.
46    #[error("no chart version found for {name}-{version}")]
47    NoChartVersion {
48        /// The chart name.
49        name: String,
50        /// The requested version or constraint.
51        version: String,
52    },
53
54    /// The requested constraint does not parse.
55    #[error("invalid version constraint {constraint:?}: {source}")]
56    InvalidConstraint {
57        /// The constraint as given.
58        constraint: String,
59        /// Why it did not parse.
60        source: crate::version::Error,
61    },
62}
63
64/// A repository index (`IndexFile`).
65#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
66pub struct Index {
67    /// The index format version, `v1`.
68    #[serde(default, rename = "apiVersion")]
69    pub api_version: String,
70    /// When the index was generated.
71    #[serde(default)]
72    pub generated: Option<Timestamp>,
73    /// The versions of each chart, newest first once loaded.
74    #[serde(default, deserialize_with = "entries")]
75    pub entries: BTreeMap<String, Vec<ChartVersion>>,
76    /// The signing public keys the repository advertises.
77    #[serde(default, rename = "publicKeys", deserialize_with = "null_default")]
78    pub public_keys: Vec<String>,
79    /// Annotations Helm does not interpret.
80    #[serde(default, deserialize_with = "null_default")]
81    pub annotations: BTreeMap<String, String>,
82}
83
84/// One chart version in an index (`ChartVersion`): the chart's metadata plus where to get it.
85#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
86pub struct ChartVersion {
87    /// The `Chart.yaml` metadata.
88    #[serde(flatten)]
89    pub metadata: Metadata,
90    /// Where the chart archive can be downloaded (relative to the repository or absolute).
91    #[serde(default, deserialize_with = "null_default")]
92    pub urls: Vec<String>,
93    /// When the version was added to the index.
94    #[serde(default)]
95    pub created: Option<Timestamp>,
96    /// Whether the version was removed from the repository.
97    #[serde(default)]
98    pub removed: bool,
99    /// The SHA-256 digest of the archive.
100    #[serde(default)]
101    pub digest: String,
102}
103
104/// Reads a possibly `null` value as its default.
105fn null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
106where
107    D: Deserializer<'de>,
108    T: Deserialize<'de> + Default,
109{
110    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
111}
112
113/// Reads the entries, dropping `null` versions as Helm does.
114fn entries<'de, D: Deserializer<'de>>(
115    deserializer: D,
116) -> Result<BTreeMap<String, Vec<ChartVersion>>, D::Error> {
117    let raw: BTreeMap<String, Option<Vec<Option<ChartVersion>>>> = null_default(deserializer)?;
118
119    Ok(raw
120        .into_iter()
121        .map(|(name, versions)| (name, versions.into_iter().flatten().flatten().collect()))
122        .collect())
123}
124
125impl Index {
126    /// Reads an index file (`LoadIndexFile`): YAML or JSON, versions sorted newest first.
127    pub fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
128        Self::parse(&std::fs::read_to_string(path)?)
129    }
130
131    /// Parses the text of an index (`loadIndex`).
132    pub fn parse(text: &str) -> Result<Self, Error> {
133        if text.trim().is_empty() {
134            return Err(Error::Empty);
135        }
136
137        let mut index: Self = serde_norway::from_str(text)?;
138
139        index.sort_entries();
140
141        if index.api_version.is_empty() {
142            return Err(Error::NoApiVersion);
143        }
144
145        Ok(index)
146    }
147
148    /// Sorts every chart's versions newest first (`SortEntries`); versions that are not semantic
149    /// versions go last.
150    pub fn sort_entries(&mut self) {
151        for versions in self.entries.values_mut() {
152            versions.sort_by(|a, b| {
153                let a = Version::parse(&a.metadata.version).ok();
154                let b = Version::parse(&b.metadata.version).ok();
155
156                match (a, b) {
157                    (Some(a), Some(b)) => b.compare(&a),
158                    (a, b) => b.is_some().cmp(&a.is_some()),
159                }
160            });
161        }
162    }
163
164    /// Finds a chart version (`Get`): an empty `version` selects the newest stable one; otherwise
165    /// an exact version string wins, then the newest version that satisfies the constraint.
166    pub fn get(&self, name: &str, version: &str) -> Result<&ChartVersion, Error> {
167        let versions = self
168            .entries
169            .get(name)
170            .ok_or_else(|| Error::NoChartName(name.to_owned()))?;
171        let not_found = || Error::NoChartVersion {
172            name: name.to_owned(),
173            version: version.to_owned(),
174        };
175
176        if versions.is_empty() {
177            return Err(not_found());
178        }
179
180        let requirement = if version.is_empty() {
181            Constraints::parse("*")
182        } else {
183            Constraints::parse(version)
184        }
185        .map_err(|source| Error::InvalidConstraint {
186            constraint: version.to_owned(),
187            source,
188        })?;
189
190        if !version.is_empty()
191            && let Some(exact) = versions.iter().find(|v| v.metadata.version == version)
192        {
193            return Ok(exact);
194        }
195
196        versions
197            .iter()
198            .find(|v| Version::parse(&v.metadata.version).is_ok_and(|v| requirement.matches(&v)))
199            .ok_or_else(not_found)
200    }
201
202    /// True when the index has exactly this chart version (`Has`).
203    #[must_use]
204    pub fn has(&self, name: &str, version: &str) -> bool {
205        self.get(name, version).is_ok()
206    }
207}