verctl-core 0.9.7

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
463
//! Pure asset target naming, built-in target metadata, and generated-file path
//! validation rules shared by configuration validation and asset planning.

use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::config::{AssetTarget, Assets};

/// Output format of an asset target under `assets.<id>.format`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub enum AssetFormat {
    /// A gzip-compressed tar archive (`.tar.gz`).
    #[default]
    TarGz,
    /// A zip archive (`.zip`).
    Zip,
    /// One existing file staged as-is without archiving.
    Raw,
}

impl AssetFormat {
    /// The word a configuration file writes for this format.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::TarGz => "tar.gz",
            Self::Zip => "zip",
            Self::Raw => "raw",
        }
    }
}

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

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

impl TryFrom<String> for AssetFormat {
    type Error = String;

    fn try_from(word: String) -> Result<Self, Self::Error> {
        match word.as_str() {
            "tar.gz" => Ok(Self::TarGz),
            "zip" => Ok(Self::Zip),
            "raw" => Ok(Self::Raw),
            other => Err(format!(
                "assets format must be tar.gz, zip, or raw, not {other:?}"
            )),
        }
    }
}

/// The placeholders an `assets.<id>.file` path may use.
pub const RAW_FILE_PLACEHOLDERS: [&str; 6] =
    ["{bin}", "{version}", "{id}", "{os}", "{arch}", "{triple}"];

/// The first cross-field problem across `targets`, or `None` when every target
/// is sound.
#[must_use]
pub fn targets_problem(targets: &BTreeMap<String, AssetTarget>) -> Option<String> {
    for (id, spec) in targets {
        if spec.tarball.is_some() && spec.name.is_some() {
            return Some(format!(
                "assets.{id}.tarball cannot be set beside name; use name"
            ));
        }
        if spec.tarball.is_some() && spec.format != AssetFormat::TarGz {
            return Some(format!(
                "assets.{id}.tarball only applies to format: tar.gz; use name instead"
            ));
        }
        if spec.format == AssetFormat::Raw {
            if spec.files.is_some() {
                return Some(format!(
                    "assets.{id}.files cannot be set when format is raw; use file instead"
                ));
            }
            if !spec.external && spec.file.is_none() {
                return Some(format!(
                    "assets.{id}.file is required when format is raw and external is false"
                ));
            }
            if spec.external && spec.file.is_none() && spec.name.is_none() {
                return Some(format!(
                    "assets.{id}.name is required when format is raw, external is true, and file is omitted"
                ));
            }
        } else if spec.file.is_some() {
            return Some(format!("assets.{id}.file only applies when format is raw"));
        }
        if let Some(file) = &spec.file {
            let text = file.to_string_lossy();
            let rest = RAW_FILE_PLACEHOLDERS
                .iter()
                .fold(text.to_string(), |rest, placeholder| {
                    rest.replace(placeholder, "")
                });
            if rest.contains(['{', '}']) {
                return Some(format!(
                    "assets.{id}.file has a '{{' or '}}' that is not {}",
                    RAW_FILE_PLACEHOLDERS.join(", ")
                ));
            }
            if text.ends_with('/') || file.file_name().is_none() {
                return Some(format!(
                    "assets.{id}.file must name a file, not a directory"
                ));
            }
        }
    }
    None
}

/// The default tarball name template when a target sets none.
pub const DEFAULT_TARBALL: &str = "{bin}_{version}_{os}_{arch}.tar.gz";

/// The default zip archive name template when a `format: zip` target sets none.
pub const DEFAULT_ZIP: &str = "{bin}_{version}_{os}_{arch}.zip";

/// The placeholders an `assets.generated` path may use.
pub const GENERATED_PLACEHOLDERS: [&str; 5] = ["{bin}", "{id}", "{os}", "{arch}", "{triple}"];

/// A platform built into verctl. A repo that wants the usual values writes
/// only its name. Every field is a default the repo may override.
#[derive(Clone, Copy, Debug)]
pub struct DeclaredTargets {
    /// Target identifier, such as `darwin-arm64`.
    pub id: &'static str,
    /// Default runner labels.
    pub labels: &'static [&'static str],
    /// Operating system name.
    pub os: &'static str,
    /// CPU architecture name.
    pub arch: &'static str,
    /// Rust target triple.
    pub triple: &'static str,
}

/// Built-in target defaults.
pub const KNOWN: &[DeclaredTargets] = &[
    DeclaredTargets {
        id: "darwin-arm64",
        labels: &["xcode-27"],
        os: "darwin",
        arch: "arm64",
        triple: "aarch64-apple-darwin",
    },
    DeclaredTargets {
        id: "linux-x64",
        labels: &["ubuntu-26.04"],
        os: "linux",
        arch: "x64",
        triple: "x86_64-unknown-linux-gnu",
    },
];

/// Comma-separated list of built-in target ids.
#[must_use]
pub fn known_ids() -> String {
    KNOWN
        .iter()
        .map(|known| known.id)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The file name of the tarball for a target at `version`: `template`, or
/// `{bin}_{version}_{os}_{arch}.tar.gz` when the target sets none, with
/// `macos` for `darwin`.
#[must_use]
pub fn tarball_name(
    template: Option<&str>,
    bin: &str,
    version: &str,
    os: &str,
    arch: &str,
) -> String {
    let os = if os == "darwin" { "macos" } else { os };
    template
        .unwrap_or(DEFAULT_TARBALL)
        .replace("{bin}", bin)
        .replace("{version}", version)
        .replace("{os}", os)
        .replace("{arch}", arch)
}

/// The uploaded file name for target `id` at `version`, respecting `format`,
/// `name`, `tarball`, and `file`.
///
/// Returns `None` when a required placeholder (`{os}`, `{arch}`, or `{triple}`)
/// or `file` path is missing on the target.
#[must_use]
pub fn asset_name(
    id: &str,
    spec: &AssetTarget,
    bin: &str,
    version: &str,
    os: Option<&str>,
    arch: Option<&str>,
    triple: Option<&str>,
) -> Option<String> {
    let mapped_os = os.map(|value| if value == "darwin" { "macos" } else { value });
    if let Some(template) = spec.name.as_deref().or(spec.tarball.as_deref()) {
        if (template.contains("{os}") && mapped_os.is_none())
            || (template.contains("{arch}") && arch.is_none())
        {
            return None;
        }
        return Some(
            template
                .replace("{bin}", bin)
                .replace("{version}", version)
                .replace("{id}", id)
                .replace("{os}", mapped_os.unwrap_or(""))
                .replace("{arch}", arch.unwrap_or("")),
        );
    }
    match spec.format {
        AssetFormat::TarGz | AssetFormat::Zip => {
            let (Some(os), Some(arch)) = (mapped_os, arch) else {
                return None;
            };
            let default_template = if spec.format == AssetFormat::Zip {
                DEFAULT_ZIP
            } else {
                DEFAULT_TARBALL
            };
            Some(
                default_template
                    .replace("{bin}", bin)
                    .replace("{version}", version)
                    .replace("{os}", os)
                    .replace("{arch}", arch),
            )
        }
        AssetFormat::Raw => {
            let raw_file = spec.file.as_ref()?.to_str()?;
            if (raw_file.contains("{os}") && os.is_none())
                || (raw_file.contains("{arch}") && arch.is_none())
                || (raw_file.contains("{triple}") && triple.is_none())
            {
                return None;
            }
            let expanded = raw_file
                .replace("{bin}", bin)
                .replace("{version}", version)
                .replace("{id}", id)
                .replace("{os}", os.unwrap_or(""))
                .replace("{arch}", arch.unwrap_or(""))
                .replace("{triple}", triple.unwrap_or(""));
            Path::new(&expanded)
                .file_name()
                .and_then(|name| name.to_str())
                .map(str::to_owned)
        }
    }
}

/// The os and arch a target's tarball name renders: the target's own, else its
/// built-in record's.
#[must_use]
pub fn platform<'a>(id: &str, spec: &'a AssetTarget) -> Option<(&'a str, &'a str)> {
    let known = KNOWN.iter().find(|known| known.id == id);
    let os = spec.os.as_deref().or(known.map(|known| known.os))?;
    let arch = spec.arch.as_deref().or(known.map(|known| known.arch))?;
    Some((os, arch))
}

/// The target triple a target builds for: its own, else its built-in record's.
#[must_use]
pub fn triple<'a>(id: &str, spec: &'a AssetTarget) -> Option<&'a str> {
    let known = KNOWN.iter().find(|known| known.id == id);
    spec.triple.as_deref().or(known.map(|known| known.triple))
}

/// The ids of two targets that render one asset name, with that name, or
/// `None` when every target has its own.
#[must_use]
pub fn asset_name_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
    let mut named: BTreeMap<String, &str> = BTreeMap::new();
    for (id, spec) in &assets.targets {
        let known = KNOWN.iter().find(|known| known.id == id);
        let os = spec.os.as_deref().or(known.map(|known| known.os));
        let arch = spec.arch.as_deref().or(known.map(|known| known.arch));
        let triple = spec.triple.as_deref().or(known.map(|known| known.triple));
        let Some(name) = asset_name(id, spec, bin, "{version}", os, arch, triple) else {
            continue;
        };
        if let Some(first) = named.insert(name.clone(), id) {
            return Some((first.to_owned(), id.clone(), name));
        }
    }
    None
}

/// The ids of two targets that render one tarball name, with that name, or
/// `None` when every target has its own.
#[must_use]
pub fn tarball_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
    asset_name_clash(assets, bin)
}

/// The first reason an `assets.generated` path of `assets` is wrong, in the
/// words the load reports, or `None` when every path is sound.
#[must_use]
pub fn generated_problem(assets: &Assets, bin: &str) -> Option<String> {
    if !assets.generated.is_empty()
        && !assets.targets.is_empty()
        && assets
            .targets
            .values()
            .all(|target| target.format == AssetFormat::Raw)
    {
        return Some(
            "assets.generated cannot be set when every assets target uses format: raw".to_owned(),
        );
    }
    for (at, entry) in assets.generated.iter().enumerate() {
        let rest = GENERATED_PLACEHOLDERS
            .iter()
            .fold(entry.path.clone(), |rest, placeholder| {
                rest.replace(placeholder, "")
            });
        if rest.contains(['{', '}']) {
            return Some(format!(
                "assets.generated[{at}].path {:?} has a '{{' or '}}' that is not {}",
                entry.path,
                GENERATED_PLACEHOLDERS.join(", ")
            ));
        }
    }
    for (id, spec) in &assets.targets {
        if spec.format == AssetFormat::Raw {
            continue;
        }
        let (Some((os, arch)), Some(triple)) = (platform(id, spec), triple(id, spec)) else {
            continue;
        };
        let ctx = BTreeMap::from([
            ("bin", bin.to_owned()),
            ("id", id.clone()),
            ("os", os.to_owned()),
            ("arch", arch.to_owned()),
            ("triple", triple.to_owned()),
        ]);
        let packed: Vec<String> = if assets.dir.is_some() {
            spec.files
                .as_ref()
                .unwrap_or(&assets.files)
                .iter()
                .map(|file| expand_one(&file.display().to_string(), &ctx))
                .collect()
        } else {
            vec![bin.to_owned()]
        };
        let mut seen: Vec<(usize, Vec<String>)> = Vec::new();
        for (at, entry) in assets.generated.iter().enumerate() {
            let expanded = expand_one(&entry.path, &ctx);
            let named = format!("assets.generated[{at}].path {:?} (target {id})", entry.path);
            if let Some(reason) = unsafe_path(&expanded) {
                return Some(format!("{named} {reason}"));
            }
            let parts = plain_parts(&expanded);
            if parts.is_empty() {
                return Some(format!("{named} names the tarball's directory, not a file"));
            }
            if let Some((other, _)) = seen.iter().find(|(_, taken)| overlaps(taken, &parts)) {
                return Some(format!(
                    "{named} equals, contains, or sits under assets.generated[{other}].path: each names its own file"
                ));
            }
            if let Some(file) = packed.iter().find(|file| {
                let taken = plain_parts(file);
                !taken.is_empty() && overlaps(&taken, &parts)
            }) {
                return Some(format!(
                    "{named} would replace {file:?}, which the tarball already packs"
                ));
            }
            seen.push((at, parts));
        }
    }
    None
}

/// Expand `{key}` placeholders in `part` using `ctx`.
#[must_use]
pub fn expand_one(part: &str, ctx: &BTreeMap<&str, String>) -> String {
    let mut out = part.to_owned();
    for (key, value) in ctx {
        out = out.replace(&format!("{{{key}}}"), value);
    }
    out
}

/// Why `path` could leave the tarball or name a file two ways, or `None`.
#[must_use]
pub fn unsafe_path(path: &str) -> Option<String> {
    if path.is_empty() {
        return Some("is empty".to_owned());
    }
    if path.starts_with('/') {
        return Some("is absolute: write it relative to the tarball's directory".to_owned());
    }
    if path.ends_with('/') {
        return Some("ends in /: it names a directory, not a file".to_owned());
    }
    let mut parts = path.split('/');
    if parts.clone().any(|part| part == "..") {
        return Some("has a .. component, which leaves the tarball's directory".to_owned());
    }
    if let Some(part) = parts.clone().find(|part| part.starts_with('-')) {
        return Some(format!(
            "has the component {part:?}, which starts with '-': tar would read it as an option"
        ));
    }
    parts
        .find(|part| {
            !part
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
        })
        .map(|part| {
            format!(
                "has the component {part:?}: use only ASCII letters, digits, '.', '_', and '-', so no spelling names one file two ways"
            )
        })
}

/// The components of `path` that name something: no `.`, and no empty one from
/// a repeated separator.
#[must_use]
pub fn components(path: &str) -> Vec<&str> {
    path.split('/')
        .filter(|part| !part.is_empty() && *part != ".")
        .collect()
}

/// [`components`] with ASCII case folded.
#[must_use]
pub fn plain_parts(path: &str) -> Vec<String> {
    components(path)
        .into_iter()
        .map(str::to_ascii_lowercase)
        .collect()
}

/// Whether one of the two component lists equals or begins with the other.
#[must_use]
pub fn overlaps(left: &[String], right: &[String]) -> bool {
    left.starts_with(right) || right.starts_with(left)
}