verctl 0.3.10

Stack-agnostic version PRs from Changesets-format fragments
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
use crate::driver::{CommandSpec, Driver, Format};
use crate::publisher::PublisherSpec;
use anyhow::{Context, Result, bail, ensure};
use ctl_core::input::Input;
use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum CommandField {
    Mise(String),
    Argv(Vec<String>),
}

impl CommandField {
    fn into_spec(self) -> Result<CommandSpec> {
        match self {
            Self::Mise(task) => {
                if task.is_empty() {
                    bail!("mise task name is empty");
                }
                Ok(CommandSpec::Mise(task))
            }
            Self::Argv(argv) => {
                ensure!(!argv.is_empty(), "driver argv is empty");
                Ok(CommandSpec::Argv(argv))
            }
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct DriverSpec {
    pub format: Option<String>,
    pub keys: Option<Vec<String>>,
    pub read: Option<CommandField>,
    pub write: Option<CommandField>,
    pub after: Option<String>,
}

impl DriverSpec {
    pub fn into_driver(self, name: &str) -> Result<Driver> {
        if let (Some(read), Some(write)) = (self.read, self.write) {
            return Ok(Driver::Command {
                read: read.into_spec()?,
                write: write.into_spec()?,
                after: self.after,
            });
        }
        let format = match self.format.as_deref() {
            Some("toml") => Format::Toml,
            Some("json") => Format::Json,
            Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
            None => bail!("driver {name:?} needs format+keys or read+write"),
        };
        let keys = self
            .keys
            .filter(|keys| !keys.is_empty())
            .with_context(|| format!("driver {name:?} needs keys"))?;
        Ok(Driver::Path {
            format,
            keys,
            after: self.after,
        })
    }

    fn stock(name: &str) -> Option<Self> {
        match name {
            "cargo" => Some(Self {
                format: Some("toml".into()),
                keys: Some(vec![
                    "workspace.package.version".into(),
                    "package.version".into(),
                ]),
                ..Self::default()
            }),
            "npm" => Some(Self {
                format: Some("json".into()),
                keys: Some(vec!["version".into()]),
                ..Self::default()
            }),
            _ => None,
        }
    }

    fn merge(self, over: Self) -> Self {
        Self {
            format: over.format.or(self.format),
            keys: over.keys.or(self.keys),
            read: over.read.or(self.read),
            write: over.write.or(self.write),
            after: over.after.or(self.after),
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct PackageSpec {
    pub name: String,
    pub path: PathBuf,
    pub driver: Option<String>,
    /// Stock `cargo` / `bun`, a `publishers` key, or omit to infer.
    pub publisher: Option<String>,
    /// Pretty noun (`crate`, `package`, `wheel`). Defaults from the publisher.
    pub noun: Option<String>,
    /// Override the publisher argv for this package.
    #[serde(default, rename = "publish")]
    pub publish_argv: Option<Vec<String>>,
    pub registry: Option<String>,
    /// Package CHANGELOG.md. Defaults to next to the manifest.
    pub changelog: Option<PathBuf>,
    #[serde(flatten)]
    pub spec: DriverSpec,
}

impl PackageSpec {
    #[must_use]
    pub fn changelog_path(&self, root: &Path) -> PathBuf {
        if let Some(path) = &self.changelog {
            return root.join(path);
        }
        root.join(&self.path)
            .parent()
            .unwrap_or(root)
            .join("CHANGELOG.md")
    }

    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
        let inferred = self
            .path
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(stock_name_for_file);
        let driver_name = self.driver.as_deref().or(inferred);
        let mut spec = driver_name
            .and_then(|name| config.driver_spec(name))
            .unwrap_or_default();
        spec = spec.merge(self.spec.clone());
        if spec.after.is_none() {
            spec.after = crate::detect::follow_up(&root.join(&self.path));
        }
        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
    }
}

/// One machine, declared once under `runners`. The key names it; this
/// 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))]
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)]
pub struct Job {
    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.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Assets {
    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}` `{arch}`.
    pub binary: Option<String>,
    /// Every remaining sub-mapping: `assets.linux-x64` and friends. A typo'd
    /// recipe key lands here and fails as an unknown target, loudly.
    #[serde(flatten)]
    pub targets: BTreeMap<String, AssetTarget>,
}

/// One build target: the platform it produces and the single machine that
/// builds it. One tarball, one machine — so `runner` is not a list.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct AssetTarget {
    pub runner: Option<String>,
    pub os: Option<String>,
    pub arch: Option<String>,
    pub triple: Option<String>,
}

/// The whole file, and the context every rule in it is checked against: a
/// pattern is only unused, and an id only unknown, relative to the rest of the
/// config. `Config::parse` reads the shape with serde and then validates it
/// once, here, so a complaint names the field that has to change.
///
/// A section verctl does not know stops the load rather than being dropped:
/// silently ignoring `pattern:` for `patterns:` would ship a release with the
/// pins it declares never rewritten.
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Self as config))]
#[garde(allow_unvalidated)]
pub struct Config {
    #[serde(default)]
    pub drivers: BTreeMap<String, DriverSpec>,
    /// What this repo releases. A config that names none has nothing to do.
    #[garde(custom(at_least_one("package")))]
    pub packages: Vec<PackageSpec>,
    #[serde(default)]
    pub publishers: BTreeMap<String, PublisherSpec>,
    /// Machines, declared once and named. Entirely repo-owned: verctl ships no
    /// built-in names.
    #[serde(default)]
    #[garde(dive)]
    pub runners: BTreeMap<String, Runner>,
    #[serde(default)]
    pub assets: Option<Assets>,
    /// PR and push validation. Empty means one `verify` on `ubuntu-latest`.
    #[serde(default)]
    pub ci: BTreeMap<String, Job>,
    #[serde(default)]
    pub prepare: Prepare,
    /// Where served-file templates live. Omit for the convention.
    #[serde(default)]
    #[garde(dive)]
    pub templates: Templates,
    /// How release tags are named. Omit for `v{version}` — one tag when every
    /// released package shares a version. Put `{name}` in the template for one
    /// tag (and one Release) per package.
    #[serde(default)]
    #[garde(dive)]
    pub tags: Tags,
    /// Version spellings, named once and listed by the files that carry them,
    /// so a spelling three files share is written once.
    #[serde(default)]
    #[garde(custom(every_pattern_says_where_the_version_goes))]
    #[garde(custom(every_pattern_is_listed))]
    pub patterns: BTreeMap<String, PinPattern>,
    /// Collocated tool pins rewritten when `package` is bumped.
    #[serde(default)]
    #[garde(dive)]
    pub pins: Vec<Pin>,
}

/// Where the version goes, said once: no placeholder is a spelling that tracks
/// nothing, two is a spelling with no single version to put anywhere.
fn every_pattern_says_where_the_version_goes(
    patterns: &BTreeMap<String, PinPattern>,
    _: &Config,
) -> garde::Result {
    for (id, pattern) in patterns {
        let found = pattern.r#match.matches(PLACEHOLDER).count();
        if found != 1 {
            return Err(garde::Error::new(format!(
                "{id}: match says {PLACEHOLDER} {found} times, and must say it once"
            )));
        }
    }
    Ok(())
}

/// A declared pattern nothing lists is dead configuration, not a spare: it
/// would sit there reading like a tracked spelling while no file is checked
/// against it.
fn every_pattern_is_listed(
    patterns: &BTreeMap<String, PinPattern>,
    config: &Config,
) -> garde::Result {
    let listed: BTreeSet<&str> = config
        .pins
        .iter()
        .flat_map(|pin| pin.pattern_ids.iter().map(String::as_str))
        .collect();
    for id in patterns.keys() {
        if !listed.contains(id.as_str()) {
            return Err(garde::Error::new(format!(
                "{id:?} is declared and no pin lists it"
            )));
        }
    }
    Ok(())
}

/// A file that serves a package version and must track it.
#[derive(Debug, Clone, Deserialize, Validate)]
#[garde(context(Config as config))]
#[garde(allow_unvalidated)]
pub struct Pin {
    #[garde(custom(inside_the_repo))]
    pub file: PathBuf,
    /// A mise `[tools]` entry, in a file that parses as TOML. Its own
    /// `?ref=v…` includes move with it.
    pub tool: Option<String>,
    /// `patterns` ids this file carries, so which file a spelling belongs to
    /// is written down rather than implied by where a table sits.
    #[serde(default, rename = "patterns")]
    #[garde(
        custom(each_id_is_declared),
        custom(no_id_is_listed_twice),
        custom(something_to_rewrite(self.tool.is_some()))
    )]
    pub pattern_ids: Vec<String>,
    /// The patterns those ids name, filled in by `Config::load` — the only way
    /// to build a pin that rewrites anything.
    #[serde(skip)]
    pub patterns: Vec<PinPattern>,
    pub package: String,
}

/// A name is only a name if something declares it.
fn each_id_is_declared(ids: &[String], config: &Config) -> garde::Result {
    for id in ids {
        if !config.patterns.contains_key(id) {
            return Err(garde::Error::new(format!("no patterns.{id}")));
        }
    }
    Ok(())
}

/// Listing a spelling twice says nothing twice: arity belongs to the pattern.
fn no_id_is_listed_twice(ids: &[String], _: &Config) -> garde::Result {
    let mut seen = BTreeSet::new();
    for id in ids {
        if !seen.insert(id.as_str()) {
            return Err(garde::Error::new(format!("lists {id:?} twice")));
        }
    }
    Ok(())
}

/// A pin with neither a `tool` nor a pattern names a file and asks for nothing.
fn something_to_rewrite(has_tool: bool) -> impl Fn(&[String], &Config) -> garde::Result {
    move |ids, _| {
        if has_tool || !ids.is_empty() {
            return Ok(());
        }
        Err(garde::Error::new("needs a tool or a pattern to rewrite"))
    }
}

/// The directory every ctl CLI shares, so a repo root gains one entry however
/// many of them it uses. verctl owns the files it names here and nothing else.
pub const DIR: &str = ".ctl";

/// verctl's declarations, named after the task an operator runs (`mise run
/// ver`) rather than after the crate that reads them.
pub const FILE: &str = ".ctl/ver.yaml";

/// The directory a config governs — what every `path` in it is relative to.
///
/// Declarations sit in `<root>/.ctl/`, so the directory holding the file is a
/// level too deep and its parent is the root. `-c crates/foo/.ctl/ver.yaml`
/// therefore still governs `crates/foo`. A file outside a `.ctl` directory is
/// read where it sits, which is what an ad-hoc `-c` asks for.
#[must_use]
pub fn root_of(config: &Path) -> PathBuf {
    let dir = here(config.parent());
    if dir.file_name() == Some(OsStr::new(DIR)) {
        return here(dir.parent()).to_path_buf();
    }
    dir.to_path_buf()
}

fn here(path: Option<&Path>) -> &Path {
    path.filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// What a `pins` pattern puts where the version goes.
pub const PLACEHOLDER: &str = "{version}";

/// What a tag template puts where the package name goes.
pub const NAME_PLACEHOLDER: &str = "{name}";

/// How release tags are named. The arity falls out of the template: no
/// `{name}` means one tag for the release; `{name}` means one tag per package.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
pub struct Tags {
    /// Literal text with `{version}` and optionally `{name}`. Defaults to
    /// `v{version}`, so a repo that writes nothing keeps today's behaviour.
    #[serde(default = "Tags::default_template")]
    #[garde(
        custom(cannot_be_empty(
            "it is the shape of every release tag, like \"v{version}\" or \"{name}@{version}\""
        )),
        custom(tag_template_placeholders)
    )]
    pub template: String,
}

impl Tags {
    fn default_template() -> String {
        format!("v{PLACEHOLDER}")
    }

    #[must_use]
    pub fn uses_name(&self) -> bool {
        self.template.contains(NAME_PLACEHOLDER)
    }

    /// Substitute `{version}` and, when given, `{name}`. The load already
    /// proved those are the only braces, so a leftover `{` here is a bug.
    pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
        let mut out = self.template.replace(PLACEHOLDER, version);
        if let Some(name) = name {
            out = out.replace(NAME_PLACEHOLDER, name);
        } else if out.contains(NAME_PLACEHOLDER) {
            bail!(
                "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
                self.template
            );
        }
        ensure!(
            !out.contains('{') && !out.contains('}'),
            "tags.template {:?} still has braces after substitution",
            self.template
        );
        Ok(out)
    }
}

impl Default for Tags {
    fn default() -> Self {
        Self {
            template: Self::default_template(),
        }
    }
}

/// A tag template may only say `{version}` and `{name}`, must say at least one
/// of them, and must say `{version}` — a name with no version cannot date a
/// release.
fn tag_template_placeholders(template: &str, _: &Config) -> garde::Result {
    let mut saw_version = false;
    let mut saw_name = false;
    let mut rest = template;
    while let Some(start) = rest.find('{') {
        let after = &rest[start + 1..];
        let Some(end) = after.find('}') else {
            return Err(garde::Error::new("has an opening '{' with no closing '}'"));
        };
        let name = &after[..end];
        match name {
            "version" => saw_version = true,
            "name" => saw_name = true,
            _ => {
                return Err(garde::Error::new(format!(
                    "names {{{name}}}, and the only placeholders are {PLACEHOLDER} and {NAME_PLACEHOLDER}"
                )));
            }
        }
        rest = &after[end + 1..];
    }
    if !saw_version && !saw_name {
        return Err(garde::Error::new(format!(
            "has no placeholder — put {PLACEHOLDER} where the version goes"
        )));
    }
    if !saw_version {
        return Err(garde::Error::new(format!(
            "must say {PLACEHOLDER} — a tag with only {NAME_PLACEHOLDER} cannot date a release"
        )));
    }
    let leftover = template
        .replace(PLACEHOLDER, "")
        .replace(NAME_PLACEHOLDER, "");
    if leftover.contains('{') || leftover.contains('}') {
        return Err(garde::Error::new(format!(
            "has a '{{' or '}}' that is not {PLACEHOLDER} or {NAME_PLACEHOLDER}"
        )));
    }
    let _ = saw_name;
    Ok(())
}

/// Where the templates for served files live, and how they are marked. The
/// defaults are the whole convention: a repo that follows it writes nothing.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
pub struct Templates {
    /// The directory every template lives in, flat. Each one declares its own
    /// target, so nothing sits beside the file it generates.
    #[serde(default = "Templates::default_source")]
    #[garde(custom(inside_the_repo))]
    pub source: PathBuf,
    /// What marks a source file as a template of its target.
    #[serde(default = "Templates::default_suffix")]
    #[garde(custom(cannot_be_empty(
        "it is what marks a file in the source tree as a template, like \".jinja\""
    )))]
    pub suffix: String,
}

