nativ 0.3.0

Nativ CLI — compile .nativ DSL to real SwiftUI and Jetpack Compose
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
//! End-to-end CLI tests.
//!
//! Each test spawns the real `nativ` binary (via CARGO_BIN_EXE_nativ) in a
//! temp directory, so command parsing, command dispatch, exit codes, and the
//! scaffolding produced by `nativ init` are all exercised exactly as a user
//! would hit them.

use nativ_config::NativConfig;
use std::io::Write as _;
use std::path::Path;
use std::process::{Command, Output, Stdio};

fn nativ(cwd: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_nativ"))
        .args(args)
        .current_dir(cwd)
        .output()
        .expect("failed to spawn nativ binary")
}

fn nativ_with_stdin(cwd: &Path, args: &[&str], input: &str) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_nativ"))
        .args(args)
        .current_dir(cwd)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn nativ binary");
    child
        .stdin
        .as_mut()
        .expect("stdin pipe")
        .write_all(input.as_bytes())
        .expect("write stdin");
    child.wait_with_output().expect("wait for nativ binary")
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

// ─── init ────────────────────────────────────────────────────────────

/// Lowercase/kebab project names are the common case; init must derive a
/// valid `app <TypeName>:` identifier from them (the scaffold used to write
/// the name verbatim and produce a project that failed to parse).
#[test]
fn init_lowercase_name_scaffolds_parseable_project() {
    let tmp = tempfile::tempdir().unwrap();

    assert!(nativ(tmp.path(), &["init", "my-app"]).status.success());

    let app_nativ = std::fs::read_to_string(tmp.path().join("my-app/src/app.nativ")).unwrap();
    assert!(
        app_nativ.contains("app MyApp:"),
        "app declaration must be PascalCased:\n{app_nativ}"
    );
    assert!(
        app_nativ.contains("name: \"my-app\""),
        "display name must keep the original spelling:\n{app_nativ}"
    );

    let check = nativ(tmp.path(), &["check", "--dir", "my-app"]);
    assert!(
        check.status.success(),
        "scaffolded lowercase project failed check.\nstdout: {}\nstderr: {}",
        stdout(&check),
        stderr(&check)
    );
}

#[test]
fn init_scaffolds_a_complete_project() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["init", "Demo"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("Project created: Demo/"));

    let project = tmp.path().join("Demo");

    // Expected files
    for file in [
        "nativ.toml",
        ".gitignore",
        "src/app.nativ",
        "src/screens/Home.nativ",
        "src/screens/Detail.nativ",
        "src/models/Item.nativ",
        "i18n/en.json",
    ] {
        assert!(project.join(file).is_file(), "missing file: {file}");
    }

    // Expected directories
    for dir in [
        "assets",
        "i18n",
        "src/screens",
        "src/components",
        "src/models",
    ] {
        assert!(project.join(dir).is_dir(), "missing directory: {dir}");
    }

    // The strengthened starter must exercise real capabilities: a typed
    // model list, each-loop, and typed navigation to a detail screen.
    let home = std::fs::read_to_string(project.join("src/screens/Home.nativ")).unwrap();
    assert!(
        home.contains("list of Item"),
        "starter must showcase a typed model list:\n{home}"
    );
    assert!(
        home.contains("go to Detail(item)"),
        "starter must showcase typed navigation:\n{home}"
    );
    let detail = std::fs::read_to_string(project.join("src/screens/Detail.nativ")).unwrap();
    assert!(
        detail.contains("screen Detail(item):"),
        "detail screen must accept a typed param:\n{detail}"
    );

    // The generated nativ.toml must be a valid, loadable config.
    let config = NativConfig::load(&project.join("nativ.toml")).unwrap();
    assert_eq!(config.app.name, "Demo");
    assert_eq!(config.app.bundle_id.as_deref(), Some("com.example.demo"));
    assert!(config.build.ios);
    assert!(config.build.android);

    // The generated sources must parse: `nativ check` must pass.
    let check = nativ(tmp.path(), &["check", "--dir", "Demo"]);
    assert!(
        check.status.success(),
        "generated project failed check.\nstdout: {}\nstderr: {}",
        stdout(&check),
        stderr(&check)
    );
    assert!(stdout(&check).contains("No errors found"));
}

