arcature 0.1.0

Arcature: an opinionated full-stack Rust web framework. One package, batteries included.
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
//! What each `arc make:<kind>` writes, and where.
//!
//! One function per kind would spread sixteen near-identical decisions across
//! sixteen places, so instead [`plan`] answers all of them: the destination
//! path, the file body, whether a sibling `mod.rs` should learn about the new
//! file, and any follow-up the generator cannot do for the developer.
//!
//! # Scaffolds that compile
//!
//! Every blueprint here produces a file that compiles as written, with one
//! deliberate exception each for `policy` and `listener`. Both macros bind to
//! a type the developer chooses -- the model a policy guards, the event a
//! listener reacts to -- and no generator can guess it. Those two name a
//! placeholder and say so at the top of the file, because a scaffold that
//! silently omits the binding is worse than one that fails to compile until
//! it is pointed somewhere real.

use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use super::name::{ArtifactName, pluralize, to_pascal_case};
use crate::cli::parser::MakeKind;

/// One file a generator is about to write, plus what to do around it.
#[derive(Debug, Clone)]
pub struct Artifact {
    /// Where the file goes, relative to the project root.
    pub path: PathBuf,
    /// The rendered file body.
    pub contents: String,
    /// Whether the sibling `mod.rs` should gain a `pub mod` line. False only
    /// for `tests/`, where each file is its own crate and no `mod.rs` exists.
    pub register_module: bool,
    /// Follow-up the generator deliberately left to the developer.
    pub notes: Vec<String>,
}

/// Decide everything about the file `kind` + `name` produces.
#[must_use]
pub fn plan(kind: MakeKind, name: &ArtifactName) -> Artifact {
    match kind {
        MakeKind::Controller => rust(name, "app/controllers", "Controller", controller),
        MakeKind::Model => rust(name, "app/models", "", model),
        MakeKind::Migration => migration(name),
        MakeKind::Request => rust(name, "app/requests", "Request", request),
        MakeKind::Resource => rust(name, "app/resources", "Resource", resource),
        MakeKind::Policy => policy(name),
        MakeKind::Service => rust(name, "app/services", "Service", service),
        MakeKind::Job => rust(name, "app/jobs", "", job),
        MakeKind::Event => rust(name, "app/events", "", event),
        MakeKind::Listener => listener(name),
        MakeKind::Middleware => rust(name, "app/middleware", "", middleware),
        MakeKind::Command => rust(name, "app/commands", "", command),
        MakeKind::Page => rust(name, "app/pages", "Page", page),
        MakeKind::Test => test(name),
        MakeKind::Factory => rust(name, "database/factories", "Factory", factory),
        MakeKind::Seeder => rust(name, "database/seeders", "Seeder", seeder),
    }
}

/// The shape almost every kind shares: `<root>/<segments>/<stem>.rs`, a
/// `mod.rs` registration, and no follow-up.
fn rust(
    name: &ArtifactName,
    root: &str,
    suffix: &str,
    render: fn(&Rendered) -> String,
) -> Artifact {
    let rendered = Rendered::new(name, suffix);
    Artifact {
        path: destination(root, name, &rendered.stem),
        contents: render(&rendered),
        register_module: true,
        notes: Vec::new(),
    }
}

/// `<root>/<segments...>/<stem>.rs`.
fn destination(root: &str, name: &ArtifactName, stem: &str) -> PathBuf {
    let mut path = PathBuf::from(root);
    for segment in name.segments() {
        path.push(segment);
    }
    path.push(format!("{stem}.rs"));
    path
}

/// The handful of strings a blueprint interpolates, computed once so a
/// template body reads as a template and not as string plumbing.
pub struct Rendered {
    /// The snake_case file stem (no extension).
    pub stem: String,
    /// The PascalCase type name.
    pub type_name: String,
    /// The name as a `/`-joined path, for page contracts and doc lines.
    pub slash_path: String,
    /// The base PascalCase name with the kind suffix removed (`UserPolicy`
    /// -> `User`), which is the model or event a binding points at.
    pub base_type: String,
    /// The base name in snake_case, for a sibling module path.
    pub base_stem: String,
}

