autumn-cli 0.8.0

CLI tool for the Autumn web framework
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
//! `autumn new --starter` — curated built-in and community (git) starters.
//!
//! A *starter* scaffolds a complete, runnable application archetype rather than
//! the minimal base project `autumn new <name>` produces. Built-in starters are
//! vetted, version-locked, and embedded in the CLI (no network fetch, no
//! confirmation). Community starters are fetched from a git URL (or `owner/repo`
//! shorthand) — their provenance is printed and confirmed before anything is
//! fetched or applied. A local directory acts as a community starter too, which
//! lets fixtures and authors test a starter without publishing it.
//!
//! Built-in and community starters share one [`manifest`] format
//! (`autumn-starter.toml`) and one render path — the same `{{…}}` substitution
//! [`crate::new`] uses for the base project (issue #993).

pub mod builtin;
pub mod git;
pub mod manifest;

use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};

use include_dir::Dir;

use crate::generate::Flags;
use crate::generate::emit::Plan;
use crate::new::{TemplateVars, render_template, validate_name};
use git::GitSource;
use manifest::{MANIFEST_FILE, Manifest};

/// Errors that can occur while resolving, fetching, or applying a starter.
#[derive(Debug, thiserror::Error)]
pub enum StarterError {
    /// The `--starter` value is not a valid source.
    #[error("{0}")]
    InvalidSource(String),

    /// Both an `@ref` suffix and `--starter-ref` were supplied.
    #[error("a starter ref was given twice (an '@ref' suffix and --starter-ref); supply only one")]
    AmbiguousRef,

    /// `--starter-ref` was given for a built-in or local-path starter.
    #[error("--starter-ref only applies to git starters")]
    RefNotApplicable,

    /// The project directory already exists.
    #[error("directory '{0}' already exists")]
    AlreadyExists(String),

    /// The project name is not a valid Rust package name.
    #[error("invalid project name '{0}': {1}")]
    InvalidName(String, String),

    /// The starter has no `autumn-starter.toml`, or it is malformed.
    #[error("invalid starter manifest: {0}")]
    Manifest(String),