#[test]
fn init_verbose_logs_created_paths() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["--verbose", "init", "Demo"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let out = stdout(&output);
    assert!(out.contains("Creating project: Demo"));
    assert!(out.contains("Dir:"));
}

#[test]
fn init_rejects_names_with_spaces() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["init", "bad name"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("spaces"));
    assert!(!tmp.path().join("bad name").exists());
}

#[test]
fn init_rejects_names_with_invalid_characters() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["init", "bad!name"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("letters, numbers"));
}

#[test]
fn init_refuses_to_overwrite_existing_directory() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir(tmp.path().join("taken")).unwrap();

    let output = nativ(tmp.path(), &["init", "taken"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("already exists"));
}

// ─── build ───────────────────────────────────────────────────────────

#[test]
fn build_compiles_scaffolded_project_for_ios() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(nativ(tmp.path(), &["init", "Demo"]).status.success());

    let output = nativ(
        tmp.path(),
        &["--verbose", "build", "--ios", "--dir", "Demo"],
    );
    assert!(
        output.status.success(),
        "stdout: {}\nstderr: {}",
        stdout(&output),
        stderr(&output)
    );
    let out = stdout(&output);
    assert!(out.contains("Compiling: Demo -> iOS"));
    assert!(out.contains("Build complete"));

    let ios_dir = tmp.path().join("Demo").join("build").join("ios");
    assert!(ios_dir.is_dir(), "build/ios not created");
    let has_swift = walk_files(&ios_dir)
        .iter()
        .any(|p| p.extension().is_some_and(|e| e == "swift"));
    assert!(has_swift, "no .swift files generated under build/ios");
}

#[test]
fn build_quiet_suppresses_progress_output() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(nativ(tmp.path(), &["init", "Demo"]).status.success());

    let output = nativ(tmp.path(), &["--quiet", "build", "--ios", "--dir", "Demo"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(!stdout(&output).contains("Compiling"));
    assert!(!stdout(&output).contains("Build complete"));
}

#[test]
fn build_fails_without_config_file() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["build"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("nativ.toml"));
}

#[test]
fn build_fails_when_all_targets_disabled() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("nativ.toml"),
        "[app]\nname = \"demo\"\n\n[build]\nios = false\nandroid = false\n",
    )
    .unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();

    let output = nativ(tmp.path(), &["build"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("No target platform"));
}

// ─── check ───────────────────────────────────────────────────────────

#[test]
fn check_fails_on_source_with_parse_error() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"demo\"\n").unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    // Tab indentation is always a parse error.
    std::fs::write(
        tmp.path().join("src").join("app.nativ"),
        "screen Bad:\n\ttext \"tabs\"\n",
    )
    .unwrap();

    let output = nativ(tmp.path(), &["check"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("Error"));
}

#[test]
fn check_reports_collected_semantic_errors() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"demo\"\n").unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    // Parses fine, but the IR transform rejects an orphan `on tap:` (#81:
    // it has no preceding element to attach to), so check exits via the
    // "N errors found" path instead of an early abort.
    std::fs::write(
        tmp.path().join("src").join("home.nativ"),
        "screen Home:\n  on tap:\n    go to Home\n",
    )
    .unwrap();

    let output = nativ(tmp.path(), &["check"]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("errors found"),
        "stderr: {}",
        stderr(&output)
    );
}

#[test]
fn check_fails_without_config_file() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["check"]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("nativ.toml"));
}

// ─── version and stub commands ───────────────────────────────────────