impl Rendered {
    fn new(name: &ArtifactName, suffix: &str) -> Self {
        let base_stem = name.file_stem("");
        Self {
            stem: name.file_stem(suffix),
            type_name: name.type_name(suffix),
            slash_path: name.slash_path(),
            base_type: to_pascal_case(&base_stem),
            base_stem,
        }
    }
}

// ---------------------------------------------------------------------------
// The blueprints.
// ---------------------------------------------------------------------------

fn controller(r: &Rendered) -> String {
    let Rendered {
        type_name,
        slash_path,
        ..
    } = r;
    format!(
        "//! The `{type_name}`: HTTP entry points for `{slash_path}`.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// The `{slash_path}` controller.\n\
         pub struct {type_name};\n\
         \n\
         #[controller]\n\
         impl {type_name} {{\n\
         \x20   /// The index action. Register it in `routes/mod.rs`, then\n\
         \x20   /// replace this body with the real response.\n\
         \x20   pub async fn index() -> Result<Response> {{\n\
         \x20       Ok(text(StatusCode::OK, \"{type_name}::index\"))\n\
         \x20   }}\n\
         }}\n"
    )
}

fn model(r: &Rendered) -> String {
    let Rendered {
        type_name,
        base_stem,
        ..
    } = r;
    let table = pluralize(base_stem);
    format!(
        "//! The `{type_name}` model: one row of `{table}`.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// A `{table}` row.\n\
         #[model(table = \"{table}\")]\n\
         pub struct {type_name} {{\n\
         \x20   #[sea_orm(primary_key)]\n\
         \x20   pub id: i64,\n\
         }}\n"
    )
}

fn migration(name: &ArtifactName) -> Artifact {
    let stem = name.file_stem("");
    let module = format!("m{}_{stem}", utc_stamp());
    let mut path = PathBuf::from("database/migrations");
    for segment in name.segments() {
        path.push(segment);
    }
    path.push(format!("{module}.rs"));

    let contents = format!(
        "//! Migration `{stem}`.\n\
         //!\n\
         //! `up` runs on `arc migrate`. `down` has to undo exactly what `up`\n\
         //! did -- a rollback that leaves the schema in a state no migration\n\
         //! describes is worse than no rollback at all.\n\
         \n\
         use arcature::database::sea_orm_migration::prelude::*;\n\
         \n\
         /// The `{stem}` schema change.\n\
         #[derive(DeriveMigrationName)]\n\
         pub struct Migration;\n\
         \n\
         #[async_trait::async_trait]\n\
         impl MigrationTrait for Migration {{\n\
         \x20   async fn up(&self, _manager: &SchemaManager) -> Result<(), DbErr> {{\n\
         \x20       todo!(\"describe the schema change for `{stem}`\")\n\
         \x20   }}\n\
         \n\
         \x20   async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {{\n\
         \x20       todo!(\"undo the schema change for `{stem}`\")\n\
         \x20   }}\n\
         }}\n"
    );

    Artifact {
        path,
        contents,
        register_module: true,
        notes: vec![format!(
            "add `Box::new({module}::Migration)` to `Migrator::migrations()` \
             in database/migrations/mod.rs -- ordering is yours to choose, so \
             the generator does not guess it"
        )],
    }
}

fn request(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}` payload.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// A validated request body. `#[request]` adds `Validate`; the\n\
         /// `Deserialize` derive stays explicit so the extractor can\n\
         /// deserialize and validate in one step.\n\
         #[request]\n\
         #[derive(Debug, Clone, Deserialize)]\n\
         pub struct {type_name} {{\n\
         \x20   #[validate(length(min = 1, max = 255))]\n\
         \x20   pub name: String,\n\
         }}\n"
    )
}