    /// The system `git` binary was not found on `PATH`.
    #[error(
        "git is required to fetch a community starter but was not found on PATH; \
         install git or use a built-in starter (autumn new --list-starters)"
    )]
    GitNotInstalled,

    /// `git clone` failed.
    #[error("{0}")]
    CloneFailed(String),

    /// A non-built-in starter needs confirmation but stdin is not interactive.
    #[error(
        "fetching a community starter requires confirmation; re-run with --yes to \
         proceed non-interactively"
    )]
    ConfirmationRequired,

    /// The user declined the confirmation prompt.
    #[error("aborted: starter not applied")]
    Aborted,

    /// Filesystem error.
    #[error("{0}")]
    Io(#[from] io::Error),

    /// Error from the underlying project emission engine.
    #[error("{0}")]
    Emit(#[from] crate::generate::GenerateError),
}

/// Where a `--starter` value resolves to.
#[derive(Debug)]
pub enum Resolved {
    /// A curated, embedded starter.
    Builtin(&'static builtin::Builtin),
    /// A community starter on the local filesystem.
    LocalDir(PathBuf),
    /// A community starter in a git repository.
    Git(GitSource),
}

impl Resolved {
    /// Whether the starter must be confirmed before it is fetched/applied.
    /// Built-in starters apply without a network fetch or prompt.
    #[must_use]
    pub const fn requires_confirmation(&self) -> bool {
        !matches!(self, Self::Builtin(_))
    }
}

/// Resolve a `--starter` value (+ optional `--starter-ref`) into a source.
///
/// Resolution order: exact built-in name → existing local directory → git
/// (full URL or `owner/repo` shorthand).
///
/// # Errors
/// See [`StarterError`] variants for the failure modes (ambiguous/non-applicable
/// ref, invalid source).
pub fn resolve(value: &str, ref_override: Option<&str>) -> Result<Resolved, StarterError> {
    if let Some(b) = builtin::find(value) {
        if ref_override.is_some() {
            return Err(StarterError::RefNotApplicable);
        }
        return Ok(Resolved::Builtin(b));
    }
    if Path::new(value).is_dir() {
        if ref_override.is_some() {
            return Err(StarterError::RefNotApplicable);
        }
        return Ok(Resolved::LocalDir(PathBuf::from(value)));
    }
    let source = git::resolve(value, ref_override)?;
    Ok(Resolved::Git(source))
}

/// A starter loaded into memory: its manifest plus every template file.
#[derive(Debug)]
struct StarterContents {
    manifest: Manifest,
    files: Vec<StarterFile>,
}

/// One file from a starter tree (path relative to the starter root, raw bytes).
#[derive(Debug)]
struct StarterFile {
    rel_path: String,
    bytes: Vec<u8>,
}

/// Outcome of the provenance-confirmation decision, separated from IO so it can
/// be unit-tested without a real terminal.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfirmMode {
    /// Proceed without prompting (`--yes`, or a built-in).
    Proceed,
    /// Prompt the user interactively.
    Prompt,
    /// Refuse: confirmation is required but stdin is not a TTY and `--yes` was
    /// not given.
    NeedsYesFlag,
}

/// Decide how to confirm a non-built-in starter, given the `--yes` flag and
/// whether stdin is interactive. Pure — the IO lives in [`confirm`].
#[must_use]
pub const fn confirm_mode(yes: bool, interactive: bool) -> ConfirmMode {
    if yes {
        ConfirmMode::Proceed
    } else if interactive {
        ConfirmMode::Prompt
    } else {
        ConfirmMode::NeedsYesFlag
    }
}

/// Human-readable provenance line for a non-built-in starter.
fn provenance(resolved: &Resolved) -> String {
    match resolved {
        Resolved::Builtin(b) => format!("Built-in starter '{}'", b.name),
        Resolved::LocalDir(path) => {
            let abs = path.canonicalize().unwrap_or_else(|_| path.clone());
            format!("Community starter (local path): {}", abs.display())
        }
        Resolved::Git(source) => {
            let reference = source.reference.as_deref().unwrap_or("<default branch>");
            format!("Community starter (git): {} (ref: {reference})", source.url)
        }
    }
}

/// Print the resolved provenance and confirm before fetching/applying.
fn confirm(provenance: &str, yes: bool) -> Result<(), StarterError> {
    println!("{provenance}");
    match confirm_mode(yes, io::stdin().is_terminal()) {
        ConfirmMode::Proceed => Ok(()),
        ConfirmMode::NeedsYesFlag => Err(StarterError::ConfirmationRequired),
        ConfirmMode::Prompt => {
            print!("Proceed? [y/N] ");
            io::stdout().flush().ok();
            let mut line = String::new();
            io::stdin().read_line(&mut line)?;
            if matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
                Ok(())
            } else {
                Err(StarterError::Aborted)
            }
        }
    }
}

/// Print the list of built-in starters (for `autumn new --list-starters`).
pub fn print_list() {
    println!("Available built-in starters:\n");
    let width = builtin::BUILTINS
        .iter()
        .map(|b| b.name.len())
        .max()
        .unwrap_or(0);
    for b in builtin::BUILTINS {
        println!("  {:<width$}  {}", b.name, b.description, width = width);
    }
    println!("\nScaffold one with:   autumn new <name> --starter <starter>");
    println!("Community starters:  autumn new <name> --starter <git-url|owner/repo>[@ref] [--yes]");
}