#[test]
fn version_prints_crate_version() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["version"]);
    assert!(output.status.success());
    assert!(stdout(&output).contains(&format!("nativ {}", env!("CARGO_PKG_VERSION"))));
}

#[test]
fn version_bump_updates_project_config() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(nativ(tmp.path(), &["init", "Demo"]).status.success());

    let output = nativ(tmp.path(), &["version", "bump", "minor", "--dir", "Demo"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("0.1.0 -> 0.2.0"));

    let config = std::fs::read_to_string(tmp.path().join("Demo/nativ.toml")).unwrap();
    assert!(config.contains("version = \"0.2.0\""));
}

#[test]
fn preview_help_lists_live_device_and_hosted_preview_flags() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["preview", "--help"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let help = stdout(&output);
    assert!(help.contains("--serve"), "help: {help}");
    assert!(help.contains("--port"), "help: {help}");
    assert!(help.contains("--stdin"), "help: {help}");
    assert!(help.contains("--json"), "help: {help}");
}

#[test]
fn dev_help_lists_native_preview_flags() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["dev", "--help"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let help = stdout(&output);
    assert!(help.contains("--ios"), "help: {help}");
    assert!(help.contains("--android"), "help: {help}");
    assert!(help.contains("--dir"), "help: {help}");
}

#[test]
fn build_help_lists_dev_flag() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["build", "--help"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("--dev"));
}

#[test]
fn ci_help_lists_init_command() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["ci", "--help"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("init"));
}

#[test]
fn ci_init_writes_github_actions_workflow() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(nativ(tmp.path(), &["init", "Demo"]).status.success());

    let output = nativ(tmp.path(), &["ci", "init", "--dir", "Demo"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));

    let workflow = tmp.path().join("Demo/.github/workflows/nativ.yml");
    let body = std::fs::read_to_string(&workflow).unwrap();
    assert!(body.contains("nativ check --dir ."));
    assert!(body.contains("nativ build --android --dir ."));
    assert!(body.contains("nativ build --ios --dir ."));
    assert!(body.contains("nativ submit ios --lane beta --dir ."));

    let second = nativ(tmp.path(), &["ci", "init", "--dir", "Demo"]);
    assert!(!second.status.success());
    assert!(stderr(&second).contains("--force"));

    std::fs::write(&workflow, "old workflow").unwrap();
    let forced = nativ(tmp.path(), &["ci", "init", "--dir", "Demo", "--force"]);
    assert!(forced.status.success(), "stderr: {}", stderr(&forced));
    assert!(
        std::fs::read_to_string(&workflow)
            .unwrap()
            .contains("gradle :app:assembleDebug")
    );
}

#[test]
fn submit_dry_run_wraps_existing_fastlane_lane() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(nativ(tmp.path(), &["init", "Demo"]).status.success());
    std::fs::create_dir_all(tmp.path().join("Demo/fastlane")).unwrap();
    std::fs::write(tmp.path().join("Demo/fastlane/Fastfile"), "").unwrap();

    let output = nativ(tmp.path(), &["submit", "ios", "--dir", "Demo", "--dry-run"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("fastlane ios beta"));
}

#[test]
fn preview_renders_a_self_contained_html_file() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("home.nativ"),
        "screen Home:\n  text \"Welcome\", big\n  button \"Start\"\n",
    )
    .unwrap();

    let output = nativ(tmp.path(), &["preview", "home.nativ"]);
    assert!(
        output.status.success(),
        "preview should exit 0.\nstdout: {}\nstderr: {}",
        stdout(&output),
        stderr(&output)
    );

    // The default output sits next to the input as `<stem>.preview.html`.
    let html_path = tmp.path().join("home.preview.html");
    assert!(html_path.exists(), "preview HTML was not written");
    let html = std::fs::read_to_string(&html_path).unwrap();
    assert!(html.starts_with("<!DOCTYPE html>"), "not a full document");
    assert!(html.contains("<style>"), "CSS must be inlined");
    assert!(html.contains("class=\"phone\""), "phone frame missing");
    assert!(html.contains("Home"), "screen name missing");
    assert!(html.contains("Welcome"), "text content missing");
    assert!(html.contains("<button class=\"el btn\""), "button missing");
}

