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
//! Render the files a repo serves, from templates that say what they are for.
//!
//! Every template lives flat in `.ctl/templates/` and **declares where it
//! goes**, in Jinja's own syntax rather than a manifest beside it or a mirrored
//! directory tree:
//!
//! ```jinja
//! {%- set path = "tasks/q" -%}
//! {%- set executable = true -%}
//! #!/usr/bin/env bash
//! #MISE tools = { "github:victor-software-house/qctl" = "{{ versions["qctl"] }}" }
//! ```
//!
//! Jinja has no frontmatter, but a top-level `{% set %}` is its equivalent: an
//! export, readable from the evaluated state, so the metadata travels inside
//! the file it describes. `q.jinja` above serves `tasks/q/q` — the file name
//! defaults to the template's own, so most templates declare one line, and
//! nothing accumulates in configuration.
//!
//! `Declared` is the whole schema, parsed once and resolved into a checked
//! `Served`. Trim declarations with `{%- … -%}`: a shebang has to stay on line
//! one.

use crate::cli::Cli;
use crate::config::Templates;
use crate::git;
use anyhow::{Context, Result, bail};
use ctl_core::validate::{inside_the_repo, one_file_name};
use ctl_core::{Surface, surface::add_fragments};
use garde::Validate;
use minijinja::value::Value;
use minijinja::{Environment, State, UndefinedBehavior, context};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Component, Path, PathBuf};

/// What a template declares about the file it serves, in Jinja's own syntax:
/// top-level `{%- set … -%}` exports, read as one schema and checked at the
/// boundary. Other exports are the template's own business — a name it uses to
/// build a line is not a declaration.
#[derive(Debug, Deserialize, Validate)]
#[garde(allow_unvalidated)]
struct Declared {
    /// The directory the target goes in. Unsaid: the repository root.
    #[serde(default)]
    #[garde(custom(inside_the_repo))]
    path: PathBuf,
    /// The target file's name. Unsaid, it is this template's own name without
    /// the suffix, which is what a served file almost always wants — so the
    /// fallback is seeded before parsing and this is never absent.
    #[garde(custom(one_file_name))]
    name: String,
    /// Whether the target is executable. Git records one bit of mode for a
    /// regular file and nothing else — "only 0755 and 0644 are valid for
    /// regular files" (gitformat-index) — and its other modes are not files a
    /// template renders: 120000 is a symlink, 160000 a gitlink, 040000 a tree.
    /// So there is no third state, and no mode field: unsaid means 0644.
    #[serde(default)]
    executable: bool,
}

pub fn write(
    root: &Path,
    config: &Templates,
    versions: &[(String, String)],
) -> Result<Vec<PathBuf>> {
    render(root, config, versions, true)
}

/// Whether this repo serves anything from a template at all.
///
/// A repo that serves nothing must not pay for what rendering needs — reading
/// every package's manifest to build the version map — so the caller asks first.
pub fn any(root: &Path, config: &Templates) -> Result<bool> {
    Ok(!sources(root, config)?.is_empty())
}

/// Same checks as `write`, without touching disk.
pub fn plan(
    root: &Path,
    config: &Templates,
    versions: &[(String, String)],
) -> Result<Vec<PathBuf>> {
    render(root, config, versions, false)
}