/// Entry point for `autumn new <name> --starter <value>`.
///
/// Exits the process non-zero with a diagnostic on any error, mirroring
/// [`crate::new::run`].
pub fn run(name: &str, starter: &str, starter_ref: Option<&str>, yes: bool, flags: Flags) {
    let cwd = std::env::current_dir().unwrap_or_else(|e| {
        eprintln!("Error: cannot determine current directory: {e}");
        std::process::exit(1);
    });
    if let Err(e) = run_inner(name, starter, starter_ref, yes, flags, &cwd) {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

fn run_inner(
    name: &str,
    starter: &str,
    starter_ref: Option<&str>,
    yes: bool,
    flags: Flags,
    parent_dir: &Path,
) -> Result<(), StarterError> {
    validate_name(name).map_err(|e| {
        StarterError::InvalidName(name.to_owned(), strip_name_error(&e.to_string()))
    })?;

    let project_dir = parent_dir.join(name);
    if project_dir.exists() {
        return Err(StarterError::AlreadyExists(name.to_owned()));
    }

    let resolved = resolve(starter, starter_ref)?;

    // Surface provenance and confirm before fetching/applying anything that did
    // not ship with the CLI (built-ins are vetted and apply silently).
    if resolved.requires_confirmation() {
        confirm(&provenance(&resolved), yes)?;
    }

    // Any git clone goes into a tempdir that must outlive scaffolding; hold it
    // here and drop it explicitly once the files have been emitted.
    let mut clone_guard: Option<tempfile::TempDir> = None;
    let contents = match &resolved {
        Resolved::Builtin(b) => {
            println!("Scaffolding built-in starter '{}'", b.name);
            load_from_embedded(b.dir)?
        }
        Resolved::LocalDir(path) => load_from_dir(path)?,
        Resolved::Git(source) => {
            let tmp = tempfile::TempDir::new()?;
            git::clone_into(source, tmp.path())?;
            let contents = load_from_dir(tmp.path())?;
            clone_guard = Some(tmp);
            contents
        }
    };

    let crate_name = name.replace('-', "_");
    let vars = TemplateVars {
        project_name: name,
        crate_name: &crate_name,
        autumn_version: env!("CARGO_PKG_VERSION"),
        rust_version: option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("1.88.0"),
    };

    println!("\nCreating `{name}`:");
    scaffold(&contents, &vars, &project_dir, flags)?;
    drop(clone_guard);

    if !flags.dry_run {
        print_post_scaffold(&contents.manifest, &vars);
    }
    Ok(())
}

/// `NewError::InvalidName` renders as `invalid project name '<n>': <reason>`;
/// extract just the reason so we don't double up the prefix.
fn strip_name_error(msg: &str) -> String {
    msg.rsplit(": ").next().unwrap_or(msg).to_owned()
}

/// Recursively collect every embedded file, paths relative to the starter root.
fn collect_embedded(dir: &Dir<'_>, out: &mut Vec<StarterFile>) {
    for f in dir.files() {
        out.push(StarterFile {
            rel_path: f.path().to_string_lossy().replace('\\', "/"),
            bytes: f.contents().to_vec(),
        });
    }
    for d in dir.dirs() {
        collect_embedded(d, out);
    }
}

fn load_from_embedded(dir: &Dir<'_>) -> Result<StarterContents, StarterError> {
    let manifest_src = dir
        .get_file(MANIFEST_FILE)
        .ok_or_else(|| StarterError::Manifest(format!("missing {MANIFEST_FILE}")))?
        .contents_utf8()
        .ok_or_else(|| StarterError::Manifest(format!("{MANIFEST_FILE} is not valid UTF-8")))?;
    let manifest = Manifest::parse(manifest_src).map_err(StarterError::Manifest)?;

    let mut all = Vec::new();
    collect_embedded(dir, &mut all);
    Ok(finish_contents(manifest, all))
}

/// Directory names that are always skipped when collecting a community starter
/// from the local filesystem — they contain build artefacts, not source files.
const SKIP_DIRS: &[&str] = &[".git", "target", "node_modules", "dist", "build"];

/// Recursively read a starter from the filesystem, skipping common artefact dirs.
fn collect_dir(root: &Path, cur: &Path, out: &mut Vec<StarterFile>) -> io::Result<()> {
    for entry in fs::read_dir(cur)? {
        let entry = entry?;
        if SKIP_DIRS.contains(&entry.file_name().to_str().unwrap_or("")) {
            continue;
        }
        // Skip symlinks entirely: following them risks infinite recursion (a link
        // to an ancestor) and reading/writing files outside the starter root.
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            continue;
        }
        let path = entry.path();
        if file_type.is_dir() {
            collect_dir(root, &path, out)?;
        } else {
            let rel = path
                .strip_prefix(root)
                .unwrap_or(&path)
                .to_string_lossy()
                .replace('\\', "/");
            out.push(StarterFile {
                rel_path: rel,
                bytes: fs::read(&path)?,
            });
        }
    }
    Ok(())
}

fn load_from_dir(root: &Path) -> Result<StarterContents, StarterError> {
    let manifest_path = root.join(MANIFEST_FILE);
    let manifest_src = fs::read_to_string(&manifest_path).map_err(|_| {
        StarterError::Manifest(format!(
            "missing {MANIFEST_FILE} at the starter root ({})",
            root.display()
        ))
    })?;
    let manifest = Manifest::parse(&manifest_src).map_err(StarterError::Manifest)?;

    let mut all = Vec::new();
    collect_dir(root, root, &mut all)?;
    Ok(finish_contents(manifest, all))
}

/// Drop the manifest from the file list and sort for deterministic emission.
fn finish_contents(manifest: Manifest, mut all: Vec<StarterFile>) -> StarterContents {
    all.retain(|f| f.rel_path != MANIFEST_FILE);
    all.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
    StarterContents {
        manifest,
        files: all,
    }
}

/// Whether `rel_path` should be emitted verbatim (no template substitution).
fn is_verbatim(manifest: &Manifest, rel_path: &str) -> bool {
    manifest.starter.verbatim.iter().any(|p| p == rel_path)
}

/// Suffix stripped from a starter file's in-tree name when it is emitted into
/// the scaffolded project.
///
/// A starter ships its project manifest as `Cargo.toml.tmpl` rather than a
/// literal `Cargo.toml`: `cargo package` treats any subdirectory that contains
/// a `Cargo.toml` as a nested crate and drops that whole subtree from the
/// published tarball, which would leave `include_dir!` with no starter files to
/// embed at `cargo publish` verify time. The `.tmpl` suffix keeps the file in
/// the tarball; it is removed here so the generated project gets a real
/// `Cargo.toml` (and any other `*.tmpl`-named starter file its intended name).
const TEMPLATE_SUFFIX: &str = ".tmpl";

/// Map a starter file's in-tree path to the path emitted into the project,
/// stripping a single trailing [`TEMPLATE_SUFFIX`].
fn emit_rel_path(rel_path: &str) -> &str {
    rel_path.strip_suffix(TEMPLATE_SUFFIX).unwrap_or(rel_path)
}

/// Render and emit a loaded starter into `project_dir`.
fn scaffold(
    contents: &StarterContents,
    vars: &TemplateVars<'_>,
    project_dir: &Path,
    flags: Flags,
) -> Result<(), StarterError> {
    let mut plan = Plan::new(project_dir);
    for file in &contents.files {
        // Defence-in-depth: reject absolute paths or `..` components so a
        // malicious starter cannot write outside the target project directory.
        let rel_path = Path::new(&file.rel_path);
        if rel_path.is_absolute()
            || rel_path
                .components()
                .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            return Err(StarterError::InvalidSource(format!(
                "malicious path in starter: {}",
                file.rel_path
            )));
        }
        let target = project_dir.join(emit_rel_path(&file.rel_path));
        // Verbatim or non-UTF-8 files are copied byte-for-byte; substituting
        // them would corrupt binary assets.
        if is_verbatim(&contents.manifest, &file.rel_path) {
            plan.create_bytes(target, file.bytes.clone());
        } else {
            match std::str::from_utf8(&file.bytes) {
                Ok(text) => plan.create(target, render_template(text, vars)),
                Err(_) => plan.create_bytes(target, file.bytes.clone()),
            }
        }
    }
    plan.execute(flags)?;
    Ok(())
}