#[test]
fn preview_honors_explicit_out_path() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("home.nativ"),
        "screen Home:\n  text \"Hi\"\n",
    )
    .unwrap();

    let out = tmp.path().join("custom.html");
    let output = nativ(
        tmp.path(),
        &["preview", "home.nativ", "--out", out.to_str().unwrap()],
    );
    assert!(output.status.success(), "preview should exit 0");
    assert!(out.exists(), "preview did not honor --out");
}

#[test]
fn preview_json_reads_source_from_stdin() {
    let tmp = tempfile::tempdir().unwrap();
    let source = r#"app TodoApp:
  name: "My Todos"
  start: Todos

model Todo:
  title: text
  done: boolean = false

component TodoRow(todo):
  row spacing: 12:
    toggle todo.done
    text todo.title

screen Todos:
  state todos = []
  state newTitle = ""
  text "My Todos", big, bold
  textfield "Add a task", bind: newTitle
  button "Add":
    if newTitle != "":
      todos.add(Todo(newTitle))
      newTitle = ""
  each todo in todos:
    TodoRow(todo)

screen TodoDetail(todo):
  text todo.title, big
  button "Done":
    go back
"#;

    let output = nativ_with_stdin(tmp.path(), &["preview", "--stdin", "--json"], source);
    assert!(
        output.status.success(),
        "preview json should exit 0.\nstdout: {}\nstderr: {}",
        stdout(&output),
        stderr(&output)
    );

    let json: serde_json::Value = serde_json::from_str(&stdout(&output)).unwrap();
    let html = json["html"].as_str().expect("html string");
    assert!(html.starts_with("<!DOCTYPE html>"));
    assert!(html.contains("My Todos"));
    assert_eq!(json["source"].as_str(), Some(source));
    assert_eq!(json["screens"].as_u64(), Some(2));
    assert!(json["diagnostics"].as_array().unwrap().is_empty());
    assert_eq!(json["model"]["schemaVersion"].as_u64(), Some(1));
    assert_eq!(json["model"]["app"]["name"].as_str(), Some("My Todos"));
    assert_eq!(json["model"]["app"]["start"].as_str(), Some("Todos"));
    assert_eq!(
        json["model"]["dataModels"][0]["name"].as_str(),
        Some("Todo")
    );
    assert_eq!(
        json["model"]["components"][0]["name"].as_str(),
        Some("TodoRow")
    );
    assert_eq!(json["model"]["screens"][0]["name"].as_str(), Some("Todos"));
    assert_eq!(
        json["model"]["screens"][0]["nodes"][0]["type"].as_str(),
        Some("text")
    );
    assert_eq!(
        json["model"]["screens"][0]["nodes"][2]["type"].as_str(),
        Some("button")
    );
    assert_eq!(
        json["model"]["screens"][0]["nodes"][2]["actions"][0]["type"].as_str(),
        Some("if")
    );
    assert_eq!(
        json["model"]["screens"][0]["nodes"][3]["type"].as_str(),
        Some("each")
    );
    assert!(!tmp.path().join("stdin.preview.html").exists());
}

// ─── format ──────────────────────────────────────────────────────────

/// Creates a minimal project dir containing the given src/ files.
fn project_with_sources(tmp: &Path, files: &[(&str, &str)]) {
    std::fs::create_dir_all(tmp.join("src")).unwrap();
    for (name, content) in files {
        std::fs::write(tmp.join("src").join(name), content).unwrap();
    }
}