fn render(
    root: &Path,
    config: &Templates,
    versions: &[(String, String)],
    persist: bool,
) -> Result<Vec<PathBuf>> {
    let verctl_surface = Surface::new::<Cli>("ver");
    let context = context! {
        versions => versions
            .iter()
            .map(|(name, version)| (name.clone(), version.clone()))
            .collect::<BTreeMap<_, _>>(),
        verctl_surface,
    };
    let mut environment = Environment::new();
    environment.set_undefined_behavior(UndefinedBehavior::Strict);
    environment.set_keep_trailing_newline(true);
    add_fragments(&mut environment).context("register ctl-core operator fragments")?;

    let mut rendered = Vec::new();
    for template in sources(root, config)? {
        let source = fs::read_to_string(root.join(&template))
            .with_context(|| format!("read template {}", template.display()))?;
        let name = template.display().to_string();
        let compiled = environment
            .template_from_named_str(&name, &source)
            .with_context(|| format!("parse template {name}"))?;
        let captured = compiled
            .render_captured(&context)
            .with_context(|| format!("render template {}", template.display()))?;
        let body = captured.output();
        let declared = Declared::parse(&template, config, captured.state())?;
        let target = declared.target();
        ensure_inside(root, &target).with_context(|| format!("template {}", template.display()))?;
        let path = root.join(&target);
        if persist {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("create {}", parent.display()))?;
            }
            fs::write(&path, body).with_context(|| format!("write {}", target.display()))?;
            let mode = if declared.executable { 0o755 } else { 0o644 };
            fs::set_permissions(&path, fs::Permissions::from_mode(mode))
                .with_context(|| format!("chmod {}", target.display()))?;
        }
        rendered.push(path);
    }
    Ok(rendered)
}

impl Declared {
    /// Read the whole schema out of an evaluated template at once, over a
    /// seeded `name`. Types and shapes are the schema's business: `path = 5`
    /// and `name = "a/b"` fail here, not at write time.
    fn parse(template: &Path, config: &Templates, state: &State<'_, '_>) -> Result<Self> {
        let mut exports: BTreeMap<&str, Value> = state
            .exports()
            .into_iter()
            .filter_map(|name| state.lookup(name).map(|value| (name, value)))
            .filter(|(_, value)| !value.is_undefined() && !value.is_none())
            .collect();
        let own_name = template
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(|name| name.strip_suffix(&config.suffix))
            .with_context(|| {
                format!(
                    "{}: template name does not end in {}",
                    template.display(),
                    config.suffix
                )
            })?;
        exports
            .entry("name")
            .or_insert_with(|| Value::from(own_name));
        let declared = Self::deserialize(Value::from_serialize(&exports))
            .with_context(|| format!("{}: declarations", template.display()))?;
        declared
            .validate()
            .with_context(|| format!("{}: declarations", template.display()))?;
        Ok(declared)
    }

    /// Where the output goes.
    fn target(&self) -> PathBuf {
        self.path.join(&self.name)
    }
}

/// Every tracked template in the source tree. Flat or nested, the layout says
/// nothing: each template declares its own target.
///
/// Only tracked, because `prepare` stages what it renders: a template git does
/// not carry would put a served file on the tag with no source beside it, and
/// `check` would have nothing to compare against on a fresh clone. But one that
/// is present and untracked stops the run rather than rendering nothing —
/// adding a served file and getting silence served the stale file instead.
fn sources(root: &Path, config: &Templates) -> Result<Vec<PathBuf>> {
    let tracked: Vec<PathBuf> = git::tracked(root)?
        .into_iter()
        .filter(|path| is_template(path, config))
        .collect();
    if git::is_repository(root) {
        refuse_untracked(root, config, &tracked)?;
    }
    Ok(tracked)
}

fn is_template(path: &Path, config: &Templates) -> bool {
    path.starts_with(&config.source)
        && path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with(&config.suffix))
}

/// A template present in the source tree that the repo neither tracks nor
/// ignores was written and forgotten. One it ignores was written and disowned,
/// which is a repo saying it is not part of what it publishes — the same thing
/// `git::tracked` reads the index for — so that one is left alone.
fn refuse_untracked(root: &Path, config: &Templates, tracked: &[PathBuf]) -> Result<()> {
    let loose: Vec<String> = present(&root.join(&config.source), &config.suffix)?
        .iter()
        .filter_map(|path| path.strip_prefix(root).ok())
        .filter(|path| !tracked.iter().any(|known| known == path))
        .filter(|path| !git::is_ignored(root, path))
        .map(|path| path.display().to_string())
        .collect();
    if loose.is_empty() {
        return Ok(());
    }
    bail!(
        "a template git does not track renders nothing: {} — commit it or delete it",
        loose.join(", ")
    );
}

/// Every template on disk under `dir`, at any depth. A directory that is not
/// there holds none: a repo serving nothing writes no source tree.
///
/// Symlinks are skipped rather than followed, so one pointing at an ancestor
/// cannot recurse forever and one pointing outside cannot pull a foreign file
/// into this repo's answer. `ensure_inside` refuses a symlinked target for the
/// same reason.
fn present(dir: &Path, suffix: &str) -> Result<Vec<PathBuf>> {
    let Ok(entries) = fs::read_dir(dir) else {
        return Ok(Vec::new());
    };
    let mut found = Vec::new();
    for entry in entries {
        let path = entry.with_context(|| dir.display().to_string())?.path();
        let kind = fs::symlink_metadata(&path)
            .with_context(|| path.display().to_string())?
            .file_type();
        if kind.is_symlink() {
            continue;
        }
        if kind.is_dir() {
            found.extend(present(&path, suffix)?);
        } else if path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with(suffix))
        {
            found.push(path);
        }
    }
    found.sort();
    Ok(found)
}

/// A target a template may write: inside the repository, not through a
/// symlink, and not escaping upward.
fn ensure_inside(root: &Path, target: &Path) -> Result<()> {
    if target.is_absolute()
        || target
            .components()
            .any(|part| matches!(part, Component::ParentDir))
    {
        bail!("target must stay inside the repo: {}", target.display());
    }
    let path = root.join(target);
    if let Ok(meta) = fs::symlink_metadata(&path)
        && meta.file_type().is_symlink()
    {
        bail!("target must not be a symlink: {}", path.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use git2::Repository;
    use indoc::indoc;
    use tempfile::TempDir;

    /// The one template every version case below renders.
    const TEMPLATE: &str = indoc! {r#"
        {%- set path = "tasks/ver" -%}
        #!/usr/bin/env bash
        #MISE tools = { "github:victor-software-house/verctl" = "{{ versions["verctl"] }}", "cargo:ctl-core" = "{{ versions["ctl-core"] }}" }

        exec verctl "$@"
    "#};

    /// The one served file every version case below starts from.
    const BEFORE: &str = indoc! {r#"
        #!/usr/bin/env bash
        #MISE tools = { "github:victor-software-house/verctl" = "0.0.1", "cargo:ctl-core" = "1.0.0" }

        exec verctl "$@"
    "#};

    const SERVED: &str = "tasks/ver/ver";
    const TEMPLATE_PATH: &str = ".ctl/templates/ver.jinja";

    /// What a release does to `BEFORE`: the exact bytes, or the failure.
    enum Outcome {
        Serves(&'static str),
        Fails(&'static str),
    }

    fn versions(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(name, version)| ((*name).to_owned(), (*version).to_owned()))
            .collect()
    }

    /// A repo whose index holds exactly `files`, each with the given body.
    fn repo(files: &[(&str, &str)]) -> TempDir {
        let root = TempDir::new().unwrap();
        let repository = Repository::init(root.path()).unwrap();
        let mut index = repository.index().unwrap();
        for (path, body) in files {
            let full = root.path().join(path);
            fs::create_dir_all(full.parent().unwrap()).unwrap();
            fs::write(&full, body).unwrap();
            index.add_path(Path::new(path)).unwrap();
        }
        index.write().unwrap();
        root
    }

    fn read(root: &TempDir, path: &str) -> String {
        fs::read_to_string(root.path().join(path)).unwrap()
    }

    /// One template, one before, many releases — each asserted whole.
    #[test]
    fn one_template_serves_every_release_exactly() {
        let cases = [
            (
                "both packages move",
                &[("verctl", "0.0.2"), ("ctl-core", "1.2.3")][..],
                Outcome::Serves(indoc! {r#"
                    #!/usr/bin/env bash
                    #MISE tools = { "github:victor-software-house/verctl" = "0.0.2", "cargo:ctl-core" = "1.2.3" }

                    exec verctl "$@"
                "#}),
            ),
            (
                "only the tool moves",
                &[("verctl", "1.0.0"), ("ctl-core", "1.0.0")][..],
                Outcome::Serves(indoc! {r#"
                    #!/usr/bin/env bash
                    #MISE tools = { "github:victor-software-house/verctl" = "1.0.0", "cargo:ctl-core" = "1.0.0" }

                    exec verctl "$@"
                "#}),
            ),
            (
                "a release that changes nothing still serves the same bytes",
                &[("verctl", "0.0.1"), ("ctl-core", "1.0.0")][..],
                Outcome::Serves(BEFORE),
            ),
            (
                "a package the template names is not in the release",
                &[("verctl", "0.0.2")][..],
                Outcome::Fails(TEMPLATE_PATH),
            ),
            ("no packages at all", &[][..], Outcome::Fails(TEMPLATE_PATH)),
        ];
        for (label, pairs, outcome) in cases {
            let root = repo(&[(TEMPLATE_PATH, TEMPLATE), (SERVED, BEFORE)]);
            let result = write(root.path(), &Templates::default(), &versions(pairs));
            match outcome {
                Outcome::Serves(after) => {
                    assert_eq!(result.unwrap(), [root.path().join(SERVED)], "{label}");
                    assert_eq!(read(&root, SERVED), after, "{label}");
                }
                Outcome::Fails(named) => {
                    let report = format!("{:#}", result.unwrap_err());
                    assert!(report.contains(named), "{label}: {report}");
                    assert_eq!(read(&root, SERVED), BEFORE, "{label}");
                }
            }
            assert_eq!(read(&root, TEMPLATE_PATH), TEMPLATE, "{label}");
        }
    }

    /// The Version PR is regenerated on every push to main, so a second render
    /// of the same versions must produce the same bytes.
    #[test]
    fn rendering_twice_serves_the_same_bytes() {
        let root = repo(&[(TEMPLATE_PATH, TEMPLATE), (SERVED, BEFORE)]);
        let moved = versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]);
        write(root.path(), &Templates::default(), &moved).unwrap();
        let once = read(&root, SERVED);
        write(root.path(), &Templates::default(), &moved).unwrap();
        assert_eq!(read(&root, SERVED), once);
    }

    #[test]
    fn a_plan_reports_the_served_file_without_writing_it() {
        let root = repo(&[(TEMPLATE_PATH, TEMPLATE), (SERVED, BEFORE)]);
        assert_eq!(
            plan(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")])
            )
            .unwrap(),
            [root.path().join(SERVED)]
        );
        assert_eq!(read(&root, SERVED), BEFORE);
    }

    #[test]
    fn a_broken_template_fails_before_writing_the_served_file() {
        let root = repo(&[(TEMPLATE_PATH, "pin {{ versions[\n"), (SERVED, BEFORE)]);
        assert!(
            write(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2")])
            )
            .is_err()
        );
        assert_eq!(read(&root, SERVED), BEFORE);
    }

    /// Which pairs exist at all: the tree varies here, not the versions.
    #[test]
    fn an_untracked_template_stops_the_run_and_one_outside_is_ignored() {
        let moved = versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]);

        let stray_template = repo(&[(SERVED, BEFORE)]);
        let path = stray_template.path().join(TEMPLATE_PATH);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, TEMPLATE).unwrap();
        let error = write(stray_template.path(), &Templates::default(), &moved).unwrap_err();
        let text = format!("{error:#}");
        assert!(text.contains(TEMPLATE_PATH), "{text}");
        assert!(text.contains("commit it or delete it"), "{text}");
        assert_eq!(
            read(&stray_template, SERVED),
            BEFORE,
            "the served file is left alone: the run stops before anything is written"
        );

        let outside = repo(&[("templates/changelog.jinja", "# {{ anything }}\n")]);
        assert_eq!(
            write(outside.path(), &Templates::default(), &moved).unwrap(),
            Vec::<PathBuf>::new()
        );
        assert_eq!(
            read(&outside, "templates/changelog.jinja"),
            "# {{ anything }}\n"
        );
    }

    /// The layout says nothing, so neither does the search: a template nested
    /// under the source tree counts, and every loose one is named at once
    /// rather than one release at a time.
    #[test]
    fn every_untracked_template_is_named_at_whatever_depth_it_sits() {
        let root = repo(&[(SERVED, BEFORE)]);
        for path in [
            ".ctl/templates/ver.jinja",
            ".ctl/templates/nested/deeper/readme.jinja",
        ] {
            let full = root.path().join(path);
            fs::create_dir_all(full.parent().unwrap()).unwrap();
            fs::write(&full, TEMPLATE).unwrap();
        }
        fs::write(root.path().join(".ctl/templates/notes.md"), "not one\n").unwrap();
        let error = write(
            root.path(),
            &Templates::default(),
            &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]),
        )
        .unwrap_err();
        let text = format!("{error:#}");
        assert!(text.contains(".ctl/templates/ver.jinja"), "{text}");
        assert!(
            text.contains(".ctl/templates/nested/deeper/readme.jinja"),
            "{text}"
        );
        assert!(
            !text.contains("notes.md"),
            "a file without the suffix is not a template: {text}"
        );
    }

    /// One template body, every declaration a repo might write: what the
    /// schema accepts, where it lands, and what it refuses.
    #[test]
    fn the_schema_decides_where_a_template_lands() {
        let cases = [
            (
                "nothing declared: the template's own name, at the root",
                "",
                Ok("ver"),
            ),
            (
                "a directory",
                r#"{%- set path = "tasks/ver" -%}"#,
                Ok("tasks/ver/ver"),
            ),
            (
                "a name",
                r#"{%- set name = "mise.toml" -%}"#,
                Ok("mise.toml"),
            ),
            (
                "both",
                indoc! {r#"
                    {%- set path = "examples" -%}
                    {%- set name = "mise.toml" -%}
                "#},
                Ok("examples/mise.toml"),
            ),
            (
                "a computed declaration is still a declaration",
                r#"{%- set path = "tasks/" ~ "ver" -%}"#,
                Ok("tasks/ver/ver"),
            ),
            (
                "a path that climbs out",
                r#"{%- set path = "../escaped" -%}"#,
                Err("path: must stay inside the repository"),
            ),
            (
                "an absolute path",
                r#"{%- set path = "/etc" -%}"#,
                Err("path: must stay inside the repository"),
            ),
            (
                "a name that is a path",
                r#"{%- set name = "tasks/ver" -%}"#,
                Err("name: must be one file name"),
            ),
            (
                "a name that climbs out",
                r#"{%- set name = ".." -%}"#,
                Err("name: must be one file name"),
            ),
            (
                "a path of the wrong type",
                r"{%- set path = 5 -%}",
                Err("invalid type"),
            ),
            (
                "an executable of the wrong type",
                r#"{%- set executable = "yes" -%}"#,
                Err("expected a boolean"),
            ),
        ];
        for (label, declaration, expected) in cases {
            let root = repo(&[(TEMPLATE_PATH, &format!("{declaration}served\n"))]);
            let result = write(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2")]),
            );
            match expected {
                Ok(target) => {
                    assert_eq!(result.unwrap(), [root.path().join(target)], "{label}");
                    assert_eq!(read(&root, target), "served\n", "{label}");
                }
                Err(complaint) => {
                    let report = format!("{:#}", result.unwrap_err());
                    assert!(report.contains(complaint), "{label}: {report}");
                    assert!(report.contains(TEMPLATE_PATH), "{label}: {report}");
                }
            }
        }
    }

    /// A template's other variables are its own business: a `tool` it uses to
    /// build a line is not a declaration, and must not fail the schema.
    #[test]
    fn an_export_the_schema_does_not_know_is_the_templates_own() {
        let root = repo(&[(
            TEMPLATE_PATH,
            indoc! {r#"
                {%- set tool = "github:victor-software-house/verctl" -%}
                {%- set path = "tasks/ver" -%}
                {{ tool }} = "{{ versions["verctl"] }}"
            "#},
        )]);
        write(
            root.path(),
            &Templates::default(),
            &versions(&[("verctl", "0.0.2")]),
        )
        .unwrap();
        assert_eq!(
            read(&root, "tasks/ver/ver"),
            "github:victor-software-house/verctl = \"0.0.2\"\n"
        );
    }

    /// The target's own path, however deep, with no template beside it: a
    /// README template does not sit in the repo root next to `README.md`.
    #[test]
    fn a_flat_template_names_a_target_at_any_depth() {
        let root = repo(&[
            (
                ".ctl/templates/readme.jinja",
                "{%- set name = \"README.md\" -%}\nRun verctl@{{ versions[\"verctl\"] }}.\n",
            ),
            ("README.md", "Run verctl@0.0.1.\n"),
            (TEMPLATE_PATH, TEMPLATE),
            (SERVED, BEFORE),
        ]);
        let mut rendered = write(
            root.path(),
            &Templates::default(),
            &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]),
        )
        .unwrap();
        rendered.sort();
        assert_eq!(
            rendered,
            [root.path().join("README.md"), root.path().join(SERVED)]
        );
        assert_eq!(read(&root, "README.md"), "Run verctl@0.0.2.\n");
        assert!(!root.path().join("README.md.jinja").exists());
        assert!(!root.path().join(".ctl/templates/tasks").exists());
    }

    /// The one mode bit git records, declared by the template that needs it.
    /// A served task file is executable; the README beside it is not.
    #[test]
    fn a_template_declares_the_one_mode_bit_git_records() {
        let root = repo(&[
            (
                ".ctl/templates/ver.jinja",
                indoc! {r#"
                    {%- set path = "tasks/ver" -%}
                    {%- set executable = true -%}
                    #!/usr/bin/env bash
                    exec verctl@{{ versions["verctl"] }} "$@"
                "#},
            ),
            (SERVED, BEFORE),
            (
                ".ctl/templates/readme.jinja",
                indoc! {r#"
                    {%- set name = "README.md" -%}
                    {%- set executable = false -%}
                    Run verctl@{{ versions["verctl"] }}.
                "#},
            ),
            ("README.md", "Run verctl@0.0.1.\n"),
        ]);
        write(
            root.path(),
            &Templates::default(),
            &versions(&[("verctl", "0.0.2")]),
        )
        .unwrap();
        let mode = |path: &str| {
            fs::metadata(root.path().join(path))
                .unwrap()
                .permissions()
                .mode()
                & 0o777
        };
        assert_eq!(mode(SERVED), 0o755);
        assert_eq!(mode("README.md"), 0o644);
        assert!(
            read(&root, SERVED).starts_with("#!/usr/bin/env bash\n"),
            "{}",
            read(&root, SERVED)
        );
    }

    /// Unsaid is not "leave it": a served file's mode is part of what the tag
    /// carries, so silence means 0644 and a stale 0755 is corrected.
    #[test]
    fn a_template_that_says_nothing_about_mode_serves_0644() {
        let root = repo(&[(TEMPLATE_PATH, TEMPLATE), (SERVED, BEFORE)]);
        fs::set_permissions(root.path().join(SERVED), fs::Permissions::from_mode(0o755)).unwrap();
        write(
            root.path(),
            &Templates::default(),
            &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]),
        )
        .unwrap();
        assert_eq!(
            fs::metadata(root.path().join(SERVED))
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o644
        );
    }

    #[test]
    fn the_source_tree_and_suffix_are_configurable() {
        let root = repo(&[("served/tasks/ver/ver.tmpl", TEMPLATE), (SERVED, BEFORE)]);
        let config = Templates {
            source: PathBuf::from("served"),
            suffix: ".tmpl".to_owned(),
        };
        let rendered = write(
            root.path(),
            &config,
            &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")]),
        )
        .unwrap();
        assert_eq!(rendered, [root.path().join(SERVED)]);
        assert_eq!(
            read(&root, SERVED),
            indoc! {r#"
                #!/usr/bin/env bash
                #MISE tools = { "github:victor-software-house/verctl" = "0.0.2", "cargo:ctl-core" = "1.2.3" }

                exec verctl "$@"
            "#}
        );
    }

    /// A tree with no repository cannot serve a file by tag, so it has no
    /// templates — `prepare` still works there, as it did before templates
    /// existed. A repository whose index cannot be read is a different case,
    /// and `git::tracked` reports that as an error.
    /// One repository may hold several projects. The index speaks in paths from
    /// the working tree, so a project in a subdirectory has to be found by the
    /// path it uses itself — and a sibling project's templates are not its.
    #[test]
    fn a_project_below_the_repository_root_serves_its_own_templates() {
        let root = repo(&[
            (&format!("tool/{TEMPLATE_PATH}"), TEMPLATE),
            (&format!("tool/{SERVED}"), BEFORE),
            (&format!("other/{TEMPLATE_PATH}"), TEMPLATE),
        ]);
        let project = root.path().join("tool");
        assert_eq!(
            write(
                &project,
                &Templates::default(),
                &versions(&[("verctl", "0.0.2"), ("ctl-core", "0.1.0")])
            )
            .unwrap(),
            [project.join(SERVED)],
            "the project's own template, named the way the project names it"
        );
        assert_eq!(
            fs::read_to_string(root.path().join(format!("other/{SERVED}"))).ok(),
            None,
            "a sibling project's template is not this one's to render"
        );
    }

    /// A repo that serves nothing says so before anything is read on its
    /// behalf: rendering needs every package's version, and a repo with no
    /// template must not pay for that map.
    #[test]
    fn a_repo_with_no_template_serves_nothing() {
        let bare = repo(&[("README.md", "nothing to serve\n")]);
        assert!(!any(bare.path(), &Templates::default()).unwrap());
        let serving = repo(&[(TEMPLATE_PATH, TEMPLATE)]);
        assert!(any(serving.path(), &Templates::default()).unwrap());
    }

    /// Ignoring a file is a repo disowning it, which is the same statement
    /// `tracked` reads the index for — so nothing asks its author to commit it.
    #[test]
    fn an_ignored_template_is_disowned_rather_than_forgotten() {
        let root = repo(&[(SERVED, BEFORE), (".gitignore", "*.local.jinja\n")]);
        let scratch = root.path().join(".ctl/templates/draft.local.jinja");
        fs::create_dir_all(scratch.parent().unwrap()).unwrap();
        fs::write(&scratch, TEMPLATE).unwrap();
        assert_eq!(
            write(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")])
            )
            .unwrap(),
            Vec::<PathBuf>::new()
        );
        assert_eq!(read(&root, SERVED), BEFORE);
    }

    /// A symlink is not followed, so a directory outside this repository cannot
    /// have its templates counted as ours — which would ask whoever ran the
    /// release to commit a file that is not theirs.
    #[test]
    fn a_symlink_out_of_the_repository_serves_nothing_of_its_own() {
        let elsewhere = TempDir::new().unwrap();
        fs::write(elsewhere.path().join("foreign.jinja"), TEMPLATE).unwrap();

        let root = repo(&[(SERVED, BEFORE)]);
        let templates = root.path().join(".ctl/templates");
        fs::create_dir_all(&templates).unwrap();
        std::os::unix::fs::symlink(elsewhere.path(), templates.join("linked")).unwrap();
        assert_eq!(
            write(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2"), ("ctl-core", "1.2.3")])
            )
            .unwrap(),
            Vec::<PathBuf>::new()
        );
    }

    /// A template here is not untracked — there is no index to not carry it.
    /// Such a tree cannot serve a file by tag at all, so it renders nothing and
    /// says nothing, rather than failing the way a repository would.
    #[test]
    fn a_tree_with_no_repository_has_no_templates() {
        let root = TempDir::new().unwrap();
        let path = root.path().join(TEMPLATE_PATH);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, TEMPLATE).unwrap();
        assert_eq!(
            write(
                root.path(),
                &Templates::default(),
                &versions(&[("verctl", "0.0.2")])
            )
            .unwrap(),
            Vec::<PathBuf>::new()
        );
    }
}