proa-cli 0.2.1

CLI for scaffolding, inspecting, formatting, and validating Proa web projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use proa_assets::{AssetCatalog, AssetManifest, OUTPUT_ENV};
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Output},
};

const PUBLIC_CONFIG: &str = r#"
use proa::config::{BuildConfig, Config, ProjectPaths, Result, ScriptsConfig};

pub async fn config() -> Result<Config<&'static str, String>> {
    let public = proa::config::tokio::fs::read_to_string("asset-root.txt")
        .await
        .map_err(|error| format!("read asset-root.txt: {error}"))?;
    Ok(Config {
        scripts: ScriptsConfig {
            dev: "cargo run",
            build: "cargo build --release",
            ..Default::default()
        },
        paths: ProjectPaths {
            public: Some(public),
            ..Default::default()
        },
        build: BuildConfig {
            assets: Some(vec![]),
            ..Default::default()
        },
        ..Config::default()
    })
}
"#;

fn fixture() -> tempfile::TempDir {
    let temp = tempfile::tempdir().unwrap();
    fs::create_dir(temp.path().join("src")).unwrap();
    fs::create_dir(temp.path().join("public")).unwrap();
    fs::write(temp.path().join("Cargo.toml"), "[package]\nname = \"public_asset_fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n[workspace]\n").unwrap();
    fs::write(temp.path().join("src/main.rs"), r#"
fn main() {
    assert!(option_env!("PROA_PUBLIC_ASSETS").is_none(), "output path leaked into compilation");
    let path = std::env::var_os("PROA_PUBLIC_ASSETS").expect("runtime public output");
    let manifest = std::fs::read_to_string(std::path::PathBuf::from(path).join("manifest.json")).unwrap();
    println!("MAIN|{}|{}", std::env::args().nth(1).unwrap_or_default(), manifest.trim());
}
"#).unwrap();
    fs::write(temp.path().join("proa.config.rs"), PUBLIC_CONFIG).unwrap();
    fs::write(temp.path().join("asset-root.txt"), "public").unwrap();
    fs::write(temp.path().join("public/logo.svg"), b"first").unwrap();
    temp
}

fn cli(root: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_cargo-proa"))
        .current_dir(root)
        .env("CARGO_TARGET_DIR", root.join("custom-target"))
        .env_remove(OUTPUT_ENV)
        .args(args)
        .output()
        .unwrap()
}

fn success(output: &Output) -> String {
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    assert!(
        output.status.success(),
        "{stdout}\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    stdout
}

fn published(stdout: &str) -> PathBuf {
    stdout
        .lines()
        .find_map(|line| {
            line.strip_prefix("published ")?
                .split_once(" public assets to ")
                .map(|(_, path)| path.into())
        })
        .expect("published public catalog")
}

fn main_manifest(stdout: &str) -> AssetManifest {
    assert_eq!(
        stdout
            .lines()
            .filter(|line| line.starts_with("MAIN|"))
            .count(),
        1
    );
    let json = stdout
        .lines()
        .find_map(|line| line.strip_prefix("MAIN|--probe|"))
        .expect("main executed after publication, with its argument");
    serde_json::from_str(json).unwrap()
}

#[test]
fn tests_execute_after_publication_with_runtime_only_assets_and_harness_args() {
    let temp = fixture();
    let root = temp.path();
    fs::remove_file(root.join("proa.config.rs")).unwrap();
    fs::remove_dir_all(root.join("public")).unwrap();
    fs::create_dir(root.join("tests")).unwrap();
    fs::write(
        root.join("build.rs"),
        r#"
fn main() {
    assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_none());
    std::fs::create_dir_all("public").unwrap();
    std::fs::write("public/generated.svg", b"build output").unwrap();
}
"#,
    )
    .unwrap();
    fs::write(
        root.join("tests/page.rs"),
        r#"
#[test]
fn managed_page() {
    assert!(option_env!("PROA_PUBLIC_ASSETS").is_none());
    let output = std::path::PathBuf::from(std::env::var_os("PROA_PUBLIC_ASSETS").unwrap());
    let manifest = std::fs::read_to_string(output.join("manifest.json")).unwrap();
    assert!(manifest.contains("generated.svg"), "{manifest}");
}

#[test]
fn filtered_out() {
    panic!("the CLI must forward the harness filter");
}
"#,
    )
    .unwrap();
    let output = cli(
        root,
        &[
            "test",
            "--test",
            "page",
            "--offline",
            "--",
            "--exact",
            "managed_page",
        ],
    );
    let stdout = success(&output);
    assert!(stdout.contains("test managed_page ... ok"), "{stdout}");
    let published = published(&stdout);
    let catalog = AssetCatalog::load(published).unwrap();
    assert_eq!(
        fs::read(catalog.object_path("generated.svg").unwrap()).unwrap(),
        b"build output"
    );
}

#[test]
fn default_public_directory_can_be_absent_or_disabled() {
    let temp = fixture();
    let root = temp.path();
    fs::remove_file(root.join("proa.config.rs")).unwrap();
    fs::remove_dir_all(root.join("public")).unwrap();
    fs::write(
        root.join("src/main.rs"),
        r#"fn main() { assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_none()); }"#,
    )
    .unwrap();
    let run = success(&cli(root, &["run", "--offline"]));
    assert!(!run.contains(" public assets to "), "{run}");
    assert!(!root.join("public").exists());

    fs::create_dir(root.join("public")).unwrap();
    fs::write(root.join("public/logo.svg"), "logo").unwrap();
    fs::write(
        root.join("proa.config.rs"),
        PUBLIC_CONFIG.replace("public: Some(public)", "public: None"),
    )
    .unwrap();
    let run = success(&cli(root, &["run", "--offline"]));
    assert!(!run.contains(" public assets to "), "{run}");
}

#[cfg(unix)]
struct Watcher(std::process::Child);

#[cfg(unix)]
impl Watcher {
    fn wait_for(&mut self, log: &Path, message: &str, count: usize) -> String {
        use std::time::{Duration, Instant};
        let deadline = Instant::now() + Duration::from_secs(120);
        loop {
            let text = fs::read_to_string(log).unwrap();
            if text.matches(message).count() >= count {
                return text;
            }
            assert!(
                self.0.try_wait().unwrap().is_none() && Instant::now() < deadline,
                "{text}"
            );
            std::thread::sleep(Duration::from_millis(25));
        }
    }
}

#[cfg(unix)]
impl Drop for Watcher {
    fn drop(&mut self) {
        unsafe {
            libc::kill(-(self.0.id() as i32), libc::SIGTERM);
        }
        let _ = self.0.wait();
    }
}

#[cfg(unix)]
#[test]
fn test_watch_tracks_authored_inputs_without_looping_on_preparation_outputs() {
    use std::{os::unix::process::CommandExt, time::Duration};

    let temp = fixture();
    let root = temp.path();
    fs::create_dir(root.join("tests")).unwrap();
    fs::create_dir(root.join("content")).unwrap();
    fs::create_dir(root.join("styles")).unwrap();
    fs::write(root.join("content/example.txt"), "first input").unwrap();
    fs::write(root.join("styles/input.css"), ".test {}\n").unwrap();
    fs::write(
        root.join("styles/build css.sh"),
        "{ cat styles/input.css; printf '/* %s */\\n' \"$(cat content/example.txt)\"; } > public/styles.css\n",
    )
    .unwrap();
    fs::write(
        root.join("tests/page.rs"),
        r#"
#[test]
fn page_inputs() {
    let content = std::fs::read_to_string("content/example.txt").unwrap();
    let public = std::fs::read_to_string("public/logo.svg").unwrap();
    assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_some());
    println!("INPUTS|{content}|{public}");
}
"#,
    )
    .unwrap();
    fs::write(
        root.join("proa.config.rs"),
        PUBLIC_CONFIG
            .replace(
                "scripts: ScriptsConfig {",
                r#"scripts: ScriptsConfig {
            css: "sh 'styles/build css.sh'",
            before: proa::config::ScriptHooks {
                test: vec!["prepare-fixture"],
                ..Default::default()
            },
            named: std::collections::BTreeMap::from([
                ("prepare-public", proa::config::ScriptConfig {
                    command: vec!["sh", "-c", "if [ \"$(cat public/logo.svg)\" = bad ]; then echo HOOK-READ-BAD-FIXTURE; while [ ! -e release-hook ]; do sleep 0.05; done; exit 1; fi; echo fixture > public/prepared.svg"],
                    ..Default::default()
                }),
                ("prepare-fixture", proa::config::ScriptConfig {
                    command: vec!["sh", "-c", "echo fixture > content/generated.txt"],
                    depends_on: vec!["prepare-public"],
                    outputs: vec!["content/generated.txt".to_owned()],
                    ..Default::default()
                })
            ]),
"#,
            )
            .replace("assets: Some(vec![])", "assets: None"),
    )
    .unwrap();
    // Warm the config runner before starting the watcher deadline.
    success(&cli(root, &["config", "show"]));
    let log = root.join("test-watch.log");
    let output = fs::File::create(&log).unwrap();
    let mut watch = Watcher(
        Command::new(env!("CARGO_BIN_EXE_proa"))
            .current_dir(root)
            .env("CARGO_TARGET_DIR", root.join("custom-target"))
            .env_remove(OUTPUT_ENV)
            .args([
                "test",
                "--test",
                "page",
                "--offline",
                "--watch",
                "--watch-path",
                "content",
                "--",
                "--nocapture",
            ])
            .stdout(output.try_clone().unwrap())
            .stderr(output)
            .process_group(0)
            .spawn()
            .unwrap(),
    );
    let waiting = "Watching for test input changes";
    let first = watch.wait_for(&log, waiting, 1);
    assert!(first.contains("INPUTS|first input|first"), "{first}");
    let output = published(&first);
    let first_catalog = AssetCatalog::load(&output).unwrap();
    assert_eq!(
        fs::read(first_catalog.object_path("styles.css").unwrap()).unwrap(),
        b".test {}\n/* first input */\n"
    );
    fs::write(root.join("content/example.txt"), "updated input").unwrap();
    let second = watch.wait_for(&log, waiting, 2);
    assert!(second.contains("INPUTS|updated input|first"), "{second}");
    let second_catalog = AssetCatalog::load(&output).unwrap();
    assert_eq!(
        fs::read(second_catalog.object_path("styles.css").unwrap()).unwrap(),
        b".test {}\n/* updated input */\n"
    );
    let first_css = &first_catalog.manifest().assets["styles.css"];
    let second_css = &second_catalog.manifest().assets["styles.css"];
    // A stylesheet is named after its bytes like any other hashed file.
    assert!(first_css.public_path.starts_with("styles."));
    assert_ne!(second_css.public_path, first_css.public_path);
    assert_ne!(first_css.object, second_css.object);
    fs::write(root.join("public/logo.svg"), "updated logo").unwrap();
    let third = watch.wait_for(&log, waiting, 3);
    assert!(
        third.contains("INPUTS|updated input|updated logo"),
        "{third}"
    );
    fs::write(root.join("public/logo.svg"), "bad").unwrap();
    watch.wait_for(&log, "HOOK-READ-BAD-FIXTURE", 1);
    fs::write(root.join("public/logo.svg"), "fixed logo").unwrap();
    fs::write(root.join("release-hook"), "").unwrap();
    let recovered = watch.wait_for(&log, waiting, 5);
    assert!(
        recovered.contains("test run failed; watching for changes"),
        "{recovered}"
    );
    assert!(
        recovered.contains("INPUTS|updated input|fixed logo"),
        "{recovered}"
    );
    std::thread::sleep(Duration::from_millis(650));
    let text = fs::read_to_string(&log).unwrap();
    assert_eq!(text.matches("Task prepare-public").count(), 5, "{text}");
    assert_eq!(
        text.matches("building asset: public/styles.css").count(),
        4,
        "{text}"
    );
}