impl Templates {
    fn default_source() -> PathBuf {
        Path::new(DIR).join("templates")
    }

    fn default_suffix() -> String {
        ".jinja".to_owned()
    }
}

impl Default for Templates {
    fn default() -> Self {
        Self {
            source: Self::default_source(),
            suffix: Self::default_suffix(),
        }
    }
}

/// One version spelling in a file, and how often the file may say it.
#[derive(Debug, Clone, Deserialize)]
pub struct PinPattern {
    /// The text around a version, `{version}` where the version is. Literal,
    /// not a regex, so nothing about the file's format is assumed. Exactly one
    /// placeholder, checked over `patterns` so the complaint names the id.
    pub r#match: String,
    /// How often the file must say it. A pin that lost its only mention, or
    /// drifted to one nobody declared, fails the release rather than serving
    /// a stale version.
    #[serde(default)]
    pub occurrences: Occurrences,
    /// Whether the match is a whole line rather than text inside one.
    ///
    /// Unsaid, a pattern matches anywhere, which is what an inline spelling
    /// wants — `github:org/tool@1.2.3` sits inside a longer line. A pattern
    /// that owns its line says so instead of anchoring on whatever text
    /// happens to sit next to it: the alternative is spelling the neighbour
    /// into `match`, which then breaks when the neighbour moves. It also makes
    /// a partial version fail rather than rewrite, because a line ending in
    /// `0.1.1-rc1` does not end where the version does.
    #[serde(default)]
    pub whole_line: bool,
}