fn resource(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}`: the JSON shape the client sees.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// A browser-safe projection. Convert from the model explicitly\n\
         /// (`impl From<Model> for {type_name}`) so the database schema can\n\
         /// change without breaking the API.\n\
         #[resource]\n\
         pub struct {type_name} {{\n\
         \x20   pub id: String,\n\
         \x20   pub name: String,\n\
         }}\n"
    )
}

fn policy(name: &ArtifactName) -> Artifact {
    let r = Rendered::new(name, "Policy");
    let Rendered {
        type_name,
        base_type,
        base_stem,
        ..
    } = &r;

    let contents = format!(
        "//! The `{type_name}` authorization policy.\n\
         //!\n\
         //! `#[policy(M)]` records *which* model this policy guards; the\n\
         //! `Policy<M>` impl below is the decision itself, and no macro can\n\
         //! guess it. Point the import, the attribute, and `type User` at\n\
         //! real types -- until then this file names `{base_type}` and a user\n\
         //! model that may not exist yet.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         use crate::app::models::{base_stem}::{base_type};\n\
         use crate::app::models::user::User;\n\
         \n\
         /// Authorization decisions for `{base_type}`.\n\
         #[policy({base_type})]\n\
         pub struct {type_name};\n\
         \n\
         impl Policy<{base_type}> for {type_name} {{\n\
         \x20   type User = User;\n\
         \n\
         \x20   fn check(_user: &Self::User, action: &str, _resource: &{base_type}) -> bool {{\n\
         \x20       matches!(action, \"view\")\n\
         \x20   }}\n\
         }}\n"
    );

    Artifact {
        path: destination("app/policies", name, &r.stem),
        contents,
        register_module: true,
        notes: vec![format!(
            "{} names `{base_type}` and `User`; point them at the model this \
             policy guards and the application's user type",
            r.stem
        )],
    }
}

fn service(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}`: business logic over the models.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// `#[service]` builds this per request from the application's\n\
         /// resources. Keep the methods framework-agnostic -- take domain\n\
         /// values, return domain values, and let the controller map the\n\
         /// result to HTTP.\n\
         #[service]\n\
         pub struct {type_name} {{\n\
         \x20   db: Db,\n\
         }}\n\
         \n\
         impl {type_name} {{\n\
         \x20   /// The pool this service was resolved with.\n\
         \x20   pub fn db(&self) -> &Db {{\n\
         \x20       &self.db\n\
         \x20   }}\n\
         }}\n"
    )
}

fn job(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}` background job.\n\
         \n\
         use arcature::Job;\n\
         use arcature::prelude::*;\n\
         \n\
         /// The payload the worker deserializes. Keep it small and\n\
         /// self-contained: a job outlives the request that enqueued it, so\n\
         /// anything it needs has to travel in these fields or be re-read\n\
         /// from the database by the handler.\n\
         #[derive(Debug, Clone, Serialize, Deserialize, Job)]\n\
         pub struct {type_name} {{\n\
         \x20   pub id: i64,\n\
         }}\n\
         \n\
         /// The handler. Register it with `Registry::add` at startup.\n\
         #[job_handler]\n\
         pub async fn handle(_job: {type_name}) -> Result<()> {{\n\
         \x20   Ok(())\n\
         }}\n"
    )
}

fn event(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}` in-process event.\n\
         \n\
         use arcature::Event;\n\
         use arcature::prelude::*;\n\
         \n\
         /// Dispatched through the `Dispatcher`; listeners receive it by\n\
         /// reference, so the fields describe what happened rather than what\n\
         /// should happen next.\n\
         #[derive(Debug, Clone, Event)]\n\
         pub struct {type_name} {{\n\
         \x20   pub id: i64,\n\
         }}\n"
    )
}

fn listener(name: &ArtifactName) -> Artifact {
    let r = Rendered::new(name, "");
    let Rendered {
        stem,
        base_type,
        base_stem,
        ..
    } = &r;
    let event_type = format!("{base_type}Event");

    let contents = format!(
        "//! The `{stem}` listener.\n\
         //!\n\
         //! A listener is meaningless without an event, and the generator\n\
         //! cannot know which one -- `{event_type}` is a placeholder. Point\n\
         //! the import, the `#[listener(..)]` attribute, and the handler\n\
         //! argument at the event this reacts to.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         use crate::app::events::{base_stem}::{event_type};\n\
         \n\
         /// Reacts to `{event_type}`. Register it on the `Dispatcher` at\n\
         /// startup; the attribute only records the binding for inspection.\n\
         #[listener({event_type})]\n\
         pub async fn {stem}(_event: &{event_type}) -> Result<()> {{\n\
         \x20   Ok(())\n\
         }}\n"
    );

    Artifact {
        path: destination("app/listeners", name, stem),
        contents,
        register_module: true,
        notes: vec![format!(
            "{stem} listens for the placeholder `{event_type}`; point it at a \
             real event before building"
        )],
    }
}

fn middleware(r: &Rendered) -> String {
    let Rendered {
        stem, type_name, ..
    } = r;
    format!(
        "//! The `{type_name}` middleware.\n\
         \n\
         use arcature::prelude::*;\n\
         use arcature::routing::Request;\n\
         \n\
         /// `#[middleware]` turns this function into a `pub struct\n\
         /// {type_name}` implementing `Middleware`, so `routes!` can name it\n\
         /// as `middleware: [{type_name}]`. The function stays callable\n\
         /// directly, which is what makes it testable without a router.\n\
         #[middleware]\n\
         pub async fn {stem}(request: Request, next: Next) -> Result<Response> {{\n\
         \x20   Ok(next.run(request).await)\n\
         }}\n"
    )
}

fn command(r: &Rendered) -> String {
    let Rendered {
        stem, slash_path, ..
    } = r;
    let command_name = slash_path.replace('/', ":");
    format!(
        "//! The `{command_name}` application command.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// Invoked by name. The attribute records the binding for\n\
         /// inspection; registration stays explicit in the application's\n\
         /// `CommandRegistry` so nothing runs that was not asked for.\n\
         #[command(\"{command_name}\")]\n\
         pub async fn {stem}() -> Result<()> {{\n\
         \x20   Ok(())\n\
         }}\n"
    )
}

fn page(r: &Rendered) -> String {
    let Rendered {
        type_name,
        slash_path,
        ..
    } = r;
    format!(
        "//! The props for the `{slash_path}` Inertia page.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// Everything the `{slash_path}` component receives. Every field\n\
         /// crosses the Client Exposure Firewall, so a nested type has to be\n\
         /// a `#[resource]` (or another `#[page]`) -- a plain `Serialize`\n\
         /// domain model will not compile here, by design.\n\
         #[page(\"{slash_path}\")]\n\
         pub struct {type_name} {{\n\
         \x20   pub title: String,\n\
         }}\n"
    )
}

fn test(name: &ArtifactName) -> Artifact {
    let stem = name.file_stem("");
    let mut path = PathBuf::from("tests");
    for segment in name.segments() {
        path.push(segment);
    }
    path.push(format!("{stem}.rs"));

    let contents = format!(
        "//! Integration test: {stem}.\n\
         \n\
         #[test]\n\
         fn {stem}_behaves_as_specified() {{\n\
         \x20   // Replace with the behaviour under test. Name the test after\n\
         \x20   // the guarantee it protects, not after the function it calls.\n\
         }}\n"
    );

    Artifact {
        path,
        contents,
        // Each file under `tests/` is its own crate; there is no `mod.rs` to
        // register with, and creating one would break `cargo test`.
        register_module: false,
        notes: Vec::new(),
    }
}

fn factory(r: &Rendered) -> String {
    let Rendered {
        type_name,
        base_type,
        base_stem,
        ..
    } = r;
    format!(
        "//! The `{type_name}`: deterministic `{base_type}` values for tests\n\
         //! and seeders.\n\
         //!\n\
         //! Arcature ships no factory runtime, so a factory is a plain\n\
         //! constructor. The counter keeps generated values unique inside one\n\
         //! test without reaching for a random source, which is what makes a\n\
         //! failure reproducible.\n\
         \n\
         /// Builds `{base_type}` field values.\n\
         #[derive(Debug, Default)]\n\
         pub struct {type_name} {{\n\
         \x20   sequence: u32,\n\
         }}\n\
         \n\
         impl {type_name} {{\n\
         \x20   /// A fresh factory, starting its sequence at zero.\n\
         \x20   pub fn new() -> Self {{\n\
         \x20       Self::default()\n\
         \x20   }}\n\
         \n\
         \x20   /// The next unique `(id, name)` pair.\n\
         \x20   pub fn next(&mut self) -> (u32, String) {{\n\
         \x20       self.sequence += 1;\n\
         \x20       (self.sequence, format!(\"{base_stem}-{{}}\", self.sequence))\n\
         \x20   }}\n\
         }}\n"
    )
}

fn seeder(r: &Rendered) -> String {
    let Rendered { type_name, .. } = r;
    format!(
        "//! The `{type_name}`: rows this seeder owns.\n\
         \n\
         use arcature::prelude::*;\n\
         \n\
         /// Seeds a known starting state. `arc db:seed` reaches this through\n\
         /// the application's own binary, which decides what runs and in what\n\
         /// order -- the CLI never guesses at seeder ordering.\n\
         pub struct {type_name};\n\
         \n\
         impl {type_name} {{\n\
         \x20   /// Insert this seeder's rows.\n\
         \x20   pub async fn run(_db: &Db) -> Result<()> {{\n\
         \x20       Ok(())\n\
         \x20   }}\n\
         }}\n"
    )
}

// ---------------------------------------------------------------------------
// Timestamps.
// ---------------------------------------------------------------------------

/// `YYYYMMDD_HHMMSS` in UTC, the ordering prefix SeaORM migrations use.
///
/// Computed from `SystemTime` by hand rather than through `chrono`: `chrono`
/// arrives with the `database` feature, and `arc make:migration` has to work
/// in a CLI-only build. A clock before the epoch (only reachable on a badly
/// misconfigured machine) falls back to zero rather than panicking -- a
/// wrong-but-ordered filename beats a crashed generator.
fn utc_stamp() -> String {
    let seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let days = i64::try_from(seconds / 86_400).unwrap_or(0);
    let time_of_day = seconds % 86_400;
    let (year, month, day) = civil_from_days(days);
    let (hour, minute, second) = (
        time_of_day / 3_600,
        (time_of_day % 3_600) / 60,
        time_of_day % 60,
    );
    format!("{year:04}{month:02}{day:02}_{hour:02}{minute:02}{second:02}")
}

/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 to a proleptic
/// Gregorian date. Reproduced because it is exact, branch-light, and shorter
/// than the dependency it would otherwise justify.
fn civil_from_days(days: i64) -> (i64, u64, u64) {
    let shifted = days + 719_468;
    let era = if shifted >= 0 {
        shifted
    } else {
        shifted - 146_096
    } / 146_097;
    let day_of_era = (shifted - era * 146_097) as u64; // [0, 146096]
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let year = year_of_era as i64 + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_prime = (5 * day_of_year + 2) / 153; // [0, 11], March-based
    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
    let month = if month_prime < 10 {
        month_prime + 3
    } else {
        month_prime - 9
    };
    (if month <= 2 { year + 1 } else { year }, month, day)
}

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

    fn planned(kind: MakeKind, name: &str) -> Artifact {
        plan(kind, &ArtifactName::parse(name).expect("valid name"))
    }

    #[test]
    fn every_kind_plans_a_rust_file_under_a_known_root() {
        for kind in MakeKind::ALL {
            let artifact = planned(*kind, "widget");
            assert_eq!(
                artifact.path.extension().and_then(|e| e.to_str()),
                Some("rs"),
                "{} did not plan a .rs file",
                kind.as_str()
            );
            assert!(
                !artifact.contents.trim().is_empty(),
                "{} planned an empty file",
                kind.as_str()
            );
            assert!(
                artifact.contents.ends_with('\n'),
                "{} planned a file without a trailing newline",
                kind.as_str()
            );
        }
    }

    #[test]
    fn a_nested_name_nests_the_generated_file() {
        let artifact = planned(MakeKind::Controller, "admin/users");
        assert_eq!(
            artifact.path,
            PathBuf::from("app/controllers/admin/users_controller.rs")
        );
        assert!(artifact.contents.contains("pub struct UsersController;"));
    }

    #[test]
    fn a_model_guesses_a_plural_table_name() {
        let artifact = planned(MakeKind::Model, "Category");
        assert_eq!(artifact.path, PathBuf::from("app/models/category.rs"));
        assert!(
            artifact
                .contents
                .contains("#[model(table = \"categories\")]")
        );
    }

    #[test]
    fn a_page_carries_the_name_the_developer_typed_as_its_contract() {
        let artifact = planned(MakeKind::Page, "users/show");
        assert_eq!(artifact.path, PathBuf::from("app/pages/users/show_page.rs"));
        assert!(artifact.contents.contains("#[page(\"users/show\")]"));
        assert!(artifact.contents.contains("pub struct ShowPage"));
    }

    #[test]
    fn a_command_name_uses_colons_where_the_path_used_slashes() {
        let artifact = planned(MakeKind::Command, "users/prune");
        assert!(artifact.contents.contains("#[command(\"users:prune\")]"));
    }

    #[test]
    fn a_migration_is_timestamped_and_asks_to_be_registered() {
        let artifact = planned(MakeKind::Migration, "create_users_table");
        let file = artifact.path.file_name().and_then(|n| n.to_str()).unwrap();
        assert!(
            file.starts_with('m'),
            "{file} is missing its ordering prefix"
        );
        assert!(file.ends_with("_create_users_table.rs"), "{file}");
        assert_eq!(artifact.notes.len(), 1);
        assert!(artifact.notes[0].contains("Migrator::migrations()"));
    }

    #[test]
    fn a_test_is_not_registered_in_a_module_tree() {
        let artifact = planned(MakeKind::Test, "checkout");
        assert_eq!(artifact.path, PathBuf::from("tests/checkout.rs"));
        assert!(!artifact.register_module);
    }

    #[test]
    fn the_two_blueprints_with_placeholders_say_so() {
        for kind in [MakeKind::Policy, MakeKind::Listener] {
            let artifact = planned(kind, "widget");
            assert!(
                !artifact.notes.is_empty(),
                "{} has a placeholder but no note",
                kind.as_str()
            );
        }
    }

    #[test]
    fn the_civil_calendar_matches_known_dates() {
        assert_eq!(civil_from_days(0), (1970, 1, 1));
        assert_eq!(civil_from_days(-1), (1969, 12, 31));
        // 2000-02-29: the leap day the century rule keeps.
        assert_eq!(civil_from_days(11_016), (2000, 2, 29));
        assert_eq!(civil_from_days(20_454), (2026, 1, 1));
    }

    #[test]
    fn the_migration_stamp_is_fixed_width_and_sortable() {
        let stamp = utc_stamp();
        assert_eq!(stamp.len(), 15, "{stamp}");
        assert_eq!(&stamp[8..9], "_");
        assert!(
            stamp
                .chars()
                .enumerate()
                .all(|(i, c)| i == 8 || c.is_ascii_digit()),
            "{stamp}"
        );
    }
}