/// Print the manifest's post-scaffold notes (with `{{…}}` substituted).
fn print_post_scaffold(manifest: &Manifest, vars: &TemplateVars<'_>) {
    if let Some(notes) = &manifest.starter.post_scaffold_notes {
        println!("\n{}", render_template(notes, vars));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builtin_resolves_without_confirmation() {
        let r = resolve("saas", None).unwrap();
        assert!(matches!(r, Resolved::Builtin(_)));
        assert!(!r.requires_confirmation());
    }

    #[test]
    fn emit_rel_path_strips_single_tmpl_suffix() {
        // The packaging-safe manifest name is emitted as a real Cargo.toml.
        assert_eq!(emit_rel_path("Cargo.toml.tmpl"), "Cargo.toml");
        assert_eq!(emit_rel_path("src/main.rs"), "src/main.rs");
        // Only a single trailing suffix is stripped.
        assert_eq!(emit_rel_path("weird.tmpl.tmpl"), "weird.tmpl");
        assert_eq!(emit_rel_path("no-suffix"), "no-suffix");
    }

    #[test]
    fn embedded_saas_emits_a_real_cargo_toml() {
        // The starter ships Cargo.toml.tmpl (so cargo package keeps the subtree),
        // but scaffolding must produce a real Cargo.toml — and the .tmpl name
        // must never leak into the generated project.
        let contents = load_from_embedded(&builtin::SAAS).unwrap();
        let tmp = tempfile::TempDir::new().unwrap();
        let dest = tmp.path().join("app");
        let crate_name = "app".to_owned();
        let vars = TemplateVars {
            project_name: "app",
            crate_name: &crate_name,
            autumn_version: env!("CARGO_PKG_VERSION"),
            rust_version: option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("1.88.0"),
        };
        scaffold(&contents, &vars, &dest, Flags::default()).unwrap();
        assert!(dest.join("Cargo.toml").is_file());
        assert!(!dest.join("Cargo.toml.tmpl").exists());
        let cargo = fs::read_to_string(dest.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("name = \"app\""), "got: {cargo}");
        assert!(!cargo.contains("{{"), "no tokens should remain: {cargo}");
    }

    #[test]
    fn builtin_rejects_ref() {
        assert!(matches!(
            resolve("saas", Some("v1")).unwrap_err(),
            StarterError::RefNotApplicable
        ));
    }

    #[test]
    fn local_dir_resolves_as_community() {
        let tmp = tempfile::TempDir::new().unwrap();
        let r = resolve(tmp.path().to_str().unwrap(), None).unwrap();
        assert!(matches!(r, Resolved::LocalDir(_)));
        assert!(r.requires_confirmation());
    }

    #[test]
    fn unknown_value_resolves_as_git_shorthand() {
        let r = resolve("owner/repo", None).unwrap();
        match r {
            Resolved::Git(src) => {
                assert_eq!(src.url, "https://github.com/owner/repo.git");
                assert!(r_requires_confirmation_git());
            }
            _ => panic!("expected git source"),
        }
    }

    fn r_requires_confirmation_git() -> bool {
        Resolved::Git(GitSource {
            url: String::new(),
            reference: None,
        })
        .requires_confirmation()
    }

    #[test]
    fn confirm_mode_yes_proceeds() {
        assert_eq!(confirm_mode(true, false), ConfirmMode::Proceed);
        assert_eq!(confirm_mode(true, true), ConfirmMode::Proceed);
    }

    #[test]
    fn confirm_mode_non_tty_without_yes_needs_flag() {
        assert_eq!(confirm_mode(false, false), ConfirmMode::NeedsYesFlag);
    }

    #[test]
    fn confirm_mode_tty_without_yes_prompts() {
        assert_eq!(confirm_mode(false, true), ConfirmMode::Prompt);
    }

    #[test]
    fn builtin_list_includes_saas() {
        assert!(builtin::BUILTINS.iter().any(|b| b.name == "saas"));
    }

    fn fixture_minimal() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/starters/minimal")
    }

    #[test]
    fn scaffold_local_fixture_substitutes_and_copies_verbatim() {
        let contents = load_from_dir(&fixture_minimal()).unwrap();
        assert_eq!(contents.manifest.starter.name, "minimal");

        let tmp = tempfile::TempDir::new().unwrap();
        let dest = tmp.path().join("acme-app");
        let crate_name = "acme_app".to_owned();
        let vars = TemplateVars {
            project_name: "acme-app",
            crate_name: &crate_name,
            autumn_version: env!("CARGO_PKG_VERSION"),
            rust_version: option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("1.88.0"),
        };
        scaffold(&contents, &vars, &dest, Flags::default()).unwrap();

        // Template tokens substituted in text files.
        let cargo = fs::read_to_string(dest.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("name = \"acme_app\""), "got: {cargo}");
        let main_rs = fs::read_to_string(dest.join("src/main.rs")).unwrap();
        assert!(main_rs.contains("acme-app"));
        assert!(
            !main_rs.contains("{{"),
            "no tokens should remain: {main_rs}"
        );

        // The manifest itself is never emitted into the project.
        assert!(!dest.join(MANIFEST_FILE).exists());

        // The verbatim binary asset is copied byte-for-byte — not substituted
        // (it still contains the literal `{{project_name}}` and its non-UTF-8
        // bytes are intact).
        let original = fs::read(fixture_minimal().join("static/logo.bin")).unwrap();
        let copied = fs::read(dest.join("static/logo.bin")).unwrap();
        assert_eq!(
            copied, original,
            "verbatim binary asset must not be altered"
        );
        assert!(
            std::str::from_utf8(&copied).is_err(),
            "fixture asset is binary"
        );
    }

    #[test]
    fn missing_manifest_is_rejected() {
        let tmp = tempfile::TempDir::new().unwrap();
        fs::write(tmp.path().join("file.txt"), "no manifest here").unwrap();
        assert!(matches!(
            load_from_dir(tmp.path()).unwrap_err(),
            StarterError::Manifest(_)
        ));
    }

    /// Assert that `starter`, rendered with `project_name`, reproduces the
    /// committed `examples/{project_name}/` tree exactly.
    ///
    /// This is what keeps a shipped starter and its drift-gated example from
    /// diverging silently. Two files are excluded by contract:
    ///
    /// * `Cargo.toml` — the example uses an in-workspace path dependency (so it
    ///   compiles in-repo) while the shipped starter uses a versioned one.
    /// * `tests/system/smoke.rs` — workspace-internal e2e tooling (issue #1192)
    ///   that depends on the path-only `example-e2e` crate. It has no meaning
    ///   outside this monorepo, the same category of divergence as `Cargo.toml`.
    ///
    /// …and `static/css/app.css` is a Tailwind build artefact, not a source file.
    ///
    /// A Ledger profiling harness (`tests/*_profile.rs`, e.g.
    /// `tests/permalink_search_ancestry_batch_profile.rs`) is the same
    /// category as `tests/system/smoke.rs`: workspace-internal measurement
    /// tooling that needs `testcontainers`/`testcontainers-modules` wired into
    /// the in-repo example's `Cargo.toml` (excluded above) but has no meaning
    /// to a scaffolded app, which never gets that wiring.
    fn assert_starter_matches_example(starter: &'static Dir<'static>, project_name: &'static str) {
        let contents = load_from_embedded(starter).unwrap();
        let tmp = tempfile::TempDir::new().unwrap();
        let dest = tmp.path().join(project_name);
        let crate_name = project_name.replace('-', "_");
        let vars = TemplateVars {
            project_name,
            crate_name: &crate_name,
            autumn_version: env!("CARGO_PKG_VERSION"),
            rust_version: option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("1.88.0"),
        };
        scaffold(&contents, &vars, &dest, Flags::default()).unwrap();

        let example_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../examples")
            .join(project_name);

        // Every rendered file matches the committed example. Compare against
        // the emitted name (the starter ships `Cargo.toml.tmpl`, emitted as
        // `Cargo.toml`).
        for file in &contents.files {
            let emitted = emit_rel_path(&file.rel_path);
            if emitted == "Cargo.toml" {
                continue;
            }
            let example_path = example_root.join(emitted);
            let rendered = fs::read(dest.join(emitted)).unwrap();
            let committed = fs::read(&example_path).unwrap_or_else(|_| {
                panic!(
                    "examples/{project_name} is missing {emitted} — regenerate it from the starter"
                )
            });
            assert_eq!(
                rendered, committed,
                "drift between embedded {project_name} starter and examples/{project_name} at {emitted}"
            );
        }

        // …and the example has no stray files the starter does not produce.
        let mut starter_paths: std::collections::BTreeSet<String> = contents
            .files
            .iter()
            .map(|f| emit_rel_path(&f.rel_path).to_owned())
            .collect();
        starter_paths.insert("Cargo.toml".to_owned());
        let mut stack = vec![example_root.clone()];
        while let Some(dir) = stack.pop() {
            for entry in fs::read_dir(&dir).unwrap() {
                let entry = entry.unwrap();
                let path = entry.path();
                let name = entry.file_name();
                if name == "target" || name == ".git" {
                    continue;
                }
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                let rel = path
                    .strip_prefix(&example_root)
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/");
                if rel == "static/css/app.css"
                    || rel == "tests/system/smoke.rs"
                    || (rel.starts_with("tests/") && rel.ends_with("_profile.rs"))
                {
                    continue;
                }
                assert!(
                    starter_paths.contains(&rel),
                    "examples/{project_name} has {rel} which the embedded starter does not produce"
                );
            }
        }
    }

    /// Rendering a starter under a project name that is NOT its own must not
    /// leave the starter's own crate name in a Rust path.
    ///
    /// `assert_starter_matches_example` cannot see this. It renders with the
    /// starter's own name, where `{{crate_name}}` and a hardcoded `cms` produce
    /// identical bytes — so a template variable that was never substituted
    /// compares equal and ships. `autumn new my-blog --starter cms` then
    /// scaffolds a crate named `my_blog` whose `main.rs` says `cms::bootstrap()`,
    /// and it does not compile.
    ///
    /// Rendering under a different name is what separates the two, so that is
    /// what this does: scaffold each built-in as `acme-site` and assert no
    /// emitted Rust source names the starter itself.
    fn assert_no_hardcoded_crate_name(starter: &'static Dir<'static>, starter_name: &str) {
        let contents = load_from_embedded(starter).unwrap();
        let tmp = tempfile::TempDir::new().unwrap();
        let dest = tmp.path().join("acme-site");
        let vars = TemplateVars {
            project_name: "acme-site",
            crate_name: "acme_site",
            autumn_version: env!("CARGO_PKG_VERSION"),
            rust_version: option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("1.88.0"),
        };
        scaffold(&contents, &vars, &dest, Flags::default()).unwrap();

        let needle = format!("{starter_name}::");
        for file in &contents.files {
            let emitted = emit_rel_path(&file.rel_path);
            if std::path::Path::new(emitted).extension() != Some(std::ffi::OsStr::new("rs")) {
                continue;
            }
            let rendered = fs::read_to_string(dest.join(emitted)).unwrap();
            for (line_no, line) in rendered.lines().enumerate() {
                // `crate::<name>::` and `some_<name>::` are ordinary paths; only
                // the crate root spelled as the starter's own name is the bug.
                let Some(at) = line.find(&needle) else {
                    continue;
                };
                let preceded_by_ident = line[..at]
                    .chars()
                    .next_back()
                    .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == ':');
                assert!(
                    preceded_by_ident,
                    "{emitted}:{} names the crate `{starter_name}` after rendering as \
                     `acme-site`; template it as {{{{crate_name}}}}:: or the scaffolded \
                     project will not compile:\n  {line}",
                    line_no + 1
                );
            }
        }
    }

    #[test]
    fn saas_starter_has_no_hardcoded_crate_name() {
        assert_no_hardcoded_crate_name(&builtin::SAAS, "saas");
    }

    #[test]
    fn cms_starter_has_no_hardcoded_crate_name() {
        assert_no_hardcoded_crate_name(&builtin::CMS, "cms");
    }

    /// The embedded `saas` starter must reproduce `examples/saas/` exactly, so
    /// the flagship starter and the drift-gated example cannot diverge.
    #[test]
    fn embedded_saas_matches_example_saas() {
        assert_starter_matches_example(&builtin::SAAS, "saas");
    }

    /// The same contract for the `cms` starter and `examples/cms/`.
    #[test]
    fn embedded_cms_matches_example_cms() {
        assert_starter_matches_example(&builtin::CMS, "cms");
    }
}