gize-generator 0.9.2

Code generation engine for Gize: safe file writing and template rendering.
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
//! End-to-end integration and snapshot tests for the generator.
//!
//! The in-crate unit tests inspect `Plan`s; these go further and exercise the real
//! [`Writer`] against a temporary directory, then pin generated file contents with golden
//! snapshots. Together they cover the MVP Definition of Done item "all of the above is
//! covered by integration + snapshot tests in CI":
//!
//! * generation lands the expected tree on disk,
//! * re-running a generator is idempotent and never destroys hand edits (`--force` off),
//! * `--force` overwrites and `--dry-run` writes nothing,
//! * generated code does not drift from reviewed snapshots (template regression guard).

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use gize_core::{Api, Dialect, ModelSpec};
use gize_generator::{Options, Plan, Report, Writer, scaffold};

/// Fixed, injected timestamp so migration filenames and contents are deterministic.
const TS: &str = "20260101000000";

/// A unique, empty temp directory. Dependency-free (no `tempfile`): scoped by pid, a
/// nanosecond clock and a process-local counter so concurrent tests never collide.
fn unique_tmpdir() -> PathBuf {
    static COUNTER: AtomicUsize = AtomicUsize::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let dir = std::env::temp_dir().join(format!("gize-it-{}-{nanos}-{n}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn apply(root: &Path, plan: &Plan, opts: Options) -> Report {
    Writer::new(opts).apply(root, plan).expect("apply plan")
}

fn product_model() -> ModelSpec {
    ModelSpec::parse(
        "Product",
        &[
            "name:String".to_string(),
            "price:i32".to_string(),
            "active:bool".to_string(),
        ],
    )
    .unwrap()
}

// --------------------------------------------------------------------------------------
// Integration: real file I/O through the Writer
// --------------------------------------------------------------------------------------

#[test]
fn new_project_materializes_expected_tree_on_disk() {
    let root = unique_tmpdir();
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );

    for rel in [
        "Cargo.toml",
        "gize.toml",
        ".env.example",
        ".gitignore",
        "src/main.rs",
        "src/state.rs",
        "src/router.rs",
        "src/config/mod.rs",
        "src/app/mod.rs",
        "src/app/users/mod.rs",
        "src/app/users/model.rs",
        "src/app/users/handler.rs",
    ] {
        assert!(root.join(rel).is_file(), "expected generated file `{rel}`");
    }
    assert!(
        root.join(format!("migrations/{TS}_create_users.sql"))
            .is_file(),
        "expected the users migration"
    );

    // Reserved layout directories (ADR-005) exist even when empty.
    for dir in ["src/database", "src/middleware", "src/shared", "migrations"] {
        assert!(root.join(dir).is_dir(), "expected directory `{dir}`");
    }
}

#[test]
fn regenerating_is_idempotent_and_preserves_hand_edits() {
    let root = unique_tmpdir();
    let plan = scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS);
    apply(&root, &plan, Options::default());

    // Simulate a developer editing a generated file.
    let edited = root.join("src/app/users/service.rs");
    let marker = "// hand-written business logic — must survive re-generation\n";
    let original = fs::read_to_string(&edited).unwrap();
    fs::write(&edited, format!("{marker}{original}")).unwrap();

    // Re-run the same generator without --force.
    let report = apply(&root, &plan, Options::default());
    assert!(report.created.is_empty(), "re-run should create nothing");
    assert!(
        report.overwritten.is_empty(),
        "re-run without --force must overwrite nothing"
    );
    assert!(
        !report.skipped.is_empty(),
        "existing files should be skipped"
    );

    // The hand edit is intact.
    assert!(
        fs::read_to_string(&edited).unwrap().starts_with(marker),
        "the hand edit must survive re-generation"
    );
}

#[test]
fn force_overwrites_and_dry_run_writes_nothing() {
    let root = unique_tmpdir();
    let plan = scaffold::new_project("shop", false, false, false, Dialect::Postgres, None, TS);
    apply(&root, &plan, Options::default());

    let sentinel = root.join("Cargo.toml");
    let generated = fs::read_to_string(&sentinel).unwrap();
    fs::write(&sentinel, "TOUCHED").unwrap();

    // --force + --dry-run reports an overwrite but must not touch the file.
    let report = apply(
        &root,
        &plan,
        Options {
            force: true,
            dry_run: true,
            format: false,
        },
    );
    assert!(
        !report.overwritten.is_empty(),
        "dry-run should still report overwrites"
    );
    assert_eq!(
        fs::read_to_string(&sentinel).unwrap(),
        "TOUCHED",
        "dry-run must not write to disk"
    );

    // --force for real restores the generated content.
    apply(
        &root,
        &plan,
        Options {
            force: true,
            dry_run: false,
            format: false,
        },
    );
    assert_eq!(fs::read_to_string(&sentinel).unwrap(), generated);
}