#[cfg(unix)]
#[test]
fn watcher_recovers_output_and_rechecks_only_config_compile_inputs_on_asset_edits() {
    use std::{
        net::TcpListener,
        os::unix::{fs::PermissionsExt, process::CommandExt},
        time::Duration,
    };
    let temp = fixture();
    let root = temp.path();
    let artifacts = tempfile::tempdir().unwrap();
    let target = artifacts.path().join("cargo target");
    let cargo_trace = artifacts.path().join("config-cargo.log");
    let cargo = artifacts.path().join("cargo-trace");
    fs::write(
        &cargo,
        r#"#!/bin/sh
case "$1:$*" in build:*proa-config/*) echo build >> "$CONFIG_CARGO_LOG";; esac
exec "$REAL_CARGO" "$@"
"#,
    )
    .unwrap();
    fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).unwrap();
    fs::write(
        root.join("src/main.rs"),
        r#"
fn main() {
    let port = std::env::var("PORT").unwrap();
    let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
    for stream in listener.incoming() { drop(stream.unwrap()); }
}
"#,
    )
    .unwrap();
    fs::write(root.join("public/icon.svg"), "one").unwrap();
    fs::write(root.join("extra-input.txt"), "one").unwrap();
    fs::create_dir(root.join("scripts")).unwrap();
    for name in ["a", "b"] {
        fs::write(
            root.join(format!("scripts/{name}.sh")),
            format!("echo WRAPPER-{name}\nexit 33\n"),
        )
        .unwrap();
    }
    let config = PUBLIC_CONFIG.replace("cargo run", "bash scripts/a.sh").replace("    Ok(Config {", r#"    eprintln!("CONFIG {} {}", include_str!("public/icon.svg"), std::fs::read_to_string("public/logo.svg")?);
    Ok(Config {"#);
    fs::write(root.join("proa.config.rs"), &config).unwrap();
    let log = artifacts.path().join("dev.log");
    let output = fs::File::create(&log).unwrap();
    let port = TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port();
    let mut watch = Watcher(
        Command::new(env!("CARGO_BIN_EXE_proa"))
            .current_dir(root)
            .env("CARGO_TARGET_DIR", &target)
            .env("CARGO", cargo)
            .env("REAL_CARGO", env!("CARGO"))
            .env("CONFIG_CARGO_LOG", &cargo_trace)
            .args([
                "dev",
                "--offline",
                "--no-reload",
                "--watch",
                "extra-input.txt",
                "--port",
                &port.to_string(),
            ])
            .stdout(output.try_clone().unwrap())
            .stderr(output)
            .process_group(0)
            .spawn()
            .unwrap(),
    );
    let mut wait = |message, count| watch.wait_for(&log, message, count);
    let cargo_calls = || fs::read_to_string(&cargo_trace).unwrap().lines().count();
    let ready = "Proa dev ready:";
    let build_started = "running linked RSJS Cargo dev build";
    let first = wait(ready, 1);
    let output = published(&first);
    let builds = cargo_calls();
    assert_eq!(builds, 1, "{first}");
    let original = fs::read(output.join("manifest.json")).unwrap();
    fs::remove_file(output.join("manifest.json")).unwrap();
    let repaired = wait(ready, 2);
    fs::rename(&output, artifacts.path().join("moved-catalog")).unwrap();
    let recreated = wait(ready, 3);
    for text in [&repaired, &recreated] {
        assert_eq!(text.matches(build_started).count(), 1, "{text}");
    }
    assert_eq!(fs::read(output.join("manifest.json")).unwrap(), original);
    assert_eq!(cargo_calls(), builds);

    fs::write(root.join("public/logo.svg"), "two").unwrap();
    let republish = "republished catalog without Cargo";
    let logo = wait(ready, 4);
    assert!(logo.contains("CONFIG one two"));
    assert_eq!(logo.matches(republish).count(), 1, "{logo}");
    assert_eq!(logo.matches(build_started).count(), 1, "{logo}");
    assert_ne!(fs::read(output.join("manifest.json")).unwrap(), original);
    assert_eq!(
        cargo_calls(),
        builds,
        "runtime read should reuse the config executable"
    );
    fs::write(root.join("public/icon.svg"), "new-icon").unwrap();
    let icon = wait(ready, 5);
    assert!(icon.contains("CONFIG new-icon two"));
    assert_eq!(icon.matches(republish).count(), 2, "{icon}");
    assert_eq!(icon.matches(build_started).count(), 1, "{icon}");
    assert_eq!(
        cargo_calls(),
        builds + 1,
        "include_str! is a compiler input"
    );
    fs::write(
        root.join("proa.config.rs"),
        config.replace("scripts/a.sh", "scripts/b.sh"),
    )
    .unwrap();
    let changed = wait(ready, 6);
    assert!(changed.contains("use `proa run dev`"));
    assert!(!changed.contains("WRAPPER-"));

    fs::rename(&target, artifacts.path().join("moved-target")).unwrap();
    let rebuilt = wait(ready, 7);
    assert!(output.join("manifest.json").is_file());
    assert_eq!(rebuilt.matches("use `proa run dev`").count(), 1);
    assert_eq!(rebuilt.matches(build_started).count(), 3, "{rebuilt}");

    let source = root.join("src/main.rs");
    let valid_source = fs::read(&source).unwrap();
    let config_builds = cargo_calls();
    fs::write(
        &source,
        b"compile_error!(\"broken while output is missing\");",
    )
    .unwrap();
    let failed = "linked dev rebuild failed";
    let broken = wait(failed, 1);
    assert!(
        broken.contains("broken while output is missing"),
        "{broken}"
    );
    assert_eq!(
        cargo_calls(),
        config_builds,
        "an application edit outside the config inputs should reuse the config executable"
    );
    fs::remove_file(output.join("manifest.json")).unwrap();

    // Watch past the missing-catalog retry interval while the files are idle.
    std::thread::sleep(Duration::from_secs(3));
    let idle = fs::read_to_string(&log).unwrap();
    assert_eq!(idle.matches(build_started).count(), 4, "{idle}");
    assert_eq!(idle.matches(failed).count(), 1, "{idle}");
    assert!(!output.join("manifest.json").exists(), "{idle}");

    fs::write(&source, &valid_source).unwrap();
    let recovered = wait(ready, 8);
    assert_eq!(recovered.matches(build_started).count(), 5, "{recovered}");
    assert!(output.join("manifest.json").is_file(), "{recovered}");

    fs::write(root.join("extra-input.txt"), "two").unwrap();
    let watched = wait(ready, 9);
    assert_eq!(watched.matches(build_started).count(), 6, "{watched}");

    // A public file the application compiles in is a Cargo input: editing it
    // must take the linked rebuild, not the catalog-only restart.
    let mut compiled = b"const _: &str = include_str!(\"../public/logo.svg\");\n".to_vec();
    compiled.extend(fs::read(&source).unwrap());
    fs::write(&source, compiled).unwrap();
    wait(ready, 10);
    fs::write(root.join("public/logo.svg"), "three").unwrap();
    let included = wait(ready, 11);
    assert_eq!(included.matches(build_started).count(), 8, "{included}");
    assert_eq!(included.matches(republish).count(), 2, "{included}");

    // A build script that declares its inputs keeps the catalog-only restart.
    // One that declares none reruns on any package change, so it cannot.
    fs::write(&source, &valid_source).unwrap();
    fs::write(
        root.join("build.rs"),
        "fn main() { println!(\"cargo:rerun-if-changed=build.rs\"); }\n",
    )
    .unwrap();
    wait(ready, 12);
    fs::write(root.join("public/logo.svg"), "four").unwrap();
    let declared = wait(ready, 13);
    assert_eq!(declared.matches(build_started).count(), 9, "{declared}");
    assert_eq!(declared.matches(republish).count(), 3, "{declared}");
    fs::write(root.join("build.rs"), "fn main() {}\n").unwrap();
    wait(ready, 14);
    fs::write(root.join("public/logo.svg"), "five").unwrap();
    let undeclared = wait(ready, 15);
    assert_eq!(
        undeclared.matches(build_started).count(),
        11,
        "{undeclared}"
    );
    assert_eq!(undeclared.matches(republish).count(), 3, "{undeclared}");
}

#[cfg(unix)]
#[test]
fn dev_restarts_a_server_that_cannot_follow_the_catalog_and_spares_one_that_can() {
    use std::{net::TcpListener, os::unix::process::CommandExt};

    let temp = fixture();
    let root = temp.path();
    let artifacts = tempfile::tempdir().unwrap();
    // The server registers as a live reader only when `follow` exists, which
    // stands in for `PublicAssets::load_live` without a framework dependency.
    fs::write(
        root.join("src/main.rs"),
        r#"
fn main() {
    let port = std::env::var("PORT").unwrap();
    let output = std::path::PathBuf::from(std::env::var_os("PROA_PUBLIC_ASSETS").unwrap());
    let _following = std::path::Path::new("follow").exists().then(|| {
        let lock = std::fs::File::open(output.join(".live-readers.lock")).unwrap();
        lock.lock_shared().unwrap();
        lock
    });
    eprintln!("SERVER-START");
    let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
    for stream in listener.incoming() { drop(stream.unwrap()); }
}
"#,
    )
    .unwrap();
    fs::write(
        root.join("proa.config.rs"),
        PUBLIC_CONFIG.replace("\"cargo run\"", "\"proa dev\""),
    )
    .unwrap();
    let log = artifacts.path().join("dev.log");
    let output = fs::File::create(&log).unwrap();
    let port = TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port();
    let mut watch = Watcher(
        Command::new(env!("CARGO_BIN_EXE_proa"))
            .current_dir(root)
            .env("CARGO_TARGET_DIR", artifacts.path().join("target"))
            // The port comes from the environment here, the way a process
            // manager supplies it, instead of from `--port`.
            .env("PORT", port.to_string())
            .env("HOST", "arm64-apple-darwin20.0.0")
            .env_remove("PROA_HOST")
            .args(["dev", "--offline", "--no-reload"])
            .stdout(output.try_clone().unwrap())
            .stderr(output)
            .process_group(0)
            .spawn()
            .unwrap(),
    );
    let ready = "Proa dev ready:";
    let restarted = "republished catalog without Cargo";
    let in_place = "republished catalog in place without restarting";
    let starts = |text: &str| text.matches("SERVER-START").count();

    let first = watch.wait_for(&log, ready, 1);
    assert!(
        first.contains(&format!("Proa dev ready: http://127.0.0.1:{port}")),
        "{first}"
    );
    let published = published(&first);
    let before = fs::read(published.join("manifest.json")).unwrap();

    // The running server holds a fixed catalog: only a restart shows the edit.
    fs::write(root.join("follow"), "").unwrap();
    fs::write(root.join("public/logo.svg"), "second").unwrap();
    let after_restart = watch.wait_for(&log, ready, 2);
    assert_eq!(
        after_restart.matches(restarted).count(),
        1,
        "{after_restart}"
    );
    assert_eq!(
        after_restart.matches(in_place).count(),
        0,
        "{after_restart}"
    );
    assert_eq!(starts(&after_restart), 2, "{after_restart}");
    let second = fs::read(published.join("manifest.json")).unwrap();
    assert_ne!(second, before);

    // Its replacement follows the catalog, so the next edit publishes under
    // the same process.
    fs::write(root.join("public/logo.svg"), "third").unwrap();
    let after_swap = watch.wait_for(&log, in_place, 1);
    assert_ne!(fs::read(published.join("manifest.json")).unwrap(), second);
    fs::write(root.join("public/extra.png"), "png").unwrap();
    let after_second_swap = watch.wait_for(&log, in_place, 2);
    for text in [&after_swap, &after_second_swap] {
        assert_eq!(text.matches(restarted).count(), 1, "{text}");
        assert_eq!(text.matches(ready).count(), 2, "{text}");
        assert_eq!(starts(text), 2, "{text}");
    }
    assert_eq!(
        after_second_swap
            .matches("running linked RSJS Cargo dev build")
            .count(),
        1,
        "{after_second_swap}"
    );
}

#[cfg(unix)]
#[test]
fn run_dispatches_configured_scripts_and_builtins_bypass_them() {
    let temp = fixture();
    let root = temp.path();
    fs::create_dir(root.join("scripts")).unwrap();
    fs::write(
        root.join("proa.config.rs"),
        PUBLIC_CONFIG
            .replace("cargo run", "bash scripts/dev.sh")
            .replace("cargo build --release", "bash scripts/build.sh"),
    )
    .unwrap();
    for phase in ["dev", "build"] {
        fs::write(
            root.join(format!("scripts/{phase}.sh")),
            format!("echo SCRIPT:{phase}\nexec \"$PROA_SCRIPT_EXECUTABLE\" {phase} \"$@\"\n"),
        )
        .unwrap();
    }
    let cli = |arguments: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_cargo-proa"))
            .current_dir(root.parent().unwrap())
            .env("CARGO_TARGET_DIR", root.join("custom-target"))
            .env_remove(OUTPUT_ENV)
            .args(arguments)
            .output()
            .unwrap()
    };
    let relative_root = root.file_name().unwrap().to_str().unwrap();
    let direct = cli(&["dev", "--root", relative_root, "--no-restart", "--offline"]);
    assert!(!success(&direct).contains("SCRIPT:dev"));
    assert!(String::from_utf8_lossy(&direct.stderr).contains("use `proa run dev`"));

    let dev = success(&cli(&[
        "run",
        "--root",
        relative_root,
        "dev",
        "--no-restart",
        "--offline",
    ]));
    assert_eq!(dev.matches("SCRIPT:dev").count(), 1, "{dev}");
    assert!(dev.contains("MAIN||"), "{dev}");
    assert!(published(&dev).join("manifest.json").is_file());

    let artifact = "custom-target/exported shop";
    let build = success(&cli(&[
        "run",
        &format!("--root={relative_root}"),
        "build",
        "--profile",
        "dev",
        "--no-check",
        "--offline",
        "--artifact-out",
        artifact,
    ]));
    assert_eq!(build.matches("SCRIPT:build").count(), 1, "{build}");
    assert!(root.join(artifact).is_file());

    let direct = cli(&[
        "build",
        "--root",
        relative_root,
        "--profile",
        "dev",
        "--no-check",
        "--offline",
    ]);
    assert!(!success(&direct).contains("SCRIPT:build"));
    assert!(String::from_utf8_lossy(&direct.stderr).contains("use `proa run build`"));
}

#[test]
fn rsjs_minification_follows_the_config_across_reused_builds() {
    let temp = fixture();
    let root = temp.path();
    fs::write(
        root.join("src/main.rs"),
        r#"
fn main() {
    assert!(std::env::var_os("PROA_RSJS_MINIFY").is_none());
    println!("{}", env!("PROA_RSJS_MINIFY"));
}
"#,
    )
    .unwrap();
    let export = root
        .join("custom-target")
        .join(format!("probe{}", std::env::consts::EXE_SUFFIX));
    let build = || {
        success(&cli(
            root,
            &[
                "build",
                "--profile",
                "dev",
                "--offline",
                "--no-check",
                "--artifact-out",
                export.to_str().unwrap(),
            ],
        ))
    };
    let run = || {
        success(
            &Command::new(&export)
                .env_remove("PROA_RSJS_MINIFY")
                .output()
                .unwrap(),
        )
    };

    fs::remove_file(root.join("proa.config.rs")).unwrap();
    build();
    assert_eq!(run().trim(), "1");
    let warm = build();
    assert!(
        warm.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
        "{warm}"
    );
    assert_eq!(run().trim(), "1");

    fs::write(
        root.join("proa.config.rs"),
        r#"
use proa::config::{BuildConfig, Config, Result, ScriptsConfig};

pub async fn config() -> Result<Config> {
    Ok(Config {
        scripts: ScriptsConfig {
            dev: "cargo run",
            build: "cargo build --release",
            ..Default::default()
        },
        build: BuildConfig {
            minify_rsjs: false,
            ..Default::default()
        },
        ..Config::default()
    })
}
"#,
    )
    .unwrap();
    build();
    assert_eq!(run().trim(), "0");
}

#[test]
fn build_then_run_refreshes_assets_without_rebinding_the_binary_and_keeps_failures_local() {
    let temp = fixture();
    let root = temp.path();
    let built = success(&cli(
        root,
        &["build", "--profile", "dev", "--offline", "--no-check"],
    ));
    assert!(!built.contains("MAIN|"));
    let output = published(&built);
    assert!(output.starts_with(fs::canonicalize(root.join("custom-target/proa-output")).unwrap()));
    let old = AssetCatalog::load(&output).unwrap();
    let old_object = old.object_path("logo.svg").unwrap();

    let run = success(&cli(root, &["run", "--offline", "--", "--probe"]));
    assert_eq!(published(&run), output);
    assert_eq!(&main_manifest(&run), old.manifest());
    assert!(
        run.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
        "{run}"
    );

    fs::write(root.join("public/logo.svg"), b"other").unwrap();
    let edited = success(&cli(root, &["run", "--offline", "--", "--probe"]));
    let current = main_manifest(&edited);
    assert_eq!(published(&edited), output);
    assert_ne!(
        current.assets["logo.svg"].public_path,
        old.manifest().assets["logo.svg"].public_path
    );
    assert!(
        edited.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
        "{edited}"
    );
    assert_eq!(fs::read(&old_object).unwrap(), b"first");
    let loaded = AssetCatalog::load(&output).unwrap();
    assert_eq!(
        fs::read(loaded.object_path("logo.svg").unwrap()).unwrap(),
        b"other"
    );
    drop(old);
    drop(loaded);
    success(&cli(
        root,
        &["build", "--profile", "dev", "--offline", "--no-check"],
    ));
    assert!(!old_object.exists());

    let pointer = fs::read(output.join("manifest.json")).unwrap();
    fs::write(root.join("proa.config.rs"), "invalid Rust config").unwrap();
    let invalid_config = cli(root, &["run", "--offline", "--", "--probe"]);
    assert!(!invalid_config.status.success());
    assert!(String::from_utf8_lossy(&invalid_config.stderr).contains("proa.config.rs"));
    assert!(!String::from_utf8_lossy(&invalid_config.stdout).contains("MAIN|"));
    assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
    fs::write(root.join("proa.config.rs"), PUBLIC_CONFIG).unwrap();
    fs::remove_file(root.join("asset-root.txt")).unwrap();
    let config_error = cli(root, &["run", "--offline", "--", "--probe"]);
    assert!(!config_error.status.success());
    assert!(String::from_utf8_lossy(&config_error.stderr).contains("read asset-root.txt"));
    assert!(!String::from_utf8_lossy(&config_error.stdout).contains("MAIN|"));
    assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
    fs::write(root.join("asset-root.txt"), "public").unwrap();
    fs::write(root.join("public/logo.svg"), b"third").unwrap();
    fs::write(root.join("src/main.rs"), "this is invalid Rust").unwrap();
    let broken = cli(root, &["run", "--offline", "--", "--probe"]);
    assert!(!broken.status.success());
    assert!(!String::from_utf8_lossy(&broken.stdout).contains("MAIN|"));
    assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
    fs::write(
        root.join("src/main.rs"),
        "fn main() { panic!(\"must not launch\"); }",
    )
    .unwrap();
    fs::write(root.join("asset-root.txt"), "missing-custom").unwrap();
    let missing = cli(root, &["run", "--offline"]);
    assert!(!missing.status.success());
    assert!(
        String::from_utf8_lossy(&missing.stderr).contains("publish configured public directory")
    );
    assert!(!String::from_utf8_lossy(&missing.stderr).contains("must not launch"));
    assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
}

#[test]
fn public_files_used_by_rust_or_build_scripts_remain_compiler_inputs() {
    let temp = fixture();
    let root = temp.path();
    fs::write(root.join("public/build-input.txt"), "build-first").unwrap();
    fs::write(
        root.join("build.rs"),
        r#"
fn main() {
    println!("cargo:rerun-if-changed=public/build-input.txt");
    let value = std::fs::read_to_string("public/build-input.txt").unwrap();
    println!("cargo:rustc-env=PUBLIC_BUILD_INPUT={value}");
}
"#,
    )
    .unwrap();
    fs::write(
        root.join("src/main.rs"),
        r#"
fn main() {
    println!("COMPILED|{}|{}", include_str!("../public/logo.svg"), env!("PUBLIC_BUILD_INPUT"));
}
"#,
    )
    .unwrap();
    let run = success(&cli(root, &["run", "--offline"]));
    assert!(run.lines().any(|line| line == "COMPILED|first|build-first"));
    let output = published(&run);

    fs::write(root.join("public/logo.svg"), "included-second").unwrap();
    let included = success(&cli(root, &["run", "--offline"]));
    assert!(included
        .lines()
        .any(|line| line == "COMPILED|included-second|build-first"));
    assert_eq!(published(&included), output);

    fs::write(root.join("public/build-input.txt"), "build-second").unwrap();
    let generated = success(&cli(root, &["run", "--offline"]));
    assert!(generated
        .lines()
        .any(|line| line == "COMPILED|included-second|build-second"));
    assert_eq!(published(&generated), output);
    let catalog = AssetCatalog::load(output).unwrap();
    assert_eq!(
        fs::read(catalog.object_path("logo.svg").unwrap()).unwrap(),
        b"included-second"
    );
    assert_eq!(
        fs::read(catalog.object_path("build-input.txt").unwrap()).unwrap(),
        b"build-second"
    );
}

#[test]
fn dev_finalizes_before_launch_and_no_assets_skips_publication() {
    let temp = fixture();
    let root = temp.path();
    let skipped = success(&cli(
        root,
        &[
            "build",
            "--profile",
            "dev",
            "--offline",
            "--no-check",
            "--no-assets",
        ],
    ));
    assert!(!skipped.contains("published "));
    assert!(!root.join("custom-target/proa-output").exists());
    let dev = success(&cli(
        root,
        &[
            "dev",
            "--no-restart",
            "--",
            "cargo",
            "run",
            "--offline",
            "--",
            "--probe",
        ],
    ));
    let manifest = main_manifest(&dev);
    let catalog = AssetCatalog::load(published(&dev)).unwrap();
    assert_eq!(&manifest, catalog.manifest());
    assert!(dev.contains("final cache: 1/1 reused"), "{dev}");
}

#[cfg(unix)]
#[test]
fn config_runner_persists_stamp_cache_across_cli_invocations() {
    use std::os::unix::fs::PermissionsExt;

    let temp = fixture();
    let root = temp.path();
    fs::write(
        root.join("proa.config.rs"),
        r#"
use proa::config::{BuildConfig, Config, ProjectPaths, Result, ScriptsConfig};

pub async fn config() -> Result<Config<&'static str, String>> {
    let public = proa::config::tokio::fs::read_to_string("asset-root.txt")
        .await
        .map_err(|error| format!("read asset-root.txt: {error}"))?;
    Ok(Config {
        scripts: ScriptsConfig {
            dev: option_env!("PROA_TEST_DEV_CMD").unwrap_or("cargo run"),
            build: "cargo build --release",
            ..Default::default()
        },
        paths: ProjectPaths {
            public: Some(public),
            ..Default::default()
        },
        build: BuildConfig {
            assets: Some(vec![]),
            ..Default::default()
        },
        ..Config::default()
    })
}
"#,
    )
    .unwrap();
    let artifacts = tempfile::tempdir().unwrap();
    let target = artifacts.path().join("cargo-target");
    let cargo_trace = artifacts.path().join("config-cargo.log");
    let cargo = artifacts.path().join("cargo-trace");
    fs::write(
        &cargo,
        r#"#!/bin/sh
case "$1:$*" in build:*proa-config/*) echo build >> "$CONFIG_CARGO_LOG";; esac
exec "$REAL_CARGO" "$@"
"#,
    )
    .unwrap();
    fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).unwrap();

    let profile = std::cell::Cell::new(None::<&str>);
    let quiet = std::cell::Cell::new(false);
    let run_validate = |compile_env: Option<&str>| {
        let mut command = Command::new(env!("CARGO_BIN_EXE_proa"));
        if let Some(value) = profile.get() {
            command.env("CARGO_PROFILE_DEV_DEBUG_ASSERTIONS", value);
        }
        if quiet.get() {
            command.env("CARGO_TERM_QUIET", "true");
        } else {
            command.env_remove("CARGO_TERM_QUIET");
        }
        command
            .current_dir(root)
            .env("CARGO_TARGET_DIR", &target)
            .env("CARGO", &cargo)
            .env("REAL_CARGO", env!("CARGO"))
            .env("CARGO_NET_OFFLINE", "true")
            .env("CONFIG_CARGO_LOG", &cargo_trace)
            .args(["config", "validate"]);
        match compile_env {
            Some(value) => {
                command.env("PROA_TEST_DEV_CMD", value);
            }
            None => {
                command.env_remove("PROA_TEST_DEV_CMD");
            }
        }
        command.output().unwrap()
    };

    let first = run_validate(Some("cargo run --bin secret-alpha"));
    assert!(
        first.status.success(),
        "{}",
        String::from_utf8_lossy(&first.stderr)
    );
    assert!(
        String::from_utf8_lossy(&first.stderr).contains("compiling proa.config.rs..."),
        "{}",
        String::from_utf8_lossy(&first.stderr)
    );
    assert_eq!(fs::read_to_string(&cargo_trace).unwrap().lines().count(), 1);

    // Persisted stamp-cache.json must never store compile-time env values in plaintext.
    let cache_files: Vec<_> = fs::read_dir(target.join("proa-config"))
        .unwrap()
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path().join("stamp-cache.json"))
        .filter(|path| path.is_file())
        .collect();
    assert_eq!(cache_files.len(), 1);
    let persisted = fs::read_to_string(&cache_files[0]).unwrap();
    assert!(persisted.contains("PROA_TEST_DEV_CMD"), "{persisted}");
    assert!(!persisted.contains("secret-alpha"), "{persisted}");

    // Second completely fresh CLI process with identical env reuses persisted stamp-cache.json.
    let second = run_validate(Some("cargo run --bin secret-alpha"));
    assert!(
        second.status.success(),
        "{}",
        String::from_utf8_lossy(&second.stderr)
    );
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        1,
        "second CLI process should skip cargo build when inputs and compile-time env are unchanged"
    );

    // Changing a compile-time `option_env!()` value must invalidate the persisted stamp cache.
    let env_changed = run_validate(Some("cargo run --bin secret-beta"));
    assert!(
        env_changed.status.success(),
        "{}",
        String::from_utf8_lossy(&env_changed.stderr)
    );
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        2,
        "changing compile-time option_env!() must invalidate persisted stamp cache"
    );

    // Unsetting the compile-time `option_env!()` variable must also invalidate the cache.
    let env_unset = run_validate(None);
    assert!(
        env_unset.status.success(),
        "{}",
        String::from_utf8_lossy(&env_unset.stderr)
    );
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        3,
        "unsetting compile-time option_env!() must invalidate persisted stamp cache"
    );

    // Editing `proa.config.rs` invalidates the persisted stamp cache and recompiles once.
    let updated = format!(
        "{}\n// touched\n",
        fs::read_to_string(root.join("proa.config.rs")).unwrap()
    );
    fs::write(root.join("proa.config.rs"), updated).unwrap();
    let file_changed = run_validate(None);
    assert!(
        file_changed.status.success(),
        "{}",
        String::from_utf8_lossy(&file_changed.stderr)
    );
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        4,
        "editing proa.config.rs must invalidate persisted stamp cache"
    );

    // A Cargo profile setting can change what `cfg!(debug_assertions)` compiles to.
    profile.set(Some("false"));
    let profile_changed = run_validate(None);
    assert!(
        profile_changed.status.success(),
        "{}",
        String::from_utf8_lossy(&profile_changed.stderr)
    );
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        5,
        "a new CARGO_PROFILE_* setting must invalidate persisted stamp cache"
    );
    run_validate(None);
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        5,
        "an unchanged profile setting reuses the persisted stamp cache"
    );

    // Interactive `proa dev` sets CARGO_TERM_QUIET while its `proa run dev`
    // parent does not. Output-only settings must not split their caches.
    quiet.set(true);
    run_validate(None);
    quiet.set(false);
    run_validate(None);
    assert_eq!(
        fs::read_to_string(&cargo_trace).unwrap().lines().count(),
        5,
        "CARGO_TERM_* settings must not invalidate the persisted stamp cache"
    );
}

#[test]
fn build_bundles_the_public_catalog_beside_the_exported_executable() {
    let temp = fixture();
    let root = temp.path();
    let exported_bin = temp.path().join("release-export/app");
    let bundled = temp.path().join("release-export/app.assets");
    let build = |extra: &[&str]| {
        let mut args = vec!["build", "--offline", "--no-check", "--artifact-out"];
        args.push(exported_bin.to_str().unwrap());
        args.extend_from_slice(extra);
        cli(root, &args)
    };

    // No flag and no environment variable: the catalog follows the executable.
    let first = success(&build(&[]));
    assert!(first.contains(" public assets in "), "{first}");
    let catalog = AssetCatalog::load(&bundled).unwrap();
    let first_url = catalog.manifest().assets["logo.svg"].public_path.clone();
    assert_eq!(
        fs::read(catalog.object_path("logo.svg").unwrap()).unwrap(),
        b"first"
    );
    drop(catalog);
    // The bundle holds each file at the path of its URL, the manifest, and
    // the marker that says Proa wrote it. A static host can serve `public/`.
    assert_eq!(
        fs::read(bundled.join("public/_proa/immutable").join(&first_url)).unwrap(),
        b"first"
    );
    let mut entries: Vec<_> = fs::read_dir(&bundled)
        .unwrap()
        .map(|entry| entry.unwrap().file_name().into_string().unwrap())
        .collect();
    entries.sort();
    assert_eq!(entries, [".proa-assets", "manifest.json", "public"]);

    // The directory is self-contained: it still loads after the pair is moved.
    let moved = temp.path().join("deployed");
    fs::create_dir(&moved).unwrap();
    fs::copy(&exported_bin, moved.join("app")).unwrap();
    copy_tree(&bundled, &moved.join("app.assets"));
    let relocated = AssetCatalog::load(moved.join("app.assets")).unwrap();
    assert_eq!(
        relocated.manifest().assets["logo.svg"].public_path,
        first_url
    );
    drop(relocated);

    // A rebuild to the same path updates the bundled catalog in place.
    fs::write(root.join("public/logo.svg"), b"second").unwrap();
    success(&build(&[]));
    let updated = AssetCatalog::load(&bundled).unwrap();
    let second_url = updated.manifest().assets["logo.svg"].public_path.clone();
    assert_ne!(first_url, second_url);
    drop(updated);

    // `proa start` hands the bundled catalog to the executable it starts.
    let started = success(&cli(
        root,
        &["start", "--bin", exported_bin.to_str().unwrap()],
    ));
    let manifest: AssetManifest = serde_json::from_str(
        started
            .lines()
            .find_map(|line| line.strip_prefix("MAIN||"))
            .expect("started executable"),
    )
    .unwrap();
    assert_eq!(manifest.assets["logo.svg"].public_path, second_url);

    // A directory that belongs to something else is refused and left untouched.
    let blocked_bin = temp.path().join("blocked/app");
    let blocked = temp.path().join("blocked/app.assets");
    fs::create_dir_all(&blocked).unwrap();
    fs::write(blocked.join("existing.txt"), "keep").unwrap();
    let refused = cli(
        root,
        &[
            "build",
            "--offline",
            "--no-check",
            "--artifact-out",
            blocked_bin.to_str().unwrap(),
        ],
    );
    assert!(!refused.status.success());
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(stderr.contains("is in the way"), "{stderr}");
    assert_eq!(fs::read_dir(&blocked).unwrap().count(), 1);
    assert!(!blocked_bin.exists());

    // An export inside the public directory is refused before anything is
    // written there for a later build to publish.
    let inside = root.join("public/app");
    let overlapping = cli(
        root,
        &[
            "build",
            "--offline",
            "--no-check",
            "--artifact-out",
            inside.to_str().unwrap(),
        ],
    );
    assert!(!overlapping.status.success());
    let stderr = String::from_utf8_lossy(&overlapping.stderr);
    assert!(stderr.contains("overlaps the public directory"), "{stderr}");
    assert!(!root.join("public/app.assets").exists());
    assert!(!inside.exists());

    // A directory is not an executable path: nothing is bundled beside it.
    let directory = temp.path().join("release-dir");
    fs::create_dir(&directory).unwrap();
    let not_a_file = cli(
        root,
        &[
            "build",
            "--offline",
            "--no-check",
            "--artifact-out",
            directory.to_str().unwrap(),
        ],
    );
    assert!(!not_a_file.status.success());
    assert!(!temp.path().join("release-dir.assets").exists());

    // An empty leftover directory is adopted, and one holding only the lock
    // of an interrupted build is not mistaken for someone else's.
    let interrupted_bin = temp.path().join("interrupted/app");
    let interrupted = temp.path().join("interrupted/app.assets");
    fs::create_dir_all(&interrupted).unwrap();
    fs::write(interrupted.join(".writer.lock"), "").unwrap();
    success(&cli(
        root,
        &[
            "build",
            "--offline",
            "--no-check",
            "--artifact-out",
            interrupted_bin.to_str().unwrap(),
        ],
    ));
    drop(AssetCatalog::load(&interrupted).unwrap());

    // A build that publishes nothing leaves the catalog alone while a server
    // is still reading it.
    let reader = AssetCatalog::load(&bundled).unwrap();
    let installed = fs::metadata(&exported_bin).unwrap().modified().unwrap();
    let in_use = build(&["--no-assets"]);
    assert!(!in_use.status.success());
    // The refusal comes before the executable is replaced.
    assert_eq!(
        fs::metadata(&exported_bin).unwrap().modified().unwrap(),
        installed
    );
    let stderr = String::from_utf8_lossy(&in_use.stderr);
    assert!(stderr.contains("still being read"), "{stderr}");
    assert!(reader.object_path("logo.svg").unwrap().is_file());
    drop(reader);

    // Otherwise it removes the catalog an earlier export left there, so the
    // executable cannot start with stale files.
    success(&build(&["--no-assets"]));
    assert!(exported_bin.is_file());
    assert!(!bundled.exists());
}

fn copy_tree(from: &Path, to: &Path) {
    fs::create_dir_all(to).unwrap();
    for entry in fs::read_dir(from).unwrap() {
        let entry = entry.unwrap();
        let target = to.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_tree(&entry.path(), &target);
        } else {
            fs::copy(entry.path(), target).unwrap();
        }
    }
}