#[test]
fn format_rewrites_messy_file_and_is_idempotent() {
    let tmp = tempfile::tempdir().unwrap();
    project_with_sources(
        tmp.path(),
        &[(
            "home.nativ",
            "screen Home:\n  text \"Hi\" ,red   \n\n\n\n  text \"a,b:c\"\n",
        )],
    );

    let output = nativ(tmp.path(), &["format"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(
        stdout(&output).contains("reformatted"),
        "{}",
        stdout(&output)
    );

    let formatted = std::fs::read_to_string(tmp.path().join("src/home.nativ")).unwrap();
    assert_eq!(
        formatted,
        "screen Home:\n  text \"Hi\", red\n\n  text \"a,b:c\"\n"
    );

    // Second run: nothing changes (idempotent).
    let second = nativ(tmp.path(), &["format"]);
    assert!(second.status.success(), "stderr: {}", stderr(&second));
    assert!(
        stdout(&second).contains("unchanged"),
        "second run should report unchanged: {}",
        stdout(&second)
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("src/home.nativ")).unwrap(),
        formatted
    );
}

#[test]
fn format_check_exits_nonzero_without_writing() {
    let tmp = tempfile::tempdir().unwrap();
    let messy = "screen Home:\n  text \"Hi\" ,red\n";
    project_with_sources(tmp.path(), &[("home.nativ", messy)]);

    let check = nativ(tmp.path(), &["format", "--check"]);
    assert!(!check.status.success(), "--check must fail on a messy file");
    assert!(
        stdout(&check).contains("would reformat"),
        "{}",
        stdout(&check)
    );
    // --check must not modify the file.
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("src/home.nativ")).unwrap(),
        messy
    );

    // After a real format run, --check passes.
    assert!(nativ(tmp.path(), &["format"]).status.success());
    let recheck = nativ(tmp.path(), &["format", "--check"]);
    assert!(
        recheck.status.success(),
        "--check should pass after formatting.\nstdout: {}\nstderr: {}",
        stdout(&recheck),
        stderr(&recheck)
    );
}

#[test]
fn format_fails_on_unparseable_file() {
    let tmp = tempfile::tempdir().unwrap();
    // Tab indentation is always rejected by the preprocessor.
    project_with_sources(
        tmp.path(),
        &[("bad.nativ", "screen Bad:\n\ttext \"tabs\"\n")],
    );

    let output = nativ(tmp.path(), &["format"]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("could not be formatted"),
        "stderr: {}",
        stderr(&output)
    );
}

/// Runs the formatter over a TEMP COPY of the whole fixtures/valid corpus
/// (the originals are never touched) and verifies every formatted file
/// still parses and that formatting is a fixed point (`--check` passes).
#[test]
fn format_handles_fixture_corpus_in_temp_copy() {
    let fixtures = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("..")
        .join("fixtures")
        .join("valid");

    let tmp = tempfile::tempdir().unwrap();
    let src_dir = tmp.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();

    let mut copied = 0;
    for entry in std::fs::read_dir(&fixtures).unwrap() {
        let path = entry.unwrap().path();
        if path.extension().is_some_and(|e| e == "nativ") {
            std::fs::copy(&path, src_dir.join(path.file_name().unwrap())).unwrap();
            copied += 1;
        }
    }
    assert!(copied > 0, "no fixtures found at {}", fixtures.display());

    let output = nativ(tmp.path(), &["format"]);
    assert!(
        output.status.success(),
        "format failed on fixture corpus.\nstdout: {}\nstderr: {}",
        stdout(&output),
        stderr(&output)
    );

    // Every formatted fixture must still parse, and a second pass must be
    // a no-op.
    for path in walk_files(&src_dir) {
        let content = std::fs::read_to_string(&path).unwrap();
        nativ_compiler::parse(&content)
            .unwrap_or_else(|e| panic!("{} no longer parses after format: {e}", path.display()));
    }
    let check = nativ(tmp.path(), &["format", "--check"]);
    assert!(
        check.status.success(),
        "format is not idempotent over the fixture corpus.\nstdout: {}",
        stdout(&check)
    );
}

// ─── watch ───────────────────────────────────────────────────────────

/// `watch` validates the project before entering its loop: pointing it at a
/// directory without a nativ.toml must fail fast with a clear error instead
/// of hanging and watching nothing. (The loop itself is exercised via the
/// build-pass tests in src/commands/watch.rs; spawning a long-running
/// watcher in CI would be flaky.)
#[test]
fn watch_fails_cleanly_on_missing_project_dir() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["watch", "--dir", "no-such-dir"]);
    assert!(!output.status.success(), "watch should exit non-zero");
    assert!(
        stderr(&output).contains("nativ.toml"),
        "stderr should point at the missing config: {}",
        stderr(&output)
    );
}

#[test]
fn dev_help_lists_dev_shell_flag() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["dev", "--help"]);
    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("--dev-shell"));
    assert!(stdout(&output).contains("--dev-shell-port"));
    assert!(stdout(&output).contains("--dev-shell-compile"));
}

#[test]
fn unknown_command_fails_with_usage_error() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &["frobnicate"]);
    assert!(!output.status.success());
}

#[test]
fn plain_nativ_without_tty_fails_without_prompting() {
    let tmp = tempfile::tempdir().unwrap();

    let output = nativ(tmp.path(), &[]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("No command selected"));
    assert!(stdout(&output).is_empty(), "stdout: {}", stdout(&output));
}

// ─── helpers ─────────────────────────────────────────────────────────

fn walk_files(dir: &Path) -> Vec<std::path::PathBuf> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(walk_files(&path));
            } else {
                files.push(path);
            }
        }
    }
    files
}

// ─── semantic analysis (check + build) ───────────────────────────────

/// `check` on a project navigating to an undefined screen must exit
/// non-zero and print the semantic error with its file and location.
#[test]
fn check_fails_on_undefined_screen_with_clear_message() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"demo\"\n").unwrap();
    project_with_sources(
        tmp.path(),
        &[(
            "home.nativ",
            "screen Home:\n  button \"Go\":\n    go to Missing\n",
        )],
    );

    let output = nativ(tmp.path(), &["check"]);
    assert!(!output.status.success(), "check must exit non-zero");
    let err = stderr(&output);
    assert!(
        err.contains("Screen 'Missing' is not defined."),
        "stderr must name the undefined screen: {err}"
    );
    assert!(
        err.contains("home.nativ") && err.contains(":2:3:"),
        "stderr must point at file:line:col: {err}"
    );
    assert!(err.contains("1 errors found"), "stderr: {err}");
}

/// Typos within edit distance 1-2 of a declared name get a suggestion.
#[test]
fn check_suggests_closest_screen_name_for_typos() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"demo\"\n").unwrap();
    project_with_sources(
        tmp.path(),
        &[(
            "app.nativ",
            "screen Home:\n  button \"Go\":\n    go to Setings\n\nscreen Settings:\n  text \"s\"\n",
        )],
    );

    let output = nativ(tmp.path(), &["check"]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("Did you mean 'Settings'?"),
        "stderr: {}",
        stderr(&output)
    );
}

/// `build` must refuse to generate code while semantic errors exist.
#[test]
fn build_refuses_to_generate_on_semantic_errors() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"demo\"\n").unwrap();
    project_with_sources(
        tmp.path(),
        &[(
            "home.nativ",
            "screen Home:\n  button \"Go\":\n    go to Missing\n",
        )],
    );

    let output = nativ(tmp.path(), &["build", "--ios"]);
    assert!(!output.status.success(), "build must exit non-zero");
    let err = stderr(&output);
    assert!(
        err.contains("no code was generated"),
        "stderr must say the build was refused: {err}"
    );
    assert!(
        err.contains("Screen 'Missing' is not defined."),
        "stderr must list the semantic error: {err}"
    );
    assert!(
        !tmp.path().join("build").exists(),
        "no output directory may be created"
    );
}