#[test]
fn api_versioning_nests_routes_and_records_the_prefix() {
    // A versioned project nests the app under `/api/v1` and records it in gize.toml (ADR-016).
    let versioned = unique_tmpdir();
    apply(
        &versioned,
        &scaffold::new_project(
            "shop",
            true,
            false,
            false,
            Dialect::Postgres,
            Some(Api::from_version("1")),
            TS,
        ),
        Options::default(),
    );
    let router = fs::read_to_string(versioned.join("src/router.rs")).unwrap();
    assert!(
        router.contains(".nest(\"/api/v1\", app::routes())"),
        "versioned router should nest under the prefix: {router}"
    );
    let manifest = fs::read_to_string(versioned.join("gize.toml")).unwrap();
    assert!(manifest.contains("[api]"));
    assert!(manifest.contains("version = \"v1\""));

    // An unversioned project is unchanged: it merges at the root and writes no `[api]` table.
    let plain = unique_tmpdir();
    apply(
        &plain,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );
    let router = fs::read_to_string(plain.join("src/router.rs")).unwrap();
    assert!(router.contains(".merge(app::routes())"));
    assert!(!router.contains(".nest("));
    assert!(
        !fs::read_to_string(plain.join("gize.toml"))
            .unwrap()
            .contains("[api]")
    );
}

#[test]
fn mysql_project_uses_binary_uuid_and_no_returning() {
    // MySQL has no RETURNING and no UUID generator, so the repository writes then re-reads by
    // the app-generated id, and the schema uses BINARY(16) / VARCHAR(255) (ADR-015 amendment).
    let root = unique_tmpdir();
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::MySql, None, TS),
        Options::default(),
    );

    let migration =
        fs::read_to_string(root.join(format!("migrations/{TS}_create_users.sql"))).unwrap();
    assert!(migration.contains("id BINARY(16) PRIMARY KEY"));
    assert!(migration.contains("email VARCHAR(255) NOT NULL UNIQUE"));
    assert!(migration.contains("created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP"));

    let repo = fs::read_to_string(root.join("src/app/users/repository.rs")).unwrap();
    assert!(!repo.contains("RETURNING"), "MySQL must not use RETURNING");
    assert!(repo.contains("MySqlPool"));
    // create/update re-read the row via find() after writing.
    assert_eq!(repo.matches("find(pool, id).await").count(), 2);

    let error = fs::read_to_string(root.join("src/app/users/error.rs")).unwrap();
    assert!(error.contains("MySqlDatabaseError"));
    assert!(error.contains("1062 => return Error::Conflict"));

    let state = fs::read_to_string(root.join("src/state.rs")).unwrap();
    assert!(state.contains("MySqlPool"));
    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("\"mysql\""));
    assert!(
        fs::read_to_string(root.join("gize.toml"))
            .unwrap()
            .contains("database = \"mysql\"")
    );
}

#[test]
fn websocket_module_is_scaffolded_and_wired_only_with_ws() {
    // With --ws: the ws module exists, is wired into app/mod.rs, and pulls its extra deps.
    let with = unique_tmpdir();
    apply(
        &with,
        &scaffold::new_project("shop", true, false, true, Dialect::Postgres, None, TS),
        Options::default(),
    );
    for f in ["mod.rs", "message.rs", "handler.rs", "routes.rs"] {
        assert!(
            with.join(format!("src/app/ws/{f}")).is_file(),
            "expected src/app/ws/{f}"
        );
    }
    let app_mod = fs::read_to_string(with.join("src/app/mod.rs")).unwrap();
    assert!(app_mod.contains("mod ws;"));
    assert!(app_mod.contains(".merge(ws::routes())"));
    let routes = fs::read_to_string(with.join("src/app/ws/routes.rs")).unwrap();
    assert!(routes.contains("\"/ws\""));
    let cargo = fs::read_to_string(with.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("axum = { version = \"0.7\", features = [\"ws\"] }"));
    assert!(cargo.contains("serde_json"));
    assert!(
        fs::read_to_string(with.join("gize.toml"))
            .unwrap()
            .contains("websocket = true")
    );

    // Without --ws: no ws module, and Cargo stays lean (plain axum, no serde_json).
    let without = unique_tmpdir();
    apply(
        &without,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );
    assert!(!without.join("src/app/ws").exists());
    assert!(
        !fs::read_to_string(without.join("src/app/mod.rs"))
            .unwrap()
            .contains("ws")
    );
    let cargo = fs::read_to_string(without.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("axum = \"0.7\""));
    assert!(!cargo.contains("serde_json"));
}