/// How many times a pattern must match. A count is not always the useful
/// shape: a document whose examples come and go needs "one or more", and a
/// spelling that was retired needs "none".
#[derive(Debug, Clone, Copy, Default)]
pub enum Occurrences {
    /// Exactly one. What a pin normally is, so it is the default.
    #[default]
    Once,
    /// One or more, however many. For a file whose mentions grow and shrink
    /// on their own, where only "still tracked" is worth asserting.
    Many,
    /// None. A spelling that must stay gone, so its return fails a release
    /// instead of being served.
    Never,
    /// Exactly this many, for a file that says it a known number of times.
    Exactly(usize),
    /// This many or more.
    AtLeast(usize),
}

/// The vocabulary, spelled out. A derived enum cannot read both shapes a repo
/// writes: an unbounded word is a plain scalar, and a bound is a mapping that a
/// newtype variant would only accept as a YAML tag (`!exactly 2`). Untagged
/// reads both and then reports "matched no variant", naming a type nobody
/// wrote, so the arity is read here and complains in the words a repo uses.
const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";

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

struct OccurrencesVisitor;

impl<'de> serde::de::Visitor<'de> for OccurrencesVisitor {
    type Value = Occurrences;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{ARITY}")
    }

    fn visit_str<E: serde::de::Error>(self, word: &str) -> Result<Occurrences, E> {
        match word {
            "once" => Ok(Occurrences::Once),
            "many" => Ok(Occurrences::Many),
            "never" => Ok(Occurrences::Never),
            _ => Err(E::custom(format!("must be {ARITY}"))),
        }
    }

    fn visit_map<A: serde::de::MapAccess<'de>>(
        self,
        mut bound: A,
    ) -> Result<Occurrences, A::Error> {
        use serde::de::Error;
        let wrong = || A::Error::custom(format!("must be {ARITY}"));
        let key: String = bound.next_key()?.ok_or_else(wrong)?;
        let count: usize = bound.next_value().map_err(|_| wrong())?;
        if bound.next_key::<serde::de::IgnoredAny>()?.is_some() {
            return Err(wrong());
        }
        match key.as_str() {
            "exactly" => Ok(Occurrences::Exactly(count)),
            "at_least" => Ok(Occurrences::AtLeast(count)),
            _ => Err(wrong()),
        }
    }
}

impl Occurrences {
    #[must_use]
    pub const fn allows(self, found: usize) -> bool {
        match self {
            Self::Once => found == 1,
            Self::Many => found >= 1,
            Self::Never => found == 0,
            Self::Exactly(count) => found == count,
            Self::AtLeast(count) => found >= count,
        }
    }
}

impl fmt::Display for Occurrences {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Once => formatter.write_str("exactly once"),
            Self::Many => formatter.write_str("one or more"),
            Self::Never => formatter.write_str("never"),
            Self::Exactly(count) => write!(formatter, "exactly {count} times"),
            Self::AtLeast(count) => write!(formatter, "{count} or more times"),
        }
    }
}

/// Extra work after version bumps, committed on the Version PR.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Prepare {
    /// argv after all bumps (e.g. `["mise", "run", "version-sync"]`).
    pub after: Option<Vec<String>>,
    /// Extra paths `after` may write. Anything else dirty fails.
    #[serde(default)]
    pub stage: Vec<String>,
    /// Collect gitignored paths that match `stage`. Off by default.
    #[serde(default)]
    pub stage_ignored: bool,
    /// Label `prepare --pr` applies. `check --versions` trusts this
    /// on the GitHub event, not `GITHUB_HEAD_REF`.
    pub version_label: Option<String>,
}

impl Prepare {
    pub const DEFAULT_VERSION_LABEL: &'static str = "verctl:version";

    #[must_use]
    pub fn version_label(&self) -> &str {
        self.version_label
            .as_deref()
            .filter(|label| !label.is_empty())
            .unwrap_or(Self::DEFAULT_VERSION_LABEL)
    }
}

impl Config {
    pub fn load(path: &Path) -> Result<Self> {
        Self::from_input(&Input::read(path)?)
    }

    /// A config from text in memory, named as the file a repo writes.
    pub fn parse(raw: &str) -> Result<Self> {
        Self::from_input(&Input::new(".ctl/ver.yaml", raw))
    }

    /// The one parse boundary: ctl-core's declared input reads the shape and
    /// validates it once against the whole document, placing each complaint
    /// on its line, so a document is read exactly one way.
    fn from_input(input: &Input) -> Result<Self> {
        let mut config: Self = input.parse()?;
        input.check(&config, &config)?;
        config.resolve_patterns();
        Ok(config)
    }

    /// Turn every pin's `patterns` ids into the patterns they name, so no
    /// consumer looks an id up again. Validation already proved every name
    /// resolves, which is why this cannot fail.
    fn resolve_patterns(&mut self) {
        let declared = self.patterns.clone();
        for pin in &mut self.pins {
            pin.patterns = pin
                .pattern_ids
                .iter()
                .filter_map(|id| declared.get(id).cloned())
                .collect();
        }
    }

    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
        self.packages
            .iter()
            .find(|package| package.name == name)
            .with_context(|| format!("package {name:?} is not in verctl config"))
    }

    #[must_use]
    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
        match (DriverSpec::stock(name), self.drivers.get(name)) {
            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
            (Some(stock), None) => Some(stock),
            (None, Some(over)) => Some(over.clone()),
            (None, None) => None,
        }
    }
}

fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
    match file_name {
        "Cargo.toml" => Some("cargo"),
        "package.json" => Some("npm"),
        _ => None,
    }
}

pub(crate) fn stock_driver(name: &str) -> Result<Driver> {
    DriverSpec::stock(name)
        .with_context(|| format!("unknown stock driver {name:?}"))?
        .into_driver(name)
}

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::{formatdoc, indoc};

    /// A whole config, so what is under test is what a repo actually writes.
    fn load(body: &str) -> Result<Config> {
        Config::parse(body)
    }

    /// The one package every fixture below needs, and nothing else.
    const PACKAGE: &str = indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
    "};

    /// A `path` is relative to the repository, not to the directory the
    /// declarations happen to sit in, so `.ctl` never lands in front of it.
    #[test]
    fn the_root_is_the_directory_holding_the_ctl_dir() {
        let cases = [
            (".ctl/ver.yaml", "."),
            ("crates/foo/.ctl/ver.yaml", "crates/foo"),
            ("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
            ("ver.yaml", "."),
            ("/tmp/scratch/ver.yaml", "/tmp/scratch"),
        ];
        for (config, expected) in cases {
            assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
        }
    }

    /// Every arity a repo can write, in the spelling it writes it.
    #[test]
    fn every_occurrence_form_parses_and_means_what_it_says() {
        let config = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              omitted:
                match: "a@{{version}}"
              once:
                match: "b@{{version}}"
                occurrences: once
              many:
                match: "c@{{version}}"
                occurrences: many
              never:
                match: "d@{{version}}"
                occurrences: never
              twice:
                match: "e@{{version}}"
                occurrences: {{exactly: 2}}
              floor:
                match: "f@{{version}}"
                occurrences: {{at_least: 2}}

            pins:
              - file: README.md
                package: demo
                patterns: [omitted, once, many, never, twice, floor]
        "#})
        .unwrap();
        let allowed: Vec<Vec<usize>> = config.pins[0]
            .patterns
            .iter()
            .map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
            .collect();
        assert_eq!(
            allowed,
            [
                vec![1],       // omitted: exactly once
                vec![1],       // once
                vec![1, 2, 3], // many
                vec![0],       // never
                vec![2],       // exactly 2
                vec![2, 3],    // at least 2
            ]
        );
    }

    /// A section verctl does not know is a typo, and a typo that loads is a
    /// release that quietly does none of what the section asked for.
    #[test]
    fn a_misspelled_section_stops_the_load() {
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            pattern:
              install:
                match: "demo@{{version}}"
        "#})
        .expect_err("pattern is not a section");
        assert!(format!("{error:#}").contains("pattern"), "{error:#}");
    }

    /// A bound is one key and its number. A second key means the arity was
    /// mistyped, and falling through to whichever variant the first key
    /// satisfies would pin a count nobody wrote.
    #[test]
    fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              wrong:
                match: "a@{{version}}"
                occurrences: {{exactly: 2, at_leats: 3}}

            pins:
              - file: README.md
                package: demo
                patterns: [wrong]
        "#})
        .expect_err("at_leats is not a key");
        assert!(format!("{error:#}").contains(ARITY), "{error:#}");
    }

    /// A count that is not a whole number is the same mistake as a wrong
    /// key, and says so in the same words rather than serde's.
    #[test]
    fn a_bound_with_a_bad_count_names_the_arity() {
        for count in ["-1", "many"] {
            let error = load(&formatdoc! {r#"
                {PACKAGE}
                patterns:
                  wrong:
                    match: "a@{{version}}"
                    occurrences: {{exactly: {count}}}

                pins:
                  - file: README.md
                    package: demo
                    patterns: [wrong]
            "#})
            .expect_err("the count is not a whole number");
            assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
        }
    }

    #[test]
    fn an_unknown_arity_is_not_silently_a_default() {
        let broken = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              wrong:
                match: "a@{{version}}"
                occurrences: sometimes

            pins:
              - file: README.md
                package: demo
                patterns: [wrong]
        "#});
        assert!(broken.is_err());
    }

    /// One spelling, named once, carried by two files: what ids are for.
    #[test]
    fn one_named_pattern_serves_every_file_that_lists_it() {
        let config = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              install:
                match: "demo@{{version}}"
              mention:
                match: "v{{version}}"
                occurrences: many

            pins:
              - file: README.md
                package: demo
                patterns: [install, mention]
              - file: docs/install.md
                package: demo
                patterns: [install]
        "#})
        .unwrap();
        let carried: Vec<Vec<&str>> = config
            .pins
            .iter()
            .map(|pin| {
                pin.patterns
                    .iter()
                    .map(|pattern| pattern.r#match.as_str())
                    .collect()
            })
            .collect();
        assert_eq!(
            carried,
            [vec!["demo@{version}", "v{version}"], vec!["demo@{version}"]],
            "each file carries the patterns it lists, in the order it lists them"
        );
    }

    /// Every rule the schema declares, each naming what a repo has to fix.
    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "one case per rule; a table, not logic"
    )]
    fn a_config_that_breaks_a_rule_stops_the_load() {
        let cases = [
            (
                "an id no patterns section declares",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}}"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install, instal]
                "#},
                "pins[0].pattern_ids: no patterns.instal",
            ),
            (
                "the same id listed twice",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}}"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install, install]
                "#},
                r#"pins[0].pattern_ids: lists "install" twice"#,
            ),
            (
                "a pattern no pin lists",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}}"
                      orphan:
                        match: "old@{{version}}"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install]
                "#},
                r#"patterns: "orphan" is declared and no pin lists it"#,
            ),
            (
                "a pin with nothing to rewrite",
                formatdoc! {"
                    {PACKAGE}
                    pins:
                      - file: README.md
                        package: demo
                "},
                "pins[0].pattern_ids: needs a tool or a pattern to rewrite",
            ),
            (
                "a spelling with nowhere to put the version",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@1.2.3"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install]
                "#},
                "patterns: install: match says {version} 0 times",
            ),
            (
                "a pin reaching out of the repository",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}}"

                    pins:
                      - file: ../elsewhere/README.md
                        package: demo
                        patterns: [install]
                "#},
                "pins[0].file: must stay inside the repository",
            ),
            (
                "a machine no label can find",
                formatdoc! {"
                    {PACKAGE}
                    runners:
                      ghost:
                        labels: []
                "},
                "runners.ghost.labels: must declare at least one label",
            ),
            (
                "a suffix that makes every file a template",
                formatdoc! {r#"
                    {PACKAGE}
                    templates:
                      suffix: ""
                "#},
                "templates.suffix: cannot be empty — it is what marks a file",
            ),
            (
                "a tag template naming a placeholder that does not exist",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "v{{ver}}"
                "#},
                "tags.template: names {ver}, and the only placeholders are {version} and {name}",
            ),
            (
                "a tag template with no placeholder",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "latest"
                "#},
                "tags.template: has no placeholder",
            ),
            (
                "a tag template with only the package name",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "{{name}}"
                "#},
                "tags.template: must say {version}",
            ),
            (
                "an empty tag template",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: ""
                "#},
                "tags.template: cannot be empty",
            ),
            (
                "a tag template with a leftover brace",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "v{{version}}}}"
                "#},
                "tags.template: has a '{' or '}' that is not {version} or {name}",
            ),
        ];
        for (scenario, body, expected) in cases {
            let error = load(&body).expect_err(scenario);
            assert!(
                format!("{error:#}").contains(expected),
                "{scenario}: {error:#}"
            );
        }
    }
}