verctl-core 0.9.6

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, fs};

use anyhow::{Context, Result, ensure};
use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Serialize, de};

use super::validate_assets::{
    a_packslip_table, a_tarball_name, an_asset_name, asset_targets_are_sound, at_least_one_target,
    binary_is_not_beside_files, dir_comes_with_files, every_key_is_one_plain_name,
    files_come_with_dir, generated_paths_are_sound, one_archive_per_target, one_plain_name,
    only_placeholders, runner_is_declared, target_files_come_with_dir,
};
use super::{ArtifactTable, Config};
pub use crate::asset_rules::AssetFormat;

/// is how GitHub finds it. Every label is required at once, so a three-label
/// runner is one machine carrying three labels, not three machines.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Runner {
    /// Every label at once. A machine with none cannot be found at all.
    #[garde(custom(at_least_one("label")))]
    pub labels: Vec<String>,
}

/// One job, declared under `ci`. The key names it; `runners` names the
/// machines from `runners` it runs on, one check each. No `os`/`arch`/
/// `triple`: validation runs a machine's checks, it does not cross-compile.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Job {
    /// Names from `runners` this job runs on. Omit for one `ubuntu-26.04`
    /// machine.
    pub runners: Option<Vec<String>>,
}

/// Native GitHub Release tarballs, plus the recipe every target shares. Omit
/// for libraries. Each named sub-mapping is one target.
///
/// A tarball contains the one `binary`, or the `files` packed from `dir`. Use
/// `files` when a release needs more than its binary, such as a second
/// executable, a service unit, or a licence. A target that ships other files
/// lists its own `files`, which replace the shared list for that target.
#[derive(Debug, Clone, Default, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Assets {
    /// The binary name. Defaults to the first package's name.
    pub bin: Option<String>,
    /// Ran once per target before `build`. Stock rust recipe uses rustup.
    pub prepare: Option<Vec<String>>,
    /// How to produce the binary. Stock rust recipe is `cargo build --release`.
    pub build: Option<Vec<String>>,
    /// Path to the built binary, with `{bin}`, `{triple}`, `{os}`, and
    /// `{arch}`. Omit for `target/{triple}/release/{bin}`. Unused when `dir`
    /// and `files` specify what to pack, so it may not be set beside them.
    #[garde(custom(binary_is_not_beside_files))]
    pub binary: Option<String>,
    /// The directory `files` are packed from, relative to the directory
    /// containing `.ctl/`, with the same placeholders as `binary`. Omit, with
    /// `files`, to pack the one `binary`.
    #[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
    pub dir: Option<PathBuf>,
    /// Paths under `dir` packed into the tarball of every target that lists
    /// none of its own, with the same placeholders. Each keeps its place under
    /// `dir`. A directory is packed whole. Omit, with `dir`, to pack the one
    /// `binary`, or when every target lists its own.
    #[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
    pub files: Vec<PathBuf>,
    /// Files written from a command's output and packed into the tarball of
    /// every target beside the binary, such as a usage spec or a man page the
    /// built binary prints. Omit when the tarball contains nothing generated.
    #[garde(dive, custom(generated_paths_are_sound))]
    pub generated: Vec<Generated>,
    /// Every remaining sub-mapping: `assets.linux-x64` and friends. A typo'd
    /// recipe key lands here and fails as an unknown target, loudly.
    /// [`Config::load`] declares this field to ctl-core as flattened,
    /// so a problem names `assets.<id>` and lands on that key's line.
    #[garde(dive, custom(asset_targets_are_sound))]
    pub targets: BTreeMap<String, AssetTarget>,
}

impl Assets {
    /// The keys under `assets` that are settings, every other key being a
    /// target id. A reader that takes only the target ids of an old config
    /// leaves these out.
    pub const SETTINGS: [&'static str; 7] = [
        "bin",
        "prepare",
        "build",
        "binary",
        "dir",
        "files",
        "generated",
    ];
}

/// One file `release asset` writes from a command's output and packs into a
/// tarball. A host that installs the tarball then gets a file it cannot
/// generate at install time, such as a man page, which mise installs only from
/// a file.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Generated {
    /// Where the file lands under the directory the tarball is cut from, with
    /// `{bin}`, `{id}`, `{os}`, `{arch}`, and `{triple}`. The load checks it
    /// for each target: it stays inside the tarball, names one file, and
    /// replaces nothing the tarball packs.
    pub path: String,
    /// The command whose standard output is the file's content, run without a
    /// shell. `{binary}` is the binary the target built, or the one
    /// `--prebuilt-self` staged, and the placeholders of `path` and
    /// `{version}` are replaced too.
    #[garde(custom(at_least_one("argument")))]
    pub run: Vec<String>,
}

/// One build target: the platform it produces and the single machine that
/// builds it. One asset, one machine, so `runner` is not a list.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct AssetTarget {
    /// Name from `runners` of the machine that builds this target.
    pub runner: Option<String>,
    /// Operating system name. Defaults from a known target id.
    pub os: Option<String>,
    /// CPU architecture name. Defaults from a known target id.
    pub arch: Option<String>,
    /// Target triple. Defaults from a known target id.
    pub triple: Option<String>,
    /// Output format of this target's asset: `tar.gz` (default), `zip`, or
    /// `raw`.
    #[serde(default)]
    pub format: AssetFormat,
    /// Ran before `build` for this target alone, in place of the shared
    /// `assets.prepare`, with the same placeholders. Use it when one platform
    /// needs a toolchain the others do not, such as a musl C compiler.
    pub prepare: Option<Vec<String>>,
    /// How to produce this target's binary or asset, in place of the shared
    /// `assets.build`, with the same placeholders.
    pub build: Option<Vec<String>>,
    /// The uploaded asset's file name, with `{bin}`, `{version}`, `{os}`,
    /// `{arch}`, and `{id}`, where `{os}` renders `macos` for `darwin`.
    /// Applies to every format and cannot be set beside `tarball`.
    #[garde(inner(custom(an_asset_name)))]
    pub name: Option<String>,
    /// The tarball's file name, with `{bin}`, `{version}`, `{os}`, and
    /// `{arch}`, where `{os}` renders `macos` for `darwin`. Omit for
    /// `{bin}_{version}_{os}_{arch}.tar.gz`. Set it when two targets share an
    /// os and an arch, such as a glibc and a musl build, which would otherwise
    /// render one name.
    #[garde(inner(custom(a_tarball_name)))]
    pub tarball: Option<String>,
    /// Path to the existing file staged as-is when `format` is `raw`, relative
    /// to the repository root, with `{bin}`, `{version}`, `{id}`, `{os}`,
    /// `{arch}`, and `{triple}`. Required when `format` is `raw` and `external`
    /// is `false`.
    #[serde(default)]
    #[garde(inner(custom(inside_the_repo)))]
    pub file: Option<PathBuf>,
    /// Whether an external job builds this target outside `verctl release
    /// asset`. An external target stays in `declared` and release completeness
    /// checks, while `status --github-output` omits it from the `assets` build
    /// matrix.
    #[serde(default)]
    pub external: bool,
    /// The paths this target's archive contains under `assets.dir`, in place of
    /// `assets.files`, with the same placeholders. Use it when a platform
    /// ships other files, such as a tool that builds only on Linux. Unset,
    /// the target packs `assets.files`; an empty list would pack nothing.
    #[serde(default)]
    #[garde(
        custom(target_files_come_with_dir),
        inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
    )]
    pub files: Option<Vec<PathBuf>>,
    /// A table copied unread into this target's `[[artifact]]` entry of the
    /// packslip release.toml, such as `requires: { os_min: "11.0" }`. packslip
    /// reads and validates every key in it, so a key packslip adds later needs
    /// no verctl code. The entry's `path` is the asset's, which verctl
    /// writes, so the table sets none. Omit to add nothing to the entry.
    #[serde(default)]
    #[garde(custom(a_packslip_table))]
    pub packslip: ArtifactTable,
}

/// How the Release's packslip is made: the committed file that names what
/// ships, and whether the tarballs are attested.
///
/// A mapping, so a repository changes one part without restating the other.
/// The path form `packslip: <path>` is refused with the mapping to write.
#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Packslip {
    /// A packslip release.toml, relative to the directory containing `.ctl/`,
    /// that names what does not change per release: the executables and the
    /// resources that ship beside them. [`Config::load`] checks that git tracks
    /// the file and that it parses as a TOML table. Omit to list `assets.bin`
    /// and no resource.
    #[garde(inner(custom(inside_the_repo)))]
    pub manifest: Option<PathBuf>,
    /// How the tarballs are attested. Omit for `true`.
    pub attest: Attest,
    /// The public key that verifies a key-signed bundle: the line of the
    /// `release.pub` that `packslip keygen` wrote. packslip cannot derive it
    /// from the secret key, and the bundle carries only a hash of it. The
    /// release needs it when it signs with a key, and keyless signing ignores
    /// it. Omit when the release signs keyless.
    #[garde(inner(custom(a_public_key_line)))]
    pub pubkey: Option<String>,
}

/// A `packslip.pubkey` that has text in it.
fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
    if line.trim().is_empty() {
        return Err(garde::Error::new(
            "cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
        ));
    }
    Ok(())
}

/// The keys a `packslip` mapping reads, once its value is known to be one.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PackslipKeys {
    #[serde(default)]
    manifest: Option<PathBuf>,
    #[serde(default)]
    attest: Attest,
    #[serde(default)]
    pubkey: Option<String>,
}

impl<'de> Deserialize<'de> for Packslip {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(PackslipVisitor)
    }
}

struct PackslipVisitor;

impl<'de> Visitor<'de> for PackslipVisitor {
    type Value = Packslip;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
        Err(E::custom(format!(
            "packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
        )))
    }

    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
        let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
        Ok(Packslip {
            manifest: keys.manifest,
            attest: keys.attest,
            pubkey: keys.pubkey,
        })
    }
}

/// Where the tarballs' build provenance is attested, which the packslip
/// links by digest.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attest {
    /// The `publish` job attests the tarballs this run built.
    #[default]
    True,
    /// Each asset job attests its own tarball as it builds it, so a
    /// hand-written workflow whose jobs attest needs no step in `publish`.
    Link,
    /// Nothing is attested or linked.
    False,
}

impl Attest {
    /// The word a file, a flag, and a plan output write.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::True => "true",
            Self::Link => "link",
            Self::False => "false",
        }
    }
}

impl fmt::Display for Attest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Attest {
    type Err = String;

    fn from_str(word: &str) -> Result<Self, String> {
        match word {
            "true" => Ok(Self::True),
            "link" => Ok(Self::Link),
            "false" => Ok(Self::False),
            other => Err(format!(
                "packslip.attest must be true, link, or false, not {other:?}"
            )),
        }
    }
}

impl Serialize for Attest {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Attest {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(AttestVisitor)
    }
}

struct AttestVisitor;

impl Visitor<'_> for AttestVisitor {
    type Value = Attest;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("packslip.attest: true, link, or false")
    }

    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
        Ok(if v { Attest::True } else { Attest::False })
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
        v.parse().map_err(E::custom)
    }
}

/// Release assets built from someone else's source, at that source's version,
/// such as a library built from a pinned upstream release. Mise can then
/// install it as a `github:` tool. The key is the set's `{name}`. Fragments
/// never bump it, and `release` never reads it; `status --vendored <name>`
/// plans it, and `release asset <target> --vendored <name>` builds and uploads
/// it.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Vendored {
    /// The upstream version, written by hand: `{version}` in every template.
    #[garde(
        custom(cannot_be_empty("it names the release and the archives")),
        custom(one_plain_name)
    )]
    pub version: String,
    /// Release tag, with `{name}` and `{version}`. Omit for
    /// `{name}-{version}`.
    #[serde(default = "Vendored::default_tag")]
    #[garde(
        custom(cannot_be_empty("it names the release")),
        custom(only_placeholders(&["{name}", "{version}"]))
    )]
    pub tag: String,
    /// Archive file name, with `{name}`, `{version}`, and `{id}`. Omit for
    /// `{name}-{version}-{id}.tar.gz`.
    #[serde(default = "Vendored::default_archive")]
    #[garde(
        custom(one_archive_per_target),
        custom(only_placeholders(&["{name}", "{version}", "{id}"]))
    )]
    pub archive: String,
    /// Run once per target before packing. It uses no shell, and `{name}`,
    /// `{version}`, and `{id}` are replaced. Omit when an earlier workflow step
    /// builds.
    #[serde(default)]
    pub build: Vec<String>,
    /// The directory the files are packed from, relative to the directory
    /// containing `.ctl/`, with the same placeholders.
    #[garde(custom(inside_the_repo))]
    pub dir: PathBuf,
    /// Paths under `dir` packed into the archive, each kept at its place under
    /// `dir`. A directory is packed whole.
    #[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
    pub files: Vec<PathBuf>,
    /// The Release body, a file relative to the directory containing `.ctl/`.
    /// Omit for a Release with no body.
    #[garde(inner(custom(inside_the_repo)))]
    pub notes: Option<PathBuf>,
    /// One entry per platform; the key is `{id}`, such as `linux-x64`.
    #[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
    pub targets: BTreeMap<String, VendoredTarget>,
}

impl Vendored {
    fn default_tag() -> String {
        "{name}-{version}".to_owned()
    }

    fn default_archive() -> String {
        "{name}-{version}-{id}.tar.gz".to_owned()
    }
}

/// One platform of a vendored set and the single machine that builds it.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct VendoredTarget {
    /// Name from `runners` of the machine that builds this target. verctl
    /// has no built-in vendored platform, so there is no default machine.
    #[garde(custom(runner_is_declared))]
    pub runner: String,
}

/// The release.toml that `packslip.manifest` names, read from `path` and
/// parsed, with `named` as the path its errors show.
///
/// A manifest sets no `artifact`, since the path of an entry changes every
/// version. A target's `packslip` table replaces it.
///
/// # Errors
///
/// Returns an error when the file cannot be read, is not a TOML table, or sets
/// `artifact`.
pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
    let text = fs::read_to_string(path)
        .with_context(|| format!("packslip.manifest: read {}", named.display()))?;
    let document = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
    ensure!(
        !document.contains_key("artifact"),
        "packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
        named.display()
    );
    Ok(document)
}