#[test]
fn generation_stays_within_a_generous_time_budget() {
    // A coarse, non-flaky *regression gate*, not a micro-benchmark (those live in
    // `benches/generation.rs`). Building plans is pure and fast, so a huge headroom over the
    // real cost lets this catch a catastrophic slowdown (e.g. an accidental O(n²) or a
    // pathological allocation) without ever flaking on a loaded CI runner.
    let model = product_model();
    let start = std::time::Instant::now();
    for _ in 0..1000 {
        let _ = scaffold::new_project("shop", true, true, true, Dialect::Postgres, None, TS);
        let _ = scaffold::make_crud(&model, Dialect::Postgres, TS);
    }
    let elapsed = start.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(30),
        "1000 project+crud plan builds took {elapsed:?} (budget 30s) — likely a perf regression"
    );
}

#[test]
fn make_crud_lands_resource_with_declared_fields() {
    let root = unique_tmpdir();
    apply(
        &root,
        &scaffold::new_project("shop", false, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );
    apply(
        &root,
        &scaffold::make_crud(&product_model(), Dialect::Postgres, TS),
        Options::default(),
    );

    let model_rs = fs::read_to_string(root.join("src/app/products/model.rs")).unwrap();
    assert!(model_rs.contains("pub struct Product"));
    assert!(model_rs.contains("pub price: i32"));
    assert!(model_rs.contains("pub active: bool"));

    let migration =
        fs::read_to_string(root.join(format!("migrations/{TS}_create_products.sql"))).unwrap();
    assert!(migration.contains("CREATE TABLE products"));
    assert!(migration.contains("price INTEGER NOT NULL"));
}

// --------------------------------------------------------------------------------------
// Snapshots: pin generated code so template edits are always reviewed
// --------------------------------------------------------------------------------------

fn snapshots_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots")
}

fn slug(rel: &str) -> String {
    rel.replace(['/', '.', ' '], "_")
}

/// Compare `actual` to the committed golden file `tests/snapshots/{name}.snap`.
///
/// Run `UPDATE_SNAPSHOTS=1 cargo test` after an *intentional* template change to rewrite
/// the snapshots, then review the diff before committing. Missing snapshots are written on
/// first run rather than failing, so bootstrapping is a single test run.
fn assert_snapshot(name: &str, actual: &str) {
    let path = snapshots_dir().join(format!("{name}.snap"));
    if std::env::var_os("UPDATE_SNAPSHOTS").is_some() || !path.exists() {
        fs::create_dir_all(snapshots_dir()).unwrap();
        fs::write(&path, actual).unwrap();
        return;
    }
    let expected = fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {name}.snap: {e}"));
    assert_eq!(
        actual, expected,
        "generated output for `{name}` drifted from its snapshot. \
         If intentional, re-run with UPDATE_SNAPSHOTS=1 and review the diff."
    );
}

fn content<'a>(plan: &'a Plan, rel: &str) -> &'a str {
    plan.ops
        .iter()
        .find(|o| o.path.to_string_lossy() == rel)
        .map(|o| o.contents.as_str())
        .unwrap_or_else(|| panic!("plan has no file `{rel}`"))
}

#[test]
fn project_skeleton_matches_snapshots() {
    // No built-in users here, so the skeleton templates are isolated from the CRUD ones.
    let plan = scaffold::new_project("shop", false, false, false, Dialect::Postgres, None, TS);
    for rel in [
        "Cargo.toml",
        "gize.toml",
        "src/main.rs",
        "src/router.rs",
        "src/state.rs",
        "src/config/mod.rs",
        "src/app/mod.rs",
    ] {
        assert_snapshot(&format!("project__{}", slug(rel)), content(&plan, rel));
    }
}

#[test]
fn crud_slice_matches_snapshots() {
    let plan = scaffold::make_crud(&product_model(), Dialect::Postgres, TS);
    for rel in [
        "src/app/products/mod.rs",
        "src/app/products/model.rs",
        "src/app/products/dto.rs",
        "src/app/products/error.rs",
        "src/app/products/repository.rs",
        "src/app/products/service.rs",
        "src/app/products/handler.rs",
        "src/app/products/routes.rs",
        "src/app/products/tests.rs",
    ] {
        let leaf = Path::new(rel).file_name().unwrap().to_string_lossy();
        assert_snapshot(&format!("crud__{}", slug(&leaf)), content(&plan, rel));
    }
    assert_snapshot(
        "crud__create_products_sql",
        content(&plan, &format!("migrations/{TS}_create_products.sql")),
    );
}

// --------------------------------------------------------------------------------------
// Integration: `gize sync` reconciliation from the manifest (ADR-009)
// --------------------------------------------------------------------------------------

/// The desired code plan for every module in a project's `gize.toml`, mirroring what the
/// `gize sync` command builds (code files only; migrations are handled by the command).
fn desired_code_plan(root: &Path) -> Plan {
    let text = fs::read_to_string(root.join("gize.toml")).expect("read gize.toml");
    let manifest = gize_core::Manifest::from_toml(&text).expect("parse manifest");
    let mut plan = Plan::new();
    for module in &manifest.modules {
        plan = plan
            .extend(scaffold::module_code(module, Dialect::Postgres).expect("plan module code"));
    }
    plan
}

#[test]
fn sync_rebuilds_a_deleted_module_from_the_manifest() {
    let root = unique_tmpdir();
    // A project with the built-in users plus a Product CRUD, both recorded in gize.toml.
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );
    apply(
        &root,
        &scaffold::make_crud(&product_model(), Dialect::Postgres, TS),
        Options::default(),
    );
    // make_crud records the module shape the way the CLI does.
    record_products_in_manifest(&root);

    // Simulate a checkout that has the manifest but lost the module's code.
    fs::remove_dir_all(root.join("src/app/products")).unwrap();
    assert!(!root.join("src/app/products/model.rs").exists());

    // Reconcile from the manifest.
    let plan = desired_code_plan(&root);
    let recon = gize_generator::sync::reconcile(&root, &plan).unwrap();
    // users (9 files) are untouched; products (9 files) are missing.
    assert_eq!(recon.unchanged.len(), 9, "users slice should already match");
    assert_eq!(recon.missing.len(), 9, "products slice should be missing");
    assert!(recon.drift.is_empty(), "nothing should have drifted");

    let applied = gize_generator::sync::apply(&root, &recon, false, false).unwrap();
    assert_eq!(applied.created.len(), 9);
    assert!(root.join("src/app/products/model.rs").is_file());

    // A second reconcile is a no-op: the tree matches the manifest exactly.
    let recon2 = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    assert!(recon2.is_in_sync(), "re-running sync should be idempotent");
    assert_eq!(recon2.unchanged.len(), 18);
}

#[test]
fn sync_reports_drift_and_preserves_hand_edits_without_force() {
    let root = unique_tmpdir();
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );

    // A hand edit to a generated file.
    let edited = root.join("src/app/users/service.rs");
    let original = fs::read_to_string(&edited).unwrap();
    fs::write(&edited, format!("{original}\n// hand edit\n")).unwrap();

    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    assert_eq!(
        recon.drift.len(),
        1,
        "the edited file should be flagged as drift"
    );

    // Without force, drift is left untouched.
    let applied = gize_generator::sync::apply(&root, &recon, false, false).unwrap();
    assert_eq!(applied.left.len(), 1);
    assert!(
        fs::read_to_string(&edited)
            .unwrap()
            .contains("// hand edit")
    );

    // With force, it is overwritten back to the manifest's version.
    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    gize_generator::sync::apply(&root, &recon, true, false).unwrap();
    assert!(
        !fs::read_to_string(&edited)
            .unwrap()
            .contains("// hand edit")
    );
}

/// Regen-safety across a **version upgrade** (WS-RC4 / `MIGRATION.md`): simulates upgrading the
/// `gize` binary and re-running `sync` on a project generated by an older version. After an
/// upgrade a file can differ from the *current* templates for two reasons — the developer
/// hand-edited it, or the generator's output changed between versions (STABILITY.md: the exact
/// generated bytes are not stable). `sync` must treat both the same: report drift and **never
/// overwrite without `--force`**, so upgrading gize never silently destroys code on disk.
#[test]
fn sync_after_a_version_upgrade_preserves_on_disk_code() {
    let root = unique_tmpdir();
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options::default(),
    );

    // (a) a file the developer hand-edited — must survive verbatim.
    let edited = root.join("src/app/users/service.rs");
    let edited_before = format!(
        "{}\n// custom domain logic — must survive the upgrade\n",
        fs::read_to_string(&edited).unwrap()
    );
    fs::write(&edited, &edited_before).unwrap();

    // (b) a file whose bytes an *older* gize emitted differently from the current template.
    let from_old = root.join("src/app/users/handler.rs");
    let old_before = "// emitted by an older gize — intentionally different bytes\n".to_string();
    fs::write(&from_old, &old_before).unwrap();

    // (c) a file that matches the current template — sync is precise, not wholesale.
    let untouched = root.join("src/app/users/model.rs");
    let untouched_before = fs::read_to_string(&untouched).unwrap();

    // Reconcile against what the *upgraded* gize wants.
    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    let drifted: Vec<String> = recon
        .drift
        .iter()
        .map(|op| op.path.display().to_string())
        .collect();
    assert_eq!(recon.drift.len(), 2, "only the two differing files drift");
    assert!(
        drifted.iter().any(|p| p.ends_with("users/service.rs")),
        "the hand edit is drift"
    );
    assert!(
        drifted.iter().any(|p| p.ends_with("users/handler.rs")),
        "the version-delta file is drift"
    );

    // Without --force the upgrade writes over nothing: every drifted file is byte-identical.
    let applied = gize_generator::sync::apply(&root, &recon, false, false).unwrap();
    assert_eq!(applied.left.len(), 2);
    assert!(
        applied.overwritten.is_empty(),
        "nothing overwritten without --force"
    );
    assert_eq!(
        fs::read_to_string(&edited).unwrap(),
        edited_before,
        "hand edit preserved verbatim across the upgrade"
    );
    assert_eq!(
        fs::read_to_string(&from_old).unwrap(),
        old_before,
        "older-version file preserved verbatim (not silently rewritten)"
    );
    assert_eq!(
        fs::read_to_string(&untouched).unwrap(),
        untouched_before,
        "a file already matching the new template is left untouched"
    );

    // --force is the explicit opt-in to adopt the upgraded templates for drifted files.
    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    let forced = gize_generator::sync::apply(&root, &recon, true, false).unwrap();
    assert_eq!(
        forced.overwritten.len(),
        2,
        "--force adopts the new templates"
    );
    assert!(
        !fs::read_to_string(&from_old)
            .unwrap()
            .contains("older gize"),
        "with --force the file is regenerated to the current template"
    );
}

fn rustfmt_available() -> bool {
    std::process::Command::new("rustfmt")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// `gize new`/`make` write rustfmt-formatted code (ADR-020), but `sync`'s desired plan holds the
/// raw templates. Reconciliation must not mistake that pure formatting difference for a hand edit,
/// or every freshly generated project would report drift. Guarded on `rustfmt` (the seam is
/// best-effort).
#[test]
fn sync_ignores_pure_formatting_differences() {
    if !rustfmt_available() {
        return;
    }
    let root = unique_tmpdir();
    // Generate the way the CLI does: format on write.
    apply(
        &root,
        &scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS),
        Options {
            force: false,
            dry_run: false,
            format: true,
        },
    );

    // A freshly generated, untouched project is in sync with its manifest — no spurious drift.
    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    assert!(
        recon.is_in_sync(),
        "a freshly generated project must not report drift; drifted: {:?}",
        recon
            .drift
            .iter()
            .map(|op| op.path.display().to_string())
            .collect::<Vec<_>>()
    );

    // A real hand edit is still detected as drift (not masked by formatting).
    let edited = root.join("src/app/users/service.rs");
    fs::write(
        &edited,
        format!(
            "{}\nfn my_helper() -> i32 {{ 42 }}\n",
            fs::read_to_string(&edited).unwrap()
        ),
    )
    .unwrap();
    let recon = gize_generator::sync::reconcile(&root, &desired_code_plan(&root)).unwrap();
    assert_eq!(recon.drift.len(), 1, "the hand edit must still be drift");
    assert!(recon.drift[0].path.ends_with("users/service.rs"));
}

/// Record the Product module's shape in the project manifest, as `gize make crud` does.
fn record_products_in_manifest(root: &Path) {
    let path = root.join("gize.toml");
    let mut manifest = gize_core::Manifest::from_toml(&fs::read_to_string(&path).unwrap()).unwrap();
    manifest.upsert_module(gize_core::Module {
        name: "products".to_string(),
        fields: product_model().to_field_tokens(),
        belongs_to: Vec::new(),
    });
    fs::write(&path, manifest.to_toml().unwrap()).unwrap();
}

#[test]
fn auth_and_users_slice_match_snapshots() {
    // The security-sensitive generated code (auth module + the users slice that hashes
    // passwords and issues tokens) is pinned so template edits are always reviewed.
    let plan = scaffold::new_project("shop", true, false, false, Dialect::Postgres, None, TS);
    for rel in [
        "src/auth/mod.rs",
        "src/app/users/handler.rs",
        "src/app/users/routes.rs",
        "src/app/users/dto.rs",
        "src/app/users/error.rs",
    ] {
        assert_snapshot(&format!("auth__{}", slug(rel)), content(&plan, rel));
    }
}