Skip to main content

verctl_core/config/
assets.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4use std::{fmt, fs};
5
6use anyhow::{Context, Result, ensure};
7use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
8use garde::Validate;
9use serde::de::value::MapAccessDeserializer;
10use serde::de::{MapAccess, Visitor};
11use serde::{Deserialize, Serialize, de};
12
13use super::validate_assets::{
14    a_packslip_table, a_tarball_name, an_asset_name, asset_targets_are_sound, at_least_one_target,
15    binary_is_not_beside_files, dir_comes_with_files, every_key_is_one_plain_name,
16    files_come_with_dir, generated_paths_are_sound, one_archive_per_target, one_plain_name,
17    only_placeholders, runner_is_declared, target_files_come_with_dir,
18};
19use super::{ArtifactTable, Config};
20pub use crate::asset_rules::AssetFormat;
21
22/// is how GitHub finds it. Every label is required at once, so a three-label
23/// runner is one machine carrying three labels, not three machines.
24#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
25#[serde(deny_unknown_fields)]
26#[garde(context(Config))]
27#[non_exhaustive]
28pub struct Runner {
29    /// Every label at once. A machine with none cannot be found at all.
30    #[garde(custom(at_least_one("label")))]
31    pub labels: Vec<String>,
32}
33
34/// One job, declared under `ci`. The key names it; `runners` names the
35/// machines from `runners` it runs on, one check each. No `os`/`arch`/
36/// `triple`: validation runs a machine's checks, it does not cross-compile.
37#[derive(Debug, Clone, Deserialize, Default)]
38#[serde(deny_unknown_fields)]
39#[non_exhaustive]
40pub struct Job {
41    /// Names from `runners` this job runs on. Omit for one `ubuntu-26.04`
42    /// machine.
43    pub runners: Option<Vec<String>>,
44}
45
46/// Native GitHub Release tarballs, plus the recipe every target shares. Omit
47/// for libraries. Each named sub-mapping is one target.
48///
49/// A tarball contains the one `binary`, or the `files` packed from `dir`. Use
50/// `files` when a release needs more than its binary, such as a second
51/// executable, a service unit, or a licence. A target that ships other files
52/// lists its own `files`, which replace the shared list for that target.
53#[derive(Debug, Clone, Default, Validate)]
54#[garde(context(Config))]
55#[garde(allow_unvalidated)]
56#[non_exhaustive]
57pub struct Assets {
58    /// The binary name. Defaults to the first package's name.
59    pub bin: Option<String>,
60    /// Ran once per target before `build`. Stock rust recipe uses rustup.
61    pub prepare: Option<Vec<String>>,
62    /// How to produce the binary. Stock rust recipe is `cargo build --release`.
63    pub build: Option<Vec<String>>,
64    /// Path to the built binary, with `{bin}`, `{triple}`, `{os}`, and
65    /// `{arch}`. Omit for `target/{triple}/release/{bin}`. Unused when `dir`
66    /// and `files` specify what to pack, so it may not be set beside them.
67    #[garde(custom(binary_is_not_beside_files))]
68    pub binary: Option<String>,
69    /// The directory `files` are packed from, relative to the directory
70    /// containing `.ctl/`, with the same placeholders as `binary`. Omit, with
71    /// `files`, to pack the one `binary`.
72    #[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
73    pub dir: Option<PathBuf>,
74    /// Paths under `dir` packed into the tarball of every target that lists
75    /// none of its own, with the same placeholders. Each keeps its place under
76    /// `dir`. A directory is packed whole. Omit, with `dir`, to pack the one
77    /// `binary`, or when every target lists its own.
78    #[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
79    pub files: Vec<PathBuf>,
80    /// Files written from a command's output and packed into the tarball of
81    /// every target beside the binary, such as a usage spec or a man page the
82    /// built binary prints. Omit when the tarball contains nothing generated.
83    #[garde(dive, custom(generated_paths_are_sound))]
84    pub generated: Vec<Generated>,
85    /// Every remaining sub-mapping: `assets.linux-x64` and friends. A typo'd
86    /// recipe key lands here and fails as an unknown target, loudly.
87    /// [`Config::load`] declares this field to ctl-core as flattened,
88    /// so a problem names `assets.<id>` and lands on that key's line.
89    #[garde(dive, custom(asset_targets_are_sound))]
90    pub targets: BTreeMap<String, AssetTarget>,
91}
92
93impl Assets {
94    /// The keys under `assets` that are settings, every other key being a
95    /// target id. A reader that takes only the target ids of an old config
96    /// leaves these out.
97    pub const SETTINGS: [&'static str; 7] = [
98        "bin",
99        "prepare",
100        "build",
101        "binary",
102        "dir",
103        "files",
104        "generated",
105    ];
106}
107
108/// One file `release asset` writes from a command's output and packs into a
109/// tarball. A host that installs the tarball then gets a file it cannot
110/// generate at install time, such as a man page, which mise installs only from
111/// a file.
112#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
113#[serde(deny_unknown_fields)]
114#[garde(context(Config))]
115#[garde(allow_unvalidated)]
116#[non_exhaustive]
117pub struct Generated {
118    /// Where the file lands under the directory the tarball is cut from, with
119    /// `{bin}`, `{id}`, `{os}`, `{arch}`, and `{triple}`. The load checks it
120    /// for each target: it stays inside the tarball, names one file, and
121    /// replaces nothing the tarball packs.
122    pub path: String,
123    /// The command whose standard output is the file's content, run without a
124    /// shell. `{binary}` is the binary the target built, or the one
125    /// `--prebuilt-self` staged, and the placeholders of `path` and
126    /// `{version}` are replaced too.
127    #[garde(custom(at_least_one("argument")))]
128    pub run: Vec<String>,
129}
130
131/// One build target: the platform it produces and the single machine that
132/// builds it. One asset, one machine, so `runner` is not a list.
133#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
134#[serde(deny_unknown_fields)]
135#[garde(context(Config))]
136#[garde(allow_unvalidated)]
137#[non_exhaustive]
138pub struct AssetTarget {
139    /// Name from `runners` of the machine that builds this target.
140    pub runner: Option<String>,
141    /// Operating system name. Defaults from a known target id.
142    pub os: Option<String>,
143    /// CPU architecture name. Defaults from a known target id.
144    pub arch: Option<String>,
145    /// Target triple. Defaults from a known target id.
146    pub triple: Option<String>,
147    /// Output format of this target's asset: `tar.gz` (default), `zip`, or
148    /// `raw`.
149    #[serde(default)]
150    pub format: AssetFormat,
151    /// Ran before `build` for this target alone, in place of the shared
152    /// `assets.prepare`, with the same placeholders. Use it when one platform
153    /// needs a toolchain the others do not, such as a musl C compiler.
154    pub prepare: Option<Vec<String>>,
155    /// How to produce this target's binary or asset, in place of the shared
156    /// `assets.build`, with the same placeholders.
157    pub build: Option<Vec<String>>,
158    /// The uploaded asset's file name, with `{bin}`, `{version}`, `{os}`,
159    /// `{arch}`, and `{id}`, where `{os}` renders `macos` for `darwin`.
160    /// Applies to every format and cannot be set beside `tarball`.
161    #[garde(inner(custom(an_asset_name)))]
162    pub name: Option<String>,
163    /// The tarball's file name, with `{bin}`, `{version}`, `{os}`, and
164    /// `{arch}`, where `{os}` renders `macos` for `darwin`. Omit for
165    /// `{bin}_{version}_{os}_{arch}.tar.gz`. Set it when two targets share an
166    /// os and an arch, such as a glibc and a musl build, which would otherwise
167    /// render one name.
168    #[garde(inner(custom(a_tarball_name)))]
169    pub tarball: Option<String>,
170    /// Path to the existing file staged as-is when `format` is `raw`, relative
171    /// to the repository root, with `{bin}`, `{version}`, `{id}`, `{os}`,
172    /// `{arch}`, and `{triple}`. Required when `format` is `raw` and `external`
173    /// is `false`.
174    #[serde(default)]
175    #[garde(inner(custom(inside_the_repo)))]
176    pub file: Option<PathBuf>,
177    /// Whether an external job builds this target outside `verctl release
178    /// asset`. An external target stays in `declared` and release completeness
179    /// checks, while `status --github-output` omits it from the `assets` build
180    /// matrix.
181    #[serde(default)]
182    pub external: bool,
183    /// The paths this target's archive contains under `assets.dir`, in place of
184    /// `assets.files`, with the same placeholders. Use it when a platform
185    /// ships other files, such as a tool that builds only on Linux. Unset,
186    /// the target packs `assets.files`; an empty list would pack nothing.
187    #[serde(default)]
188    #[garde(
189        custom(target_files_come_with_dir),
190        inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
191    )]
192    pub files: Option<Vec<PathBuf>>,
193    /// A table copied unread into this target's `[[artifact]]` entry of the
194    /// packslip release.toml, such as `requires: { os_min: "11.0" }`. packslip
195    /// reads and validates every key in it, so a key packslip adds later needs
196    /// no verctl code. The entry's `path` is the asset's, which verctl
197    /// writes, so the table sets none. Omit to add nothing to the entry.
198    #[serde(default)]
199    #[garde(custom(a_packslip_table))]
200    pub packslip: ArtifactTable,
201}
202
203/// How the Release's packslip is made: the committed file that names what
204/// ships, and whether the tarballs are attested.
205///
206/// A mapping, so a repository changes one part without restating the other.
207/// The path form `packslip: <path>` is refused with the mapping to write.
208#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
209#[garde(context(Config))]
210#[garde(allow_unvalidated)]
211#[non_exhaustive]
212pub struct Packslip {
213    /// A packslip release.toml, relative to the directory containing `.ctl/`,
214    /// that names what does not change per release: the executables and the
215    /// resources that ship beside them. [`Config::load`] checks that git tracks
216    /// the file and that it parses as a TOML table. Omit to list `assets.bin`
217    /// and no resource.
218    #[garde(inner(custom(inside_the_repo)))]
219    pub manifest: Option<PathBuf>,
220    /// How the tarballs are attested. Omit for `true`.
221    pub attest: Attest,
222    /// The public key that verifies a key-signed bundle: the line of the
223    /// `release.pub` that `packslip keygen` wrote. packslip cannot derive it
224    /// from the secret key, and the bundle carries only a hash of it. The
225    /// release needs it when it signs with a key, and keyless signing ignores
226    /// it. Omit when the release signs keyless.
227    #[garde(inner(custom(a_public_key_line)))]
228    pub pubkey: Option<String>,
229}
230
231/// A `packslip.pubkey` that has text in it.
232fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
233    if line.trim().is_empty() {
234        return Err(garde::Error::new(
235            "cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
236        ));
237    }
238    Ok(())
239}
240
241/// The keys a `packslip` mapping reads, once its value is known to be one.
242#[derive(Deserialize)]
243#[serde(deny_unknown_fields)]
244struct PackslipKeys {
245    #[serde(default)]
246    manifest: Option<PathBuf>,
247    #[serde(default)]
248    attest: Attest,
249    #[serde(default)]
250    pubkey: Option<String>,
251}
252
253impl<'de> Deserialize<'de> for Packslip {
254    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
255        deserializer.deserialize_any(PackslipVisitor)
256    }
257}
258
259struct PackslipVisitor;
260
261impl<'de> Visitor<'de> for PackslipVisitor {
262    type Value = Packslip;
263
264    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
265        formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
266    }
267
268    fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
269        Err(E::custom(format!(
270            "packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
271        )))
272    }
273
274    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
275        let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
276        Ok(Packslip {
277            manifest: keys.manifest,
278            attest: keys.attest,
279            pubkey: keys.pubkey,
280        })
281    }
282}
283
284/// Where the tarballs' build provenance is attested, which the packslip
285/// links by digest.
286#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
287#[non_exhaustive]
288pub enum Attest {
289    /// The `publish` job attests the tarballs this run built.
290    #[default]
291    True,
292    /// Each asset job attests its own tarball as it builds it, so a
293    /// hand-written workflow whose jobs attest needs no step in `publish`.
294    Link,
295    /// Nothing is attested or linked.
296    False,
297}
298
299impl Attest {
300    /// The word a file, a flag, and a plan output write.
301    #[must_use]
302    pub const fn as_str(self) -> &'static str {
303        match self {
304            Self::True => "true",
305            Self::Link => "link",
306            Self::False => "false",
307        }
308    }
309}
310
311impl fmt::Display for Attest {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.write_str(self.as_str())
314    }
315}
316
317impl FromStr for Attest {
318    type Err = String;
319
320    fn from_str(word: &str) -> Result<Self, String> {
321        match word {
322            "true" => Ok(Self::True),
323            "link" => Ok(Self::Link),
324            "false" => Ok(Self::False),
325            other => Err(format!(
326                "packslip.attest must be true, link, or false, not {other:?}"
327            )),
328        }
329    }
330}
331
332impl Serialize for Attest {
333    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
334        serializer.serialize_str(self.as_str())
335    }
336}
337
338impl<'de> Deserialize<'de> for Attest {
339    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
340        deserializer.deserialize_any(AttestVisitor)
341    }
342}
343
344struct AttestVisitor;
345
346impl Visitor<'_> for AttestVisitor {
347    type Value = Attest;
348
349    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
350        formatter.write_str("packslip.attest: true, link, or false")
351    }
352
353    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
354        Ok(if v { Attest::True } else { Attest::False })
355    }
356
357    fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
358        v.parse().map_err(E::custom)
359    }
360}
361
362/// Release assets built from someone else's source, at that source's version,
363/// such as a library built from a pinned upstream release. Mise can then
364/// install it as a `github:` tool. The key is the set's `{name}`. Fragments
365/// never bump it, and `release` never reads it; `status --vendored <name>`
366/// plans it, and `release asset <target> --vendored <name>` builds and uploads
367/// it.
368#[derive(Debug, Clone, Deserialize, Validate)]
369#[serde(deny_unknown_fields)]
370#[garde(context(Config))]
371#[garde(allow_unvalidated)]
372#[non_exhaustive]
373pub struct Vendored {
374    /// The upstream version, written by hand: `{version}` in every template.
375    #[garde(
376        custom(cannot_be_empty("it names the release and the archives")),
377        custom(one_plain_name)
378    )]
379    pub version: String,
380    /// Release tag, with `{name}` and `{version}`. Omit for
381    /// `{name}-{version}`.
382    #[serde(default = "Vendored::default_tag")]
383    #[garde(
384        custom(cannot_be_empty("it names the release")),
385        custom(only_placeholders(&["{name}", "{version}"]))
386    )]
387    pub tag: String,
388    /// Archive file name, with `{name}`, `{version}`, and `{id}`. Omit for
389    /// `{name}-{version}-{id}.tar.gz`.
390    #[serde(default = "Vendored::default_archive")]
391    #[garde(
392        custom(one_archive_per_target),
393        custom(only_placeholders(&["{name}", "{version}", "{id}"]))
394    )]
395    pub archive: String,
396    /// Run once per target before packing. It uses no shell, and `{name}`,
397    /// `{version}`, and `{id}` are replaced. Omit when an earlier workflow step
398    /// builds.
399    #[serde(default)]
400    pub build: Vec<String>,
401    /// The directory the files are packed from, relative to the directory
402    /// containing `.ctl/`, with the same placeholders.
403    #[garde(custom(inside_the_repo))]
404    pub dir: PathBuf,
405    /// Paths under `dir` packed into the archive, each kept at its place under
406    /// `dir`. A directory is packed whole.
407    #[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
408    pub files: Vec<PathBuf>,
409    /// The Release body, a file relative to the directory containing `.ctl/`.
410    /// Omit for a Release with no body.
411    #[garde(inner(custom(inside_the_repo)))]
412    pub notes: Option<PathBuf>,
413    /// One entry per platform; the key is `{id}`, such as `linux-x64`.
414    #[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
415    pub targets: BTreeMap<String, VendoredTarget>,
416}
417
418impl Vendored {
419    fn default_tag() -> String {
420        "{name}-{version}".to_owned()
421    }
422
423    fn default_archive() -> String {
424        "{name}-{version}-{id}.tar.gz".to_owned()
425    }
426}
427
428/// One platform of a vendored set and the single machine that builds it.
429#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
430#[serde(deny_unknown_fields)]
431#[garde(context(Config))]
432#[non_exhaustive]
433pub struct VendoredTarget {
434    /// Name from `runners` of the machine that builds this target. verctl
435    /// has no built-in vendored platform, so there is no default machine.
436    #[garde(custom(runner_is_declared))]
437    pub runner: String,
438}
439
440/// The release.toml that `packslip.manifest` names, read from `path` and
441/// parsed, with `named` as the path its errors show.
442///
443/// A manifest sets no `artifact`, since the path of an entry changes every
444/// version. A target's `packslip` table replaces it.
445///
446/// # Errors
447///
448/// Returns an error when the file cannot be read, is not a TOML table, or sets
449/// `artifact`.
450pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
451    let text = fs::read_to_string(path)
452        .with_context(|| format!("packslip.manifest: read {}", named.display()))?;
453    let document = text
454        .parse::<toml_edit::DocumentMut>()
455        .with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
456    ensure!(
457        !document.contains_key("artifact"),
458        "packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
459        named.display()
460    );
461    Ok(document)
462}