htl-cli 0.9.0

htl command line (also `cargo htl`): check / run / test / fmt / build / pkg / new for Teal 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
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
//! `htl new` / `htl init`: project scaffolding.
//!
//! Layout (chosen so the same tree works for `htl run` / `htl test` locally *and*
//! as an mlua-pkg dependency for consumers):
//!
//! ```text
//! <name>/
//! ├── mlua-pkg.toml          [package] entry = "src/<mod>"  -> consumers require("<name>")
//! ├── htl.toml               [fmt], and commented [lint] / [check] / [[contract]] to fill
//! │                          in; [build] target with --target. Read by the CLI and the macros
//! ├── mise.toml              the htl command that wrote it, for mise (release builds only)
//! ├── .gitignore             .htl/ (the cache and the installed deps) and *.hb; a target
//! │                          adds its own lines
//! ├── README.md              the commands to run, and what the manifest's entry is for
//! ├── src/<mod>/init.tl      the module (require("<mod>") from src/ and from tests/)
//! ├── src/main.tl            entry script            (omitted with --lib)
//! ├── types/README.md        .d.tl the project consumes (hand-written, and <crate>/ copied
//! │                          from a dependency) and publishes (a ---@contract type)
//! ├── patches/<dep>/         a dependency taken into the tree (htl pkg patch), committed;
//! │                          checked, not formatted, its tests not run
//! ├── tests/<mod>_test.tl    htl.test sample; helpers beside it are not run
//! └── Cargo.toml + src/lib.rs    Rust host (only with a target): #[host_module] exposing
//!     + src/main.rs               `host` to Teal (declaration -> src/host.d.tl), the
//!                                 module and its require closure embedded with
//!                                 include_bundle!, and a thin binary on top when there
//!                                 is an entry script
//! ```
//!
//! A target may add to that: the `cdylib` one writes `examples/c/` and `examples/python/`
//! beside the library, because a C ABI whose reference caller nobody wrote is a C ABI
//! every caller gets wrong in the same three ways. A target may also dictate what the
//! files *say*: the `window` one writes a second host module beside the dependency's `mq`,
//! and an entry script that is a game table rather than a program.
//!
//! # The target is a [`BuildTarget`]; the profile is what the scaffold writes for it
//!
//! Everything above the `Cargo.toml` line is the same for every project. What varies is
//! the target — what will run this project's output, and therefore what Rust it needs —
//! and that is one value rather than a growing set of booleans. The value is
//! [`BuildTarget`], which lives in `htl-core` because `htl.toml` records it as
//! `[build] target`; what it means for the *crate* — its `[lib] crate-type`, whether it
//! takes an entry script — is derived there, from the target, rather than restated here.
//!
//! What is left for this module is the scaffold's own half: a [`TargetProfile`] says what
//! the target depends on, which Rust files it writes, which Teal sample it starts the
//! project from, and what its README has to say. [`PROFILES`] is the registry of the
//! targets that scaffold, `--target <name>` picks an entry from it, and a new kind of
//! target is one more [`BuildTarget`] arm and one more entry rather than another flag
//! threaded through every template.
//!
//! # Every target with Rust in it is a library crate with a thin binary on top
//!
//! Each target that writes Rust writes `src/lib.rs`: the `#[host_module]`, its records,
//! the embedded Teal module, `preload` registering both, and a Rust test that goes through
//! `preload`. When the project has an entry script it also writes `src/main.rs`, a few
//! lines that call `preload` and then run the bundle of `src/main.tl` embedded at `cargo
//! build` — `include_bundle!("src/main.tl", ..)`, the entry script and its `require`
//! closure, handed to `run_bundle` with the process arguments; nothing is read from a file
//! at run time. So what a project grows — a second host module, a C ABI layer, a window
//! loop — grows in the library, every entry point reaches it through `preload`, and
//! another crate that embeds this one calls the same function. `--lib` means the project
//! has no entry script, so there is nothing for a binary to run and none is written; what
//! is left is the library, the part someone else embeds. The `cdylib` target is that
//! taken to its end: a `#[c_export]` block in the same library and no binary at all,
//! which is why it is the target that answers
//! [`Script::Forbids`](htl::build_target::Script::Forbids).
//!
//! [`scaffold`] therefore does the same three things whatever it is asked for: pick the
//! target, turn the profile into a list of paths and bodies, write the ones that do not
//! exist yet. No template branches on `--embed`; the ones that differ between targets are
//! separate templates, chosen by the profile.
//!
//! Bodies where doubling every brace for `format!` cost more than it was worth — the Rust
//! host, the Teal sample, a C caller — live under `crates/htl-cli/templates/` and are
//! read with `include_str!`, filled by replacing `{{name}}` / `{{mod}}` / `{{MOD}}`, and
//! `{{embed}}` / `{{install}}` for what a host's `lib.rs` has under one pin and not
//! another (see [`fill`]). They stay in this crate rather than being fetched. Short TOML
//! and Markdown stay inline.
//!
//! # What the output pins is the htl this binary was built with
//!
//! A scaffolded project's `Cargo.toml` pins an `htl`, and the scaffold writes what that
//! htl reads: `htl.toml` keys, the host's `include_bundle!`. The htl it writes for is the
//! one this CLI links — same version, same tree — and the only question is where that
//! tree is for the project: on crates.io at this version when the CLI is a published
//! release, at a checkout's path when it was built from one. `build.rs` answers that at
//! build time and [`HtlPin::default`] reads the answer; `--htl main` and `--htl
//! path:<checkout>` name another tree by hand. There is no number to pass: a project for
//! an older release is written by that release's CLI (`cargo install htl-cli --version
//! <release>`), the way every generator that ships beside its library does it.
//!
//! It was a window once — `SUPPORTED`, a `DEFAULT_HTL` raised by hand after each publish,
//! and `knows_*` questions that let one CLI write for two releases. The window cost a
//! commit per minor and once wrote a bundle host for a release whose linker could not
//! serve it (#243, #245). A CLI that writes only for what it links cannot do that.

use anyhow::{Context, Result, anyhow, bail};
use htl::BuildTarget;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// The htl a scaffolded project depends on: where the htl this CLI was built with is,
/// for the project being written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HtlPin {
    /// A published version, as cargo's caret requirement reads it: `"0.6.0"` is
    /// `>=0.6.0, <0.7.0`. Three numbers, because a CLI at 0.6.1 writes for 0.6.1 and a
    /// project that resolved 0.6.0 under it would be one release behind its own scaffold.
    Release(String),
    /// The repository's `main` branch: `{ git = "<repository url>", branch = "main" }`.
    Main,
    /// A local checkout of this repository, by its root: `{ path = "<root>/crates/htl" }`.
    Path(PathBuf),
}

/// This repository, for the `main` pin's git dependency. Taken from the package metadata,
/// which inherits `[workspace.package] repository`, so the URL is not written twice.
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");

/// The collections library a scaffolded project depends on from the start: `htlx.list` /
/// `tablex` / `seq` / `ordered`, pure Teal, in its own repository. Lua has no such layer of
/// its own, so every project used to write the same fifty lines; the scaffold writes the
/// dependency instead and the README's first step is `htl pkg install`.
const HTLX_REPOSITORY: &str = "https://github.com/ynishi/htl-x";

/// The tag of [`HTLX_REPOSITORY`] the scaffold pins. Data with a default rather than
/// anything derived: it moves when htl-x cuts a tag that the e2e consumer gate
/// (`e2e/tests/htlx_consumer.rs`) has been seen to install, check and test against this
/// checkout — and not before, because a tag nobody has pulled through this scaffold is a
/// project `htl new` cannot promise works. Exact, not a prefix: mlua-pkg's `tag` is one
/// ref, and a floating `v0.1` would be a tag htl-x has to keep moving.
pub const HTLX_TAG: &str = "v0.1.0";

/// How this binary was built, as `build.rs` decided it: `release`, `main` or `path`.
/// The table in `build.rs` says which tree each one comes from.
const PIN_DEFAULT: &str = env!("HTL_PIN_DEFAULT");

/// The checkout this binary was built in, when [`PIN_DEFAULT`] is `path`; empty otherwise.
const PIN_CHECKOUT: &str = env!("HTL_PIN_CHECKOUT");

impl Default for HtlPin {
    /// What `htl new` pins when `--htl` is not given: this CLI's own htl, where it is.
    /// A published CLI pins its version on crates.io; one built from a checkout pins that
    /// checkout, so `cargo run -- new` in this repository writes a project that builds
    /// against the tree it was written by, with nothing patched afterwards.
    fn default() -> Self {
        match PIN_DEFAULT {
            "release" => HtlPin::Release(env!("CARGO_PKG_VERSION").to_string()),
            "main" => HtlPin::Main,
            "path" => HtlPin::Path(PathBuf::from(PIN_CHECKOUT)),
            other => unreachable!("build.rs wrote HTL_PIN_DEFAULT={other}"),
        }
    }
}

impl HtlPin {
    /// Read what `--htl` was given: nothing (the default), `main`, or `path:<checkout>`.
    ///
    /// A number is refused, and the refusal says where that release's scaffold is. This
    /// CLI's templates are the ones its own htl reads — `htl.toml` keys, the host's
    /// macros — so a project pinned at another release by this binary is a project whose
    /// first `cargo build` reads a key that release does not have. The CLI that wrote for
    /// that release is on crates.io beside it.
    pub fn parse(s: Option<&str>) -> Result<HtlPin> {
        let Some(s) = s else {
            return Ok(HtlPin::default());
        };
        if s == "main" {
            return Ok(HtlPin::Main);
        }
        if let Some(dir) = s.strip_prefix("path:") {
            if dir.is_empty() {
                bail!("`path:` names no checkout directory; {}", accepted());
            }
            return Ok(HtlPin::Path(PathBuf::from(dir)));
        }
        bail!(
            "unsupported htl `{s}`; {}. A project for a published release is written by that release's CLI: cargo install htl-cli --version {s}",
            accepted()
        );
    }

    /// The right-hand side of the `htl = ...` line a project's `Cargo.toml` gets, with no
    /// features on it: `"0.6.0"`, or the git or path table. A target that needs features
    /// merges them into the same table — see [`dep_value`], which is where both forms are
    /// written.
    ///
    /// `allow(dead_code)` because every scaffolded manifest goes through [`t_cargo`], which
    /// has the target's features in hand and so calls [`dep_value`] directly. This is the
    /// featureless form the tests and the README quote, and it is the one a caller outside
    /// this module would want.
    #[allow(dead_code)]
    pub fn requirement(&self) -> String {
        dep_value(&self.keys(), &[])
    }

    /// The pin as a cargo dependency table's key/value pairs, in the order they are
    /// written. Features are deliberately absent: they belong to the target that asked for
    /// them ([`DepLine`]), and keeping the two apart until [`dep_value`] is what stops the
    /// `cdylib` line from being right under one pin kind and wrong under the others.
    fn keys(&self) -> Vec<(&'static str, String)> {
        self.keys_for("htl")
    }

    /// The same for any crate of this repository ([`Dep::Sibling`]). The pin names a
    /// *tree* — a release of the workspace, a branch of it, a checkout of it — and every
    /// crate in that tree is at the same place in it, so only the last path segment
    /// changes. A release and a branch do not even change that: the version and the branch
    /// are the workspace's, and the crate name is the key on the left of the line.
    fn keys_for(&self, crate_name: &str) -> Vec<(&'static str, String)> {
        match self {
            HtlPin::Release(v) => vec![("version", v.clone())],
            HtlPin::Main => vec![
                ("git", REPOSITORY.to_string()),
                ("branch", "main".to_string()),
            ],
            // Forward slashes and no trailing one, because this goes into TOML: a Windows
            // path written verbatim would be a string with invalid escapes in it, and cargo
            // reads `/` on every platform.
            HtlPin::Path(root) => vec![(
                "path",
                format!(
                    "{}/crates/{crate_name}",
                    root.display()
                        .to_string()
                        .replace('\\', "/")
                        .trim_end_matches('/')
                ),
            )],
        }
    }
}

/// What `--htl` accepts, for the refusals in [`HtlPin::parse`].
fn accepted() -> String {
    format!(
        "--htl takes `main` or `path:<checkout>`, and without it a project pins the htl this CLI was built with ({})",
        HtlPin::default().requirement()
    )
}

pub struct Options {
    pub lib: bool,
    /// The target to write for, already resolved against [`PROFILES`] by
    /// [`resolve_target`], so nothing downstream can be asked for a target that does not
    /// exist or does not fit `--lib`.
    pub target: Option<&'static TargetProfile>,
    /// The htl the scaffolded project depends on, already read from `--htl` by
    /// [`HtlPin::parse`] — so, like the target, a refusal happens before the first file.
    /// It decides the `htl` line of `Cargo.toml` and whether `mise.toml` is written
    /// ([`t_mise`]), and nothing else: every template is the one this CLI's own htl reads.
    pub htl: HtlPin,
    /// `--no-x`: leave the `htlx` dependency out of the manifest whatever the pin. For a
    /// project that wants no dependency at all, or one that will name its own.
    pub no_x: bool,
}

impl Options {
    /// Whether the manifest gets the `htlx` line: `--no-x` was not given. Asked once here
    /// so the manifest, the README's first step and the `next:` hint cannot disagree. The
    /// pin used to have a say — `0.4` installed the dependency and could not resolve it at
    /// its `entry` (#204 landed in 0.5) — and every pin this scaffold still writes for can.
    pub fn writes_htlx(&self) -> bool {
        !self.no_x
    }
}

/// What a template is filled with: the package name and its Teal identifier. The
/// templates themselves branch on nothing — the profile decides which body is written in
/// the first place — but the README is one body for every project, and what it tells the
/// reader to run does depend on whether there is an entry script, so that answer travels
/// with the names.
pub struct Ctx<'a> {
    pub name: &'a str,
    pub module: &'a str,
    /// Is there a `src/main.tl` to run? The inverse of `--lib`, already reconciled with
    /// the target by [`resolve_target`].
    pub script: bool,
    /// Does the manifest name `htlx`? [`Options::writes_htlx`], carried here because the
    /// README's first step depends on it the way its command block depends on `script`.
    pub htlx: bool,
}

/// A dependency line in the project's `Cargo.toml`: what to require, and the features the
/// target turns on.
pub struct DepLine {
    pub name: &'static str,
    pub req: Dep,
    /// Empty writes the short `name = "req"` form; anything else writes the table.
    pub features: &'static [&'static str],
}

impl DepLine {
    /// The common case: a dependency with no features of its own.
    const fn plain(name: &'static str, req: Dep) -> Self {
        DepLine {
            name,
            req,
            features: &[],
        }
    }
}

/// What a dependency line requires.
pub enum Dep {
    /// The htl the pin names (see [`HtlPin`]).
    Htl,
    /// Another crate of this repository, under the same pin as `htl`: the release at this
    /// version, the same branch of the same git URL, or the checkout's `crates/<name>`.
    /// The four crates share one version and one tree, so a project that pins `htl` at a
    /// checkout and `htl-mq` at a release would be pinning two htls.
    Sibling(&'static str),
    /// A literal requirement.
    Version(&'static str),
}

/// One file a target's scaffold writes, relative to the project root. Mostly Rust —
/// `src/lib.rs`, `src/main.rs` — but a target that ships reference callers writes their C,
/// Python and build glue the same way, as a path and a body.
pub struct ScaffoldFile {
    pub path: &'static str,
    pub body: fn(&Ctx<'_>) -> String,
}

/// The Teal sample a project starts from. A target that dictates a different shape (a
/// `Game` record for a window loop, an entry script that requires `host`) points these at
/// its own templates; everything else uses [`DEFAULT_TEAL`].
pub struct TealSample {
    pub module: fn(&Ctx<'_>) -> String,
    pub test: fn(&Ctx<'_>) -> String,
    /// `src/main.tl`, written only when the project has an entry script.
    pub main: fn(&Ctx<'_>) -> String,
}

/// The per-target scaffold data: what the scaffold writes for one [`BuildTarget`].
///
/// What a build target *is* — and what follows from it, the crate types and the
/// entry-script rule — is defined on [`BuildTarget`], not here. This is the other half:
/// the files, the dependencies and the prose that only `htl new` has an opinion about.
pub struct TargetProfile {
    /// Which build target this scaffolds for. Its name is the name in the registry and on
    /// the command line (`--target <name>`), and its `crate_types` / `entry` are what the
    /// `Cargo.toml` and the `--lib` reconciliation below read.
    pub target: BuildTarget,
    pub deps: &'static [DepLine],
    /// `src/lib.rs`: the host module, the embedded Teal, `preload`. Always written.
    pub lib: ScaffoldFile,
    /// `src/main.rs`: the thin entry, written only when there is an entry script.
    pub main: Option<ScaffoldFile>,
    /// Anything else the target ships: `examples/`, `include/`, a header.
    pub extra: &'static [ScaffoldFile],
    /// What this target builds that is not worth committing, as `.gitignore` lines
    /// (filled like a template, so a path may name the module). What it *generates* and
    /// commits — `src/host.d.tl`, the C header — is deliberately not here.
    pub ignore: &'static [&'static str],
    pub teal: TealSample,
    /// The lines this target adds to the README's command block, and the paragraphs that
    /// follow it. The README is the one body every project has and every target has
    /// something different to say in, so it is written here rather than branched on the
    /// target's name where the file is assembled.
    pub readme_commands: fn(&Ctx<'_>) -> String,
    pub readme_prose: fn(&Ctx<'_>) -> String,
}

/// The default target: the OS runs the output as a binary. A library crate holding the
/// host module and the embedded scripts, with a thin binary on top when the project has an
/// entry script. `--target bin`, and `--embed` which is its shorthand, add to the tree:
///
/// ```text
/// ├── Cargo.toml             htl + anyhow, and [profile.dev.build-override] opt-level = 3
/// ├── src/lib.rs             #[host_module] Host, its records, the embedded module,
/// │                          and pub fn preload(&Htl) registering both
/// ├── src/host.d.tl          generated from src/lib.rs — by cargo build, and by
/// │                          htl dts / htl check without building
/// └── src/main.rs            the binary: preload, then the bundle of src/main.tl it embeds
///                            (omitted with --lib)
/// ```
const BIN: TargetProfile = TargetProfile {
    target: BuildTarget::Bin,
    deps: &[
        DepLine::plain("htl", Dep::Htl),
        DepLine::plain("anyhow", Dep::Version("1")),
    ],
    lib: ScaffoldFile {
        path: "src/lib.rs",
        body: rust_lib_rs,
    },
    main: Some(ScaffoldFile {
        path: "src/main.rs",
        body: rust_main_rs,
    }),
    extra: &[],
    ignore: &["/target"],
    teal: TealSample {
        module: teal_module,
        test: teal_test,
        // The entry script talks to the Rust side, so it is the host's, not the default.
        main: rust_main_tl,
    },
    readme_commands: rust_readme_commands,
    readme_prose: rust_readme_prose,
};

/// The C ABI target: a caller that is not written in Rust runs the output. The same
/// library, plus `#[c_export]` and the two reference callers.
///
/// It is a library and nothing else — a `cdylib` has no entry point of its own, and the
/// caller that loads it brings its own `main` — so the
/// [`Script::Forbids`](htl::build_target::Script::Forbids) that
/// [`BuildTarget::Cdylib`] answers refuses `--target cdylib` without `--lib` rather than
/// writing a `src/main.rs` nothing would run. The `staticlib` alongside is what Unity on
/// iOS links; it costs a second artefact and nothing else.
///
/// The sample shows both error paths rather than describing them: the generated `greet`
/// refuses an empty name in Teal (a Lua `error()`) and `reset` refuses a no-op in Rust (an
/// `Err`), so the callers have each kind to handle in front of the reader.
///
/// ```text
/// ├── Cargo.toml             crate-type = ["rlib", "cdylib", "staticlib"], htl with
/// │                          features = ["ffi"], serde
/// ├── src/lib.rs             the #[host_module] the scripts call, and a #[c_export] Game
/// │                          the caller holds: open / a text call / JSON / a status / close
/// ├── include/<mod>.h        written by #[c_export] at cargo build (and by htl dts), committed
/// ├── examples/c/            main.c + a Makefile: every returned char * goes back to _free
/// └── examples/python/       run.py: restype = c_void_p and ctypes.cast, never c_char_p
/// ```
const CDYLIB: TargetProfile = TargetProfile {
    target: BuildTarget::Cdylib,
    deps: &[
        DepLine {
            name: "htl",
            req: Dep::Htl,
            // The C ABI runtime the generated wrappers call, and `#[c_export]` itself.
            features: &["ffi"],
        },
        DepLine::plain("anyhow", Dep::Version("1")),
        DepLine {
            name: "serde",
            req: Dep::Version("1"),
            // The options come in as JSON and the records go out as JSON.
            features: &["derive"],
        },
    ],
    lib: ScaffoldFile {
        path: "src/lib.rs",
        body: ffi_lib_rs,
    },
    main: None,
    extra: &[
        ScaffoldFile {
            path: "examples/c/main.c",
            body: ffi_example_c,
        },
        ScaffoldFile {
            path: "examples/c/Makefile",
            body: ffi_example_makefile,
        },
        ScaffoldFile {
            path: "examples/python/run.py",
            body: ffi_example_py,
        },
    ],
    // The C caller's binary. The header the macro writes is *not* ignored: it is
    // generated and committed, like `src/host.d.tl`, so that reading the ABI does not
    // mean building the crate.
    ignore: &["/target", "examples/c/{{mod}}_c"],
    teal: TealSample {
        module: ffi_teal_module,
        test: ffi_teal_test,
        // Unreachable: `Script::Forbids` means there is never a `src/main.tl` to write.
        // The field is not an `Option` because every other target has one, so this is the
        // default sample, which is what `htl init --target cdylib` on a project that
        // already has a script would keep anyway.
        main: teal_main,
    },
    readme_commands: ffi_readme_commands,
    readme_prose: ffi_readme_prose,
};

/// The window target: the OS runs the output as a windowed app. The same library and thin
/// binary as [`BIN`], plus `htl-mq` — macroquad's drawing and input as the host module
/// `mq`, and the frame loop `src/main.rs` hands a game table to.
///
/// Two host modules, not one: `mq` is the dependency's, and `fx` is the project's own, for
/// the per-pixel work the engine only asks for. That is the shape the target exists to
/// write down, because it is the one a game gets wrong by putting the loop in the engine:
/// the engine here is Teal, takes its world as arguments, and is what `htl test` runs with
/// no display, while `src/main.tl` — the one script that calls `mq` — is the game table and
/// nothing else. Hence [`Script::Requires`](htl::build_target::Script::Requires): a loop
/// with no table to drive is not a project this scaffold can write.
///
/// Both generated declarations are committed — `src/fx.d.tl` from the project's own
/// `#[host_module]`, `types/htl-mq/mq.d.tl` copied out of the dependency — and the first
/// command in a fresh clone is `htl check .`, which writes both; `cargo build` reads the
/// second when `include_bundle!` links `mq`. `HTL_MQ_FRAMES=60 HTL_MQ_SHOT=out.png cargo
/// run` stops after sixty frames and writes the last one as a PNG.
///
/// ```text
/// ├── Cargo.toml             htl + htl-mq (under the same pin) + anyhow
/// ├── src/lib.rs             #[host_module] Fx — the project's own GPU side — the embedded
/// │                          engine, and preload registering it, `fx` and htl-mq's `mq`
/// ├── src/fx.d.tl            generated from src/lib.rs by cargo build / htl dts / htl check
/// ├── src/<mod>/init.tl      the engine: balls in a box, pure rules, no window
/// ├── src/main.tl            the game table htl_mq::run drives: update(dt), draw()
/// ├── src/main.rs            the binary: preload, then htl_mq::run
/// └── types/htl-mq/mq.d.tl   the dependency's declaration, copied in by htl check
/// ```
const WINDOW: TargetProfile = TargetProfile {
    target: BuildTarget::Window,
    deps: &[
        DepLine::plain("htl", Dep::Htl),
        // Under the same pin as `htl`: they are two crates of one tree, and one version.
        DepLine::plain("htl-mq", Dep::Sibling("htl-mq")),
        DepLine::plain("anyhow", Dep::Version("1")),
    ],
    lib: ScaffoldFile {
        path: "src/lib.rs",
        body: window_lib_rs,
    },
    main: Some(ScaffoldFile {
        path: "src/main.rs",
        body: window_main_rs,
    }),
    extra: &[],
    ignore: &["/target"],
    teal: TealSample {
        module: window_teal_module,
        test: window_teal_test,
        main: window_main_tl,
    },
    readme_commands: window_readme_commands,
    readme_prose: window_readme_prose,
};

/// Every target the scaffold writes Rust for. [`BuildTarget::Hb`] is not among them: it is
/// what plain `htl new` writes, which is the tree without a `Cargo.toml` at all.
pub static PROFILES: &[TargetProfile] = &[BIN, CDYLIB, WINDOW];

/// The target `--embed` is shorthand for.
pub const DEFAULT_TARGET: BuildTarget = BuildTarget::Bin;

/// What a project with no target of its own starts from.
static DEFAULT_TEAL: TealSample = TealSample {
    module: teal_module,
    test: teal_test,
    main: teal_main,
};

const T_MANIFEST: &str = include_str!("../templates/mlua-pkg.toml");
const T_TEAL_MODULE: &str = include_str!("../templates/teal/init.tl");
const T_TEAL_TEST: &str = include_str!("../templates/teal/test.tl");
const T_TEAL_MAIN: &str = include_str!("../templates/teal/main.tl");
const T_RUST_MAIN_TL: &str = include_str!("../templates/rust/main.tl");
const T_RUST_LIB_RS: &str = include_str!("../templates/rust/lib.rs");
const T_RUST_MAIN_RS: &str = include_str!("../templates/rust/main.rs");
const T_FFI_LIB_RS: &str = include_str!("../templates/ffi/lib.rs");
const T_FFI_TEAL_MODULE: &str = include_str!("../templates/ffi/init.tl");
const T_FFI_TEAL_TEST: &str = include_str!("../templates/ffi/test.tl");
const T_FFI_MAIN_C: &str = include_str!("../templates/ffi/main.c");
const T_FFI_MAKEFILE: &str = include_str!("../templates/ffi/Makefile");
const T_FFI_RUN_PY: &str = include_str!("../templates/ffi/run.py");
const T_WINDOW_LIB_RS: &str = include_str!("../templates/window/lib.rs");
const T_WINDOW_MAIN_RS: &str = include_str!("../templates/window/main.rs");
const T_WINDOW_TEAL_MODULE: &str = include_str!("../templates/window/init.tl");
const T_WINDOW_TEAL_TEST: &str = include_str!("../templates/window/test.tl");
const T_WINDOW_MAIN_TL: &str = include_str!("../templates/window/main.tl");

/// Teal identifier for a package name (`my-pkg` -> `my_pkg`).
pub fn module_ident(name: &str) -> String {
    let mut s: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();
    if s.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        s.insert(0, '_');
    }
    s
}

/// Rust's keywords, as cargo refuses them for a package name. The list is a copy of
/// `is_keyword` in cargo's `src/cargo/util/restricted_names.rs` (read from the cargo
/// 0.99.0 sources), which is the Rust reference's strict *and* reserved sets together —
/// `become` and `typeof` are no more usable as a crate name than `match` is.
const RUST_KEYWORDS: &[&str] = &[
    "Self", "abstract", "as", "async", "await", "become", "box", "break", "const", "continue",
    "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl",
    "in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref",
    "return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
    "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];

/// What cargo's list above does not have and a scaffolded crate still cannot be called.
/// `gen` is reserved in the 2024 edition, which is the edition [`t_cargo`] writes, and
/// cargo's `is_keyword` has not caught up: `cargo new gen` succeeds (cargo 1.95.0), and
/// the crate it writes stops at "expected expression, found reserved keyword gen" the
/// moment anything spells the crate's own path — which `src/main.rs` does, on its
/// `preload` line. Measured, not assumed: a two-file crate named `gen` on edition
/// 2024, `pub fn f()` in the library and `gen::f()` in the binary, fails to compile on
/// rustc 1.95.0.
const RUST_KEYWORDS_BEYOND_CARGO: &[&str] = &["gen"];

/// Lua 5.4's keywords, all 22 of them (§3.1 of the reference manual). Teal keeps every
/// one: `local end = require("end")` is a syntax error in both languages, and the
/// scaffold writes exactly that line.
const LUA_KEYWORDS: &[&str] = &[
    "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
    "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while",
];

/// Teal's contextual words that the scaffold's own files cannot carry. They are not
/// keywords — Teal lets a variable be called `record` — but each one opens a type
/// declaration after `local`, so the entry script's `local g = record.greet(..)` is read
/// as the declaration `local record g` and the project does not check.
///
/// Measured against this checkout's binary rather than reasoned about, by scaffolding a
/// project under each of the nine contextual words Teal has and running `htl check .` on
/// it: `record`, `enum` and `interface` fail (`syntax error: this syntax is no longer
/// valid; use 'local record g'`); `type`, `where`, `is`, `as`, `global` and `macroexp`
/// scaffold and check clean, so they are not refused.
const TEAL_TYPE_WORDS: &[&str] = &["record", "enum", "interface"];

/// Refuse a project name the scaffold cannot write into the files it is about to write,
/// before it writes the first one.
///
/// The name is not only a directory. It is the package in `mlua-pkg.toml`, the module
/// directory `src/<mod>/`, the record that module declares, the local `src/main.tl` binds
/// `require` to — and, when the project has a target, the crate in `Cargo.toml` and the
/// path `src/main.rs` reaches `preload` through. [`module_ident`] makes an identifier out
/// of the name and promises nothing more: it replaces what is not alphanumeric and
/// prefixes a leading digit, so `pub` comes out of it as `pub`, and `htl new pub --embed`
/// writes eleven files whose `cargo build` is "visibility `pub` is not followed by an
/// item". No later stage can fix that, which is why the question is asked here, beside
/// the ones [`resolve_target`] and [`HtlPin::parse`] ask: a refused name leaves nothing
/// behind.
///
/// Two sets, because two languages read the name.
///
/// **When the project has a target** it has a `Cargo.toml` ([`t_cargo`] is the only file
/// that names a crate, and `plan` writes it exactly when there is a target), and then the
/// rules are the ones `cargo new` applies — [`RUST_KEYWORDS`] from cargo's own
/// `restricted_names`, plus [`RUST_KEYWORDS_BEYOND_CARGO`], a leading digit, and a
/// character outside `[A-Za-z0-9_-]`. Adopting cargo's set rather than inventing one
/// means a name htl takes is a name `cargo new` would have taken, and the refusal can
/// keep cargo's shape (``invalid package name `pub`: it is a Rust keyword``) so that a
/// reader who has met it once recognises it. It is stricter than cargo in one place:
/// cargo's package name is any Unicode XID and warns about non-ASCII, while rustc does
/// not support a non-ASCII crate name — and `module_ident` would turn those characters
/// into `_`, leaving the crate and the module spelled differently. A plain project keeps
/// them: nothing there is compiled by rustc.
///
/// **Every project writes Teal**, so [`LUA_KEYWORDS`] and [`TEAL_TYPE_WORDS`] are checked
/// for every target, and against the *identifier* rather than the name, because that is
/// what reaches the templates. Only a name that is already an identifier can become one
/// of these words — every substitution `module_ident` makes produces a `_`, and no
/// keyword has one — so the refusal names the name the user typed. `--lib` writes no
/// `src/main.tl` and so, today, none of the three Teal words breaks anything in the tree
/// it produces; they are still refused there, because the line that breaks is the first
/// line the author writes when the project grows an entry script, and a name that is
/// wrong in one target and right in another is a worse rule than a name that is wrong.
///
/// What is not refused: `123abc` for a plain project (`module_ident` makes it `_123abc`,
/// which checks), a name a Rust keyword is merely a part of (`pubs`, `my-pub`), and a
/// name whose separators make an identifier out of it (`my-lib` → `my_lib`).
fn refuse_reserved_name(name: &str, module: &str, writes_cargo: bool) -> Result<()> {
    if writes_cargo {
        if RUST_KEYWORDS.contains(&name) {
            bail!("{}", rust_refusal(name, module, "it is a Rust keyword"));
        }
        if RUST_KEYWORDS_BEYOND_CARGO.contains(&name) {
            bail!(
                "{}",
                rust_refusal(
                    name,
                    module,
                    "it is a keyword reserved by Rust's 2024 edition, which is the edition this scaffold writes"
                )
            );
        }
        if name.starts_with(|c: char| c.is_ascii_digit()) {
            bail!(
                "{}",
                rust_refusal(name, module, "the name cannot start with a digit")
            );
        }
        if let Some(ch) = name
            .chars()
            .find(|c| !(c.is_ascii_alphanumeric() || *c == '-' || *c == '_'))
        {
            bail!(
                "{}",
                rust_refusal(
                    name,
                    module,
                    &format!(
                        "invalid character `{ch}`: the name has to be ASCII letters, digits, `-` and `_`"
                    )
                )
            );
        }
    }
    if LUA_KEYWORDS.contains(&module) {
        bail!("{}", teal_refusal(name, module, "it is a Lua keyword"));
    }
    if TEAL_TYPE_WORDS.contains(&module) {
        bail!(
            "{}",
            teal_refusal(name, module, "it is how Teal opens a type declaration")
        );
    }
    Ok(())
}

/// Why a name the Rust half cannot carry is refused: cargo's sentence, then what htl does
/// with the name, then the way out. Its own function because four reasons share
/// everything but the clause in the middle, and the value of taking cargo's shape is that
/// it is the *same* shape each time.
fn rust_refusal(name: &str, module: &str, reason: &str) -> String {
    format!(
        "invalid project name `{name}`: {reason}; a project with a target is a crate named after it and a host that preloads its module through that name (`{module}::preload`), so what cargo or rustc refuses here is a project that does not build — scaffold it under another name"
    )
}

/// The same, for the half every target writes. The line quoted is the one `src/main.tl`
/// would have carried, which is the shortest way to say why the name cannot work.
fn teal_refusal(name: &str, module: &str, reason: &str) -> String {
    format!(
        "invalid project name `{name}`: {reason}; the scaffold binds the module to a local of that name (`local {module} = require(\"{module}\")`) and declares a record called it, so the project it would write does not check — scaffold it under another name"
    )
}

/// Every target the scaffold has a profile for, in registry order: what `--target`
/// accepts and what a typo is answered with. `hb` is deliberately absent — it is the tree
/// plain `htl new` writes, so naming it as a scaffold would be offering a flag for the
/// default.
pub fn target_names() -> Vec<&'static str> {
    PROFILES.iter().map(|p| p.target.name()).collect()
}

pub fn profile(t: BuildTarget) -> Option<&'static TargetProfile> {
    PROFILES.iter().find(|p| p.target == t)
}

/// Turn `--target` / `--embed` / `--lib` into the target to write for, or into the reason
/// there is none to write. Called before the first file is created, so a refusal leaves
/// the directory as it was.
///
/// `--embed` is the shorthand for `--target bin` and stays one: clap's value parser only
/// applies to `--target`, so the two are reconciled here rather than pretended to be one
/// flag. Giving both is fine when they agree — which is decided on the *name* the user
/// wrote, before it is parsed, so that `--embed --target typo` says which flag to drop
/// rather than which targets exist.
pub fn resolve_target(
    target: Option<&str>,
    embed: bool,
    lib: bool,
) -> Result<Option<&'static TargetProfile>> {
    let t = match (target, embed) {
        (None, false) => return Ok(None),
        (None, true) => DEFAULT_TARGET,
        (Some(n), true) if n != DEFAULT_TARGET.name() => bail!(
            "--embed is the shorthand for --target {DEFAULT_TARGET}, so it cannot be given with --target {n}; drop one of them"
        ),
        (Some(n), _) => BuildTarget::from_str(n).map_err(|e| anyhow!("{e}"))?,
    };
    let Some(p) = profile(t) else {
        bail!(
            "the `{t}` target is what plain `htl new` writes, so there is no scaffold to ask for; targets that scaffold: {}",
            target_names().join(", ")
        );
    };
    if !p.target.entry().accepts(lib) {
        bail!("{}", script_mismatch(p, lib));
    }
    Ok(Some(p))
}

/// Why a target and `--lib` do not fit, and which targets do. Its own function because the
/// message is the whole point of refusing here rather than at the first write.
fn script_mismatch(p: &TargetProfile, lib: bool) -> String {
    let fits: Vec<&str> = PROFILES
        .iter()
        .filter(|c| c.target.entry().accepts(lib))
        .map(|c| c.target.name())
        .collect();
    let fits = if fits.is_empty() {
        "none".to_string()
    } else {
        fits.join(", ")
    };
    if lib {
        format!(
            "the `{}` target runs an entry script, which --lib leaves out; targets that work with --lib: {fits}",
            p.target
        )
    } else {
        format!(
            "the `{}` target writes no entry script, so it needs --lib; targets that write one: {fits}",
            p.target
        )
    }
}

/// Everything the scaffold would write, in the order it is reported, before anything
/// touches the disk.
fn plan(dir: &Path, name: &str, module: &str, opts: &Options) -> Vec<(PathBuf, String)> {
    let ctx = Ctx {
        name,
        module,
        script: !opts.lib,
        htlx: opts.writes_htlx(),
    };
    let target = opts.target;
    let teal = target.map_or(&DEFAULT_TEAL, |t| &t.teal);

    let mut files = vec![
        (dir.join("mlua-pkg.toml"), t_manifest(&ctx)),
        (dir.join("htl.toml"), t_htl_toml(target.map(|t| t.target))),
        (dir.join("types").join("README.md"), t_types_readme()),
        (
            dir.join("src").join(module).join("init.tl"),
            (teal.module)(&ctx),
        ),
        (
            dir.join("tests").join(format!("{module}_test.tl")),
            (teal.test)(&ctx),
        ),
        (dir.join(".gitignore"), t_gitignore(target, &ctx)),
        (dir.join("README.md"), t_readme(&ctx, target)),
    ];
    // The command's pin beside the crate's. Under a release pin only: a tree is not
    // something mise can install (see [`t_mise`]).
    if let Some(m) = t_mise(&opts.htl) {
        files.push((dir.join("mise.toml"), m));
    }
    // `--lib` is what "no entry script" means, and a target that disagrees with it was
    // already refused, so the question is answered here for every project alike.
    if !opts.lib {
        files.push((dir.join("src").join("main.tl"), (teal.main)(&ctx)));
    }
    if let Some(t) = target {
        files.push((dir.join("Cargo.toml"), t_cargo(name, t, &opts.htl)));
        files.push((dir.join(t.lib.path), (t.lib.body)(&ctx)));
        // The binary exists to run the entry script, so without one it is not written —
        // and a target that has no binary to write says so with `main: None`.
        if !opts.lib
            && let Some(m) = &t.main
        {
            files.push((dir.join(m.path), (m.body)(&ctx)));
        }
        for f in t.extra {
            files.push((dir.join(f.path), (f.body)(&ctx)));
        }
    }
    files
}

/// What a scaffold run did: the files it created, and the ones it left alone because they
/// were already there. `htl init` reports both, so asking an existing project for a target
/// says which of that target's files it did not touch rather than silently skipping them.
pub struct Scaffolded {
    pub written: Vec<PathBuf>,
    pub kept: Vec<PathBuf>,
}

/// Write every template file that does not exist yet.
/// With `must_be_new`, the directory must not exist (or be empty).
///
/// Two refusals come first, in the order a user meets them: the directory has to be free
/// (under `must_be_new`), and the name has to be one the templates can carry
/// ([`refuse_reserved_name`]). Both happen before the first write, so neither leaves half
/// a project behind.
pub fn scaffold(dir: &Path, name: &str, opts: &Options, must_be_new: bool) -> Result<Scaffolded> {
    if must_be_new && dir.exists() && dir.read_dir()?.next().is_some() {
        bail!(
            "{} already exists and is not empty (use `htl init` to fill in a directory)",
            dir.display()
        );
    }
    let m = module_ident(name);
    refuse_reserved_name(name, &m, opts.target.is_some())?;

    let mut out = Scaffolded {
        written: Vec::new(),
        kept: Vec::new(),
    };
    for (path, text) in plan(dir, name, &m, opts) {
        if path.exists() {
            out.kept.push(path);
            continue;
        }
        if let Some(p) = path.parent() {
            std::fs::create_dir_all(p)?;
        }
        std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
        out.written.push(path);
    }
    Ok(out)
}

/// The placeholders a template file may use. Plain `str::replace`: the bodies are ours,
/// so there is nothing to escape and no engine to depend on. `{{MOD}}` is the module
/// identifier upper-cased, which is how a generated C header spells its own constants
/// (`{{MOD}}_OK`), and therefore how a caller written in C has to spell them.
///
/// Nothing here depends on the pin. There were `{{std}}`, `{{embed}}` and `{{install}}`
/// once, whole lines a template had under one release and not another, while one CLI
/// wrote for a window of releases; a CLI writes for the htl it links now, so a host's
/// `install_std` and `include_bundle!` lines are the template's own.
///
/// There was a `{{htl}}`, and no template ever contained it — the `htl` requirement is
/// assembled in [`t_cargo`], which is the only file that names one. What does spell
/// `{{htl}}` is the snapshot tests' *normalisation*, which is the opposite direction and
/// needs nothing here.
fn fill(template: &str, ctx: &Ctx<'_>) -> String {
    template
        .replace("{{name}}", ctx.name)
        .replace("{{mod}}", ctx.module)
        .replace("{{MOD}}", &ctx.module.to_uppercase())
}

/// The project's `mlua-pkg.toml`: the template, and the `htlx` line put directly under
/// `[deps]` unless `--no-x` left it out.
///
/// The template keeps its commented `lshape` example either way. Under `--no-x` the section
/// is otherwise empty and the comment is the only place the shape of a git dependency is
/// shown; with the dependency the real line above it shows the same shape, and one line of
/// comment is a smaller cost than a template that changes with the flag — every other
/// template is filled by name and module alone, and the manifest stays that way.
fn t_manifest(ctx: &Ctx<'_>) -> String {
    let base = fill(T_MANIFEST, ctx);
    if !ctx.htlx {
        return base;
    }
    let line = format!("htlx = {{ git = \"{HTLX_REPOSITORY}\", tag = \"{HTLX_TAG}\" }}\n");
    // Exactly one `[deps]` in the template, and the line goes right after it — a
    // template without the section would be a template this function cannot fill.
    base.replace("[deps]\n", &format!("[deps]\n{line}"))
}

fn teal_module(ctx: &Ctx<'_>) -> String {
    fill(T_TEAL_MODULE, ctx)
}

fn teal_test(ctx: &Ctx<'_>) -> String {
    fill(T_TEAL_TEST, ctx)
}

fn teal_main(ctx: &Ctx<'_>) -> String {
    fill(T_TEAL_MAIN, ctx)
}

fn rust_main_tl(ctx: &Ctx<'_>) -> String {
    fill(T_RUST_MAIN_TL, ctx)
}

fn rust_lib_rs(ctx: &Ctx<'_>) -> String {
    fill(T_RUST_LIB_RS, ctx)
}

fn rust_main_rs(ctx: &Ctx<'_>) -> String {
    fill(T_RUST_MAIN_RS, ctx)
}

fn ffi_lib_rs(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_LIB_RS, ctx)
}

fn ffi_teal_module(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_TEAL_MODULE, ctx)
}

fn ffi_teal_test(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_TEAL_TEST, ctx)
}

fn ffi_example_c(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_MAIN_C, ctx)
}

fn ffi_example_makefile(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_MAKEFILE, ctx)
}

fn ffi_example_py(ctx: &Ctx<'_>) -> String {
    fill(T_FFI_RUN_PY, ctx)
}

fn window_lib_rs(ctx: &Ctx<'_>) -> String {
    fill(T_WINDOW_LIB_RS, ctx)
}

fn window_main_rs(ctx: &Ctx<'_>) -> String {
    fill(T_WINDOW_MAIN_RS, ctx)
}

fn window_teal_module(ctx: &Ctx<'_>) -> String {
    fill(T_WINDOW_TEAL_MODULE, ctx)
}

fn window_teal_test(ctx: &Ctx<'_>) -> String {
    fill(T_WINDOW_TEAL_TEST, ctx)
}

fn window_main_tl(ctx: &Ctx<'_>) -> String {
    fill(T_WINDOW_MAIN_TL, ctx)
}

fn t_types_readme() -> String {
    "# types/\n\n\
     Hand-written `.d.tl` declarations for modules the host provides at run time and\n\
     that ship no declaration of their own (a Rust crate re-exported to Lua, a runtime\n\
     SDK): `xlib.d.tl` here makes `require(\"xlib\")` typed in `htl check`, `htl test` and\n\
     `include_tl!`. Consulted after the project root and `src/`, before `[check] paths`;\n\
     a `.tl` source anywhere on the path beats a declaration, so nothing here can shadow\n\
     an implementation, and a second declaration of the same module is reported\n\
     (`duplicate-declaration`) rather than silently losing to one of them.\n\n\
     Files htl writes here are the ones the project *publishes*: the module a\n\
     `---@contract` type is declared in, for the authors of the modules that contract\n\
     holds. Declarations generated from this crate's own Rust (`#[host_module]`) are\n\
     written next to the scripts, not here. Both are committed.\n\n\
     So is `<crate>/`, when there is one: a dependency that names its declarations in\n\
     `[package.metadata.htl] dts` has them copied there by `htl dts` (and by check / run\n\
     / test). Edit the crate, not the copy — the next run writes it again.\n"
        .to_string()
}

/// The project's `htl.toml`.
///
/// It names only keys the htl the project pins can read. `HtlConfig` is
/// `deny_unknown_fields` and `include_tl!` parses this file with the pinned crate, so a
/// key that crate does not carry is not ignored there but fatal, at the project's first
/// `cargo build`. The pin is this CLI's own htl (see [`HtlPin::default`]), which reads
/// every key this file writes; `[toolchain]` was the key that taught this, written for a
/// release that did not have it while the scaffold pinned releases by number.
/// `[toolchain]` is otherwise the one key the scaffold does not write: it fixes the exact
/// `htl` that may check the project, and a fresh project has no reason to refuse a newer
/// one. `[lint]` is also left out rather than filled with defaults: the shape is a level
/// or a table per rule, the defaults are in the checker, and a written-out copy would be
/// a copy to keep in step. The comments below name neither and send the reader to
/// `htl check --list-lints`, which answers from the binary they have.
///
/// The commented `[check] paths` example names one relative directory and nothing else.
/// A `~/...` entry resolves (see `htl::config::resolve_path`) and the README's `htl.toml`
/// sample still shows one, but this line is written into every project htl scaffolds, and
/// a commit-time scanner that looks for absolute or home-relative paths in committed
/// configuration flags it there — in a file the author did not write and whose commented
/// line does nothing. An example that costs every new project an exemption is the wrong
/// example; the feature is documented where a reader goes looking for it.
///
/// `[build] target` is written whenever the project has a target. `htl init --target
/// <name>` on a project that already has an `htl.toml` keeps that file and therefore does
/// not add the key; a project that predates the key adds the `[build]` section by hand,
/// as the README's `htl.toml` sample shows it. (#194 had sketched an `htl init --check`
/// that would have said so; #201 closed #194 without it, so nothing in the CLI reports
/// the key as missing.)
fn t_htl_toml(target: Option<BuildTarget>) -> String {
    let mut s = String::from(
        "# htl project settings (htl check / htl test / htl fmt / include_tl! all read this).\n\
     # Command-line flags and HTL_LINTS / HTL_LINT override it.\n\n\
     [lint]\n\
     # strict = true   # warnings and lints fail htl check, fix, build and include_tl!\n\
     #                   (not test / run / gen); a rule at deny fails them without it\n\n\
     # Per rule: htl check --list-lints names every rule with the level it has by\n\
     # default, and the README's \"Lints\" section says how to change one.\n\n\
     [fmt]\n\
     indent = 3\n\n\
     [check]\n\
     # paths = [\"mods\"]   # extra dirs require() resolves from while checking\n\
     # ([layout] source and types are searched, src/ and types/ by default;\n\
     #  hand-written .d.tl go under types/)\n\n\
     # Where this project accepts modules written outside it:\n\
     # [[contract]]\n\
     # dir = \"mods\"             # relative to this file; \"sites/*\" = each subdirectory\n\
     # module = \"Site\"          # optional: only this module name in each dir\n\
     #\n\
     # The shape those modules must have is declared on the record itself, so the two\n\
     # cannot drift apart:\n\
     #\n\
     #   local record defs\n\
     #      record Mod              ---@contract     -- inherits `dir` above;\n\
     #         name: string         ---@required     -- ---@contract(\"other\") overrides it\n\
     #         monsters: {Monster}  ---@required\n\
     #         factions: {Faction}                   -- unmarked: for the mods that want it\n\
     #      end\n\
     #   end\n\
     #\n\
     # The host must enforce it too: htl::pkg::contract_resolvers(root, &config).\n\
     # `htl check` reports `contract-unenforced` when that call is not in the Rust sources.\n\
     # enforced_by = \"mods/_validate.lua\"   # ...or name where it is enforced instead,\n\
     #                          # for a Lua-side validator, a sibling crate, generated\n\
     #                          # code. The file has to exist; a missing one is reported.\n",
    );
    if let Some(t) = target {
        s.push_str(&format!(
            "\n[build]\n\
             # What runs this project's output: hb (the htl binary, the default when absent), bin,\n\
             # cdylib, window. Written by htl new --target; see README \"Build targets\".\n\
             target = \"{t}\"\n"
        ));
    }
    s
}
/// `mise.toml`: the htl *command* this project was written by, for a version manager to
/// hold it to — the same number `Cargo.toml` pins for the crate, in the file mise
/// (<https://mise.jdx.dev>) reads. `Some` under a release pin only. `main` and a checkout
/// name a tree, and a tree is not something mise installs; a project written by a
/// development build is tied to that tree anyway, and the person who built it has it.
///
/// Why the scaffold writes it at all: `[toolchain] htl` refuses a command outside its
/// requirement and names `cargo install htl-cli` as the way out, which is one binary in
/// `$CARGO_HOME/bin` — right for one project, a swap for two. A per-directory pin is what
/// every other toolchain hands to a version manager (`.ruby-version`, `.nvmrc`,
/// `rust-toolchain.toml`), and mise carries htl with nothing registered: its `cargo:`
/// backend installs any crates.io crate. Written unconditionally rather than behind a
/// flag, the way Rails writes `.ruby-version`: the reader who would pass the flag already
/// knows to run `mise use`, and the file is four lines and inert without mise.
///
/// `cargo:` rather than `github:`, so the command is pinned in the same registry as the
/// crate; mise takes the prebuilt release binary through that backend anyway when
/// `cargo-binstall` is installed, since cargo-dist's asset names are binstall's defaults.
fn t_mise(pin: &HtlPin) -> Option<String> {
    let HtlPin::Release(v) = pin else {
        return None;
    };
    Some(format!(
        "# The htl this project was written by. mise (https://mise.jdx.dev) reads this file:\n\
         # `mise install` puts that release on PATH here, whatever `htl` is elsewhere.\n\
         [tools]\n\
         \"cargo:htl-cli\" = \"{v}\"\n"
    ))
}

fn t_gitignore(target: Option<&'static TargetProfile>, ctx: &Ctx<'_>) -> String {
    // `.htl/` holds the run cache and the installed deps: generated, machine-local, and
    // keyed on absolute paths, so it is never worth sharing. One line covers both.
    let mut s = String::from(".htl/\n*.hb\n");
    for line in target.into_iter().flat_map(|t| t.ignore) {
        s.push_str(&fill(line, ctx));
        s.push('\n');
    }
    s
}

/// The project README: the part every project has, with the target's own lines spliced
/// into the command block and its own paragraphs after it.
fn t_readme(ctx: &Ctx<'_>, target: Option<&'static TargetProfile>) -> String {
    let (name, m) = (ctx.name, ctx.module);
    let mut s = format!(
        "# {name}\n\nTeal project managed with [htl](https://github.com/ynishi/htl).\n\n```sh\n"
    );
    // With a dependency in the manifest the fetch is the first step, because until it has
    // run `require("htlx.*")` resolves to nothing and every other command below is red.
    if ctx.htlx {
        s.push_str("htl pkg install        # fetch [deps] from mlua-pkg.toml — first, htlx is one of them\n");
    }
    s.push_str("htl check .            # type-check + lints\n");
    if ctx.script && target.is_none() {
        s.push_str("htl run src/main.tl    # run the entry script\n");
    }
    s.push_str("htl test               # every .tl that loads htl.test\nhtl fmt .              # whitespace formatter\n");
    if !ctx.htlx {
        s.push_str("htl pkg install        # fetch [deps] from mlua-pkg.toml\n");
    }
    if let Some(t) = target {
        s.push_str(&(t.readme_commands)(ctx));
    }
    s.push_str(&format!(
        "```\n\nModule: `src/{m}/init.tl` (`require(\"{m}\")` from `src/` and `tests/`).\n\n"
    ));
    if ctx.htlx {
        s.push_str(&format!(
            "`htlx` ([htl-x]({HTLX_REPOSITORY}) {HTLX_TAG}) is a dependency from the start: the collections\n\
             Lua does not have — `htlx.list` over arrays, `htlx.tablex` over maps, `htlx.seq` over\n\
             iterators, `htlx.ordered` for insertion-ordered maps and sets — as `require(\"htlx.list\")`\n\
             and the rest, once `htl pkg install` has run. Drop the line from `mlua-pkg.toml` if it\n\
             is not wanted (`htl new --no-x` writes the project without it).\n"
        ));
        s.push('\n');
    }
    s.push_str(&format!(
        "`mlua-pkg.toml` `entry = \"src/{m}\"` only matters to *consumers* that depend on this\n\
         package through mlua-pkg: they get it as `require(\"{name}\")`. "
    ));
    match target {
        Some(t) => s.push_str(&(t.readme_prose)(ctx)),
        None => s.push_str("Ignore it if nobody depends on this package.\n"),
    }
    s
}

fn rust_readme_commands(ctx: &Ctx<'_>) -> String {
    let mut s = String::new();
    if ctx.script {
        s.push_str("cargo run              # the binary: preload, then src/main.tl (type-checked at build)\n");
        s.push_str("                       # (src/main.tl requires the Rust `host`, so `htl run` cannot run it)\n");
    }
    s.push_str(
        "cargo test             # the library's Rust test: the module loaded through preload\n",
    );
    s
}

fn rust_readme_prose(ctx: &Ctx<'_>) -> String {
    let mut s = String::from(
        "The Rust host is a library:\n`src/lib.rs` holds the `#[host_module]`, embeds this module, and registers both in\n\
         `preload(&Htl)`. ",
    );
    if ctx.script {
        s.push_str(
            "`src/main.rs` is a few lines on top of it — `preload`, then the entry\nscript. Grow the library, not the binary.\n\n",
        );
    } else {
        s.push_str(
            "There is no binary: call `preload` from whatever embeds this\ncrate, and grow the library.\n\n",
        );
    }
    s.push_str(HOST_DTL);
    s
}

/// The generated-declaration paragraph, which every target that writes a `#[host_module]`
/// says the same way.
const HOST_DTL: &str = "`src/host.d.tl` is generated from `#[host_module]` in `src/lib.rs`: `cargo build` writes it,\n\
     and so does `htl dts` / `htl check` without building, so the Teal side always sees the\n\
     current Rust signatures.\n";

fn ffi_readme_commands(ctx: &Ctx<'_>) -> String {
    format!(
        "cargo test             # the library's Rust tests: preload, and the generated header\n\
         cargo build            # the library, and include/{}.h from #[c_export]\n\
         make -C examples/c run          # the C caller   (after cargo build)\n\
         python3 examples/python/run.py  # the Python caller, the same round trip\n",
        ctx.module
    )
}

fn ffi_readme_prose(ctx: &Ctx<'_>) -> String {
    let m = ctx.module;
    let mut s = String::from(
        "This project is a library with two boundaries:\n\
         `src/lib.rs` holds the `#[host_module]` the *scripts* call and the `#[c_export]` block a\n\
         *caller that is not written in Rust* calls. There is no binary — a C ABI library has no\n\
         entry point of its own, which is why `--target cdylib` implies `--lib`.\n\n",
    );
    s.push_str(HOST_DTL);
    s.push_str(&format!(
        "\n## The C ABI\n\n\
         `cargo build` writes `include/{m}.h` from the same `impl` block, and leaves\n\
         `target/debug/lib{m}.{{so,dylib,dll}}` for a caller to load and `lib{m}.a` to link\n\
         statically (Unity on iOS wants the latter). Commit the header: it is generated, and so is\n\
         `src/host.d.tl`, and both are what someone reads without building this crate.\n\n\
         Everything that crosses is an opaque `{m}_handle *`, a `char *` this library allocated,\n\
         or an `int`. Three rules cover the whole ABI:\n\n\
         - **Every `char *` returned is yours to free**, with `{m}_free()` and nothing else. The\n\
           call that produced it is not finished until you do.\n\
         - **An `int` is a status, never a value** (`{}_OK` and friends, in the header). A call\n\
           that has both writes the value through an `int *out`.\n\
         - **One handle, one thread.** Using it from another answers `WRONG_THREAD`; the exception\n\
           is `{m}_interrupt()`, which any thread may call to stop a runaway script.\n\n\
         A failed call answers `NULL` or a status, and `{m}_last_error()` is the message —\n\
         a pointer valid until the next call *on that thread*, so copy it (or use\n\
         `{m}_last_error_into()`) rather than keeping it.\n\n\
         `examples/c/` and `examples/python/` are two callers doing the same round trip: open,\n\
         a text call, a JSON call, the two error paths, `free`, close. Each is written the way its\n\
         own language gets this wrong by default — see the comment at the top of both.\n",
        m.to_uppercase()
    ));
    s
}

/// What a window project is told to run, in the order a fresh clone has to run it:
/// `htl check` before `cargo build`, because the first is what writes the declarations the
/// second links against.
fn window_readme_commands(_ctx: &Ctx<'_>) -> String {
    String::from(
        "cargo run              # the window; Esc quits\n\
         HTL_MQ_FRAMES=60 HTL_MQ_SHOT=out.png cargo run   # sixty frames, then a PNG\n\
         cargo test             # the engine's Rust test: the module loaded through preload\n",
    )
}

fn window_readme_prose(ctx: &Ctx<'_>) -> String {
    let m = ctx.module;
    let mut s = format!(
        "This project is a library, a binary and an engine:\n\
         `src/lib.rs` holds `fx` — the project's own `#[host_module]`, for what wants the GPU —\n\
         embeds the Teal engine, and registers both (plus htl-mq's `mq`) in `preload(&Htl)`.\n\
         `src/main.rs` opens the window and hands `htl_mq::run` the game table, and `src/main.tl`\n\
         is that table: `update(dt)` says whether to go on, `draw()` draws.\n\n\
         `src/{m}/init.tl` is the engine, and it is where the game goes. It takes its world as\n\
         arguments and never opens anything, so `htl test` runs it with no display: `require(\"mq\")`\n\
         resolves to the declaration, which declares and does nothing. `render` is the one function\n\
         that draws, and nothing in the engine calls it — the loop does.\n\n\
         Effects go into `fx`, beside `mq` rather than inside the engine: `mq` is macroquad's\n\
         drawing and input as htl-mq ships it, and `fx` is this project's, drawing with the same\n\
         macroquad through `htl_mq::macroquad`. A new one is a method on `Fx` and a line in\n\
         `render`.\n\n"
    );
    s.push_str(
        "`src/fx.d.tl` is generated from `#[host_module]` in `src/lib.rs`: `cargo build` writes it,\n\
         and so does `htl dts` / `htl check` without building, so the Teal side always sees the\n\
         current Rust signatures. `types/htl-mq/mq.d.tl` is the same file for the dependency's `mq`,\n\
         copied in from the crate by `htl check`. Commit both; the next run writes them again.\n\n\
         `cargo build` reads `types/htl-mq/mq.d.tl` — `include_bundle!` links `mq` against it — so\n\
         `htl check .` comes first in a fresh clone.\n",
    );
    s
}

/// One dependency's right-hand side: the short `"req"` form where cargo accepts it, the
/// table where it does not.
///
/// A bare version with no features is the only thing the short form can say, so a git or a
/// path pin, or anything with features on it, is the table — and the features are appended
/// *here*, once, rather than beside each way of spelling the requirement. That is the whole
/// reason [`HtlPin::keys_for`] hands back pairs instead of a finished line: the `cdylib`
/// target's `features = ["ffi"]` has to survive all three pin kinds, and the way to be sure
/// it does is for there to be one place it is written.
fn dep_value(keys: &[(&str, String)], features: &[&str]) -> String {
    if features.is_empty()
        && let [("version", v)] = keys
    {
        return format!("\"{v}\"");
    }
    let mut parts: Vec<String> = keys.iter().map(|(k, v)| format!("{k} = \"{v}\"")).collect();
    if !features.is_empty() {
        let feats: Vec<String> = features.iter().map(|f| format!("\"{f}\"")).collect();
        parts.push(format!("features = [{}]", feats.join(", ")));
    }
    format!("{{ {} }}", parts.join(", "))
}

/// The project's `Cargo.toml`, assembled from the profile: crate shape, then dependencies,
/// then the one profile setting every target with Rust in it needs.
fn t_cargo(name: &str, target: &TargetProfile, htl: &HtlPin) -> String {
    let mut s = format!(
        "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n# authors / license / repository: fill in yourself\n\n"
    );
    if !target.target.crate_types().is_empty() {
        let types: Vec<String> = target
            .target
            .crate_types()
            .iter()
            .map(|t| format!("\"{t}\""))
            .collect();
        s.push_str(&format!("[lib]\ncrate-type = [{}]\n\n", types.join(", ")));
    }
    s.push_str("[dependencies]\n");
    for d in target.deps {
        let keys = match d.req {
            Dep::Htl => htl.keys_for("htl"),
            Dep::Sibling(n) => htl.keys_for(n),
            Dep::Version(v) => vec![("version", v.to_string())],
        };
        s.push_str(&format!("{} = {}\n", d.name, dep_value(&keys, d.features)));
    }
    s.push_str(
        "\n# The Teal checker runs inside htl's proc macros; the dev profile would build it\n\
         # unoptimised and make every `cargo build` that touches a .tl about 3x slower.\n\
         [profile.dev.build-override]\nopt-level = 3\n",
    );
    s
}

#[cfg(test)]
mod tests {
    use super::{
        BuildTarget, Ctx, DEFAULT_TARGET, HTLX_REPOSITORY, HTLX_TAG, HtlPin, LUA_KEYWORDS, Options,
        PIN_DEFAULT, Path, PathBuf, REPOSITORY, RUST_KEYWORDS, Result, dep_value, ffi_lib_rs,
        module_ident, plan, profile, refuse_reserved_name, resolve_target, rust_lib_rs,
        rust_main_rs, script_mismatch, t_cargo, t_htl_toml, t_manifest, t_mise, t_readme,
        target_names, window_lib_rs, window_main_rs,
    };
    use htl::build_target::Script;

    /// The default is what `build.rs` decided from where this binary was built, and each
    /// answer names a tree that holds the htl this binary links: the release at this
    /// crate's own version, the repository, or a checkout with `crates/htl` in it. The
    /// test binary is built in this checkout, so the answer here is `path` unless
    /// `HTL_PIN_DEFAULT` said otherwise at build time — either way, the answer and the
    /// pin agree.
    #[test]
    fn the_default_pin_is_where_this_binary_was_built_from() {
        match (PIN_DEFAULT, HtlPin::default()) {
            ("release", HtlPin::Release(v)) => assert_eq!(v, env!("CARGO_PKG_VERSION")),
            ("main", HtlPin::Main) => {}
            ("path", HtlPin::Path(root)) => {
                assert!(root.is_absolute(), "{}", root.display());
                assert!(
                    root.join("crates").join("htl").join("Cargo.toml").exists(),
                    "{} is not a checkout of this repository",
                    root.display()
                );
                // The checkout is this one: the test binary and the crate under test come
                // from the same tree.
                let here = std::fs::canonicalize(
                    std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."),
                )
                .unwrap();
                assert_eq!(std::fs::canonicalize(&root).unwrap(), here);
            }
            (kind, pin) => panic!("HTL_PIN_DEFAULT={kind} but the default is {pin:?}"),
        }
    }

    #[test]
    fn a_pin_is_the_default_main_or_a_checkout() {
        assert_eq!(HtlPin::parse(None).unwrap(), HtlPin::default());
        assert_eq!(HtlPin::parse(Some("main")).unwrap(), HtlPin::Main);
        assert_eq!(
            HtlPin::parse(Some("path:x")).unwrap(),
            HtlPin::Path(PathBuf::from("x"))
        );
    }

    /// A number is refused — this CLI writes for the htl it links and no other — and the
    /// refusal says where that release's scaffold is. A typo gets the same answer, and an
    /// empty `path:` its own.
    #[test]
    fn a_number_is_refused_with_the_release_cli_that_writes_for_it() {
        let e = err(HtlPin::parse(Some("0.5")));
        assert!(e.contains("unsupported htl `0.5`"), "{e}");
        assert!(e.contains("`main` or `path:<checkout>`"), "{e}");
        assert!(e.contains(&HtlPin::default().requirement()), "{e}");
        assert!(e.contains("cargo install htl-cli --version 0.5"), "{e}");
        assert!(err(HtlPin::parse(Some("nope"))).contains("unsupported htl `nope`"));
        assert!(err(HtlPin::parse(Some("path:"))).contains("names no checkout directory"));
    }

    /// What each pin puts on the right of `htl = `, with and without the features a target
    /// asks for. The exact text, because this is the line a user's `cargo build` reads.
    #[test]
    fn each_pin_writes_its_own_dependency_line() {
        let release = HtlPin::Release("0.6.0".into());
        let path = HtlPin::Path(PathBuf::from("../co"));
        assert_eq!(release.requirement(), "\"0.6.0\"");
        assert_eq!(
            HtlPin::Main.requirement(),
            format!("{{ git = \"{REPOSITORY}\", branch = \"main\" }}")
        );
        assert_eq!(path.requirement(), "{ path = \"../co/crates/htl\" }");

        // The repository URL comes from the package metadata, so an inherit that stopped
        // reaching this crate would write `git = ""` rather than fail to compile.
        assert!(REPOSITORY.contains("://"), "{REPOSITORY}");

        // With features, every kind is the table form and the features go last.
        let ffi = ["ffi"];
        assert_eq!(
            dep_value(&release.keys(), &ffi),
            "{ version = \"0.6.0\", features = [\"ffi\"] }"
        );
        assert_eq!(
            dep_value(&HtlPin::Main.keys(), &ffi),
            format!("{{ git = \"{REPOSITORY}\", branch = \"main\", features = [\"ffi\"] }}")
        );
        assert_eq!(
            dep_value(&path.keys(), &ffi),
            "{ path = \"../co/crates/htl\", features = [\"ffi\"] }"
        );
    }

    /// The host's `preload` installs `std.*` before the project's own module, in both
    /// hosts.
    #[test]
    fn the_rust_host_installs_std() {
        let ctx = Ctx {
            name: "sample",
            module: "sample",
            script: true,
            htlx: false,
        };
        let lib = rust_lib_rs(&ctx);
        assert!(
            lib.contains(
                "    Host.htl_preload(h)?;\n    // `std.*`: json, string, path and the rest"
            ),
            "{lib}"
        );
        assert!(lib.contains("    h.install_std()?;\n"), "{lib}");
        assert!(!lib.contains("{{"), "{lib}");
        // The C ABI host is a Rust host too, and gets the same line.
        let ffi = ffi_lib_rs(&ctx);
        assert!(ffi.contains("    h.install_std()?;\n"), "{ffi}");
    }

    /// The host embeds its module as the require closure — `include_bundle!` in both
    /// hosts, `install_bundle` in `preload` — and the binary runs the entry the same way.
    /// One body each, with no placeholder left: there was a one-file host
    /// (`include_tl_bytes!` / `preload_bytes` / `exec`) for a release whose linker could
    /// not serve a bundle, while one CLI wrote for a window of releases.
    #[test]
    fn the_rust_host_embeds_its_module_as_a_bundle() {
        let ctx = Ctx {
            name: "sample",
            module: "sample",
            script: true,
            htlx: true,
        };
        let lib = rust_lib_rs(&ctx);
        assert!(
            lib.contains("include_bundle!(\"src/sample/init.tl\");"),
            "{lib}"
        );
        assert!(
            lib.contains("h.install_bundle(&htl::bundle::Bundle::decode(BUNDLE)?)?;"),
            "{lib}"
        );
        assert!(
            !lib.contains("include_tl_bytes") && !lib.contains("{{"),
            "{lib}"
        );
        let ffi = ffi_lib_rs(&ctx);
        assert!(
            ffi.contains("include_bundle!(\"src/sample/init.tl\"") && !ffi.contains("{{"),
            "{ffi}"
        );
        let main = rust_main_rs(&ctx);
        assert!(
            main.contains("include_bundle!(\"src/main.tl\", host = [\"sample\"], debug = true)")
                && main.contains("h.run_bundle(&Bundle::decode(MAIN)?, &args)?;"),
            "{main}"
        );
        assert!(
            !main.contains("set_arg") && !main.contains("h.exec(") && !main.contains("{{"),
            "{main}"
        );
    }

    /// The manifest under its two shapes: the `htlx` line right under `[deps]`, and the
    /// bare template with `--no-x` — whatever the pin. The line is asserted whole because
    /// it is what a user's `htl pkg install` fetches.
    #[test]
    fn the_manifest_names_htlx_unless_no_x_is_given() {
        let opts = |htl: HtlPin, no_x: bool| Options {
            lib: false,
            target: None,
            htl,
            no_x,
        };
        let ctx = |o: &Options| Ctx {
            name: "sample",
            module: "sample",
            script: true,
            htlx: o.writes_htlx(),
        };
        let opted_out = opts(HtlPin::Release("0.6.0".into()), true);
        let bare = t_manifest(&ctx(&opted_out));
        assert!(!bare.contains("htlx"), "{bare}");
        assert!(bare.contains("[deps]\n# lshape"), "{bare}");

        let main = opts(HtlPin::Main, false);
        let with = t_manifest(&ctx(&main));
        // A release pin writes the same line: the pin has no say in the manifest.
        let release = opts(HtlPin::Release("0.6.0".into()), false);
        assert_eq!(t_manifest(&ctx(&release)), with);
        let line = format!(
            "[deps]\nhtlx = {{ git = \"{HTLX_REPOSITORY}\", tag = \"{HTLX_TAG}\" }}\n# lshape"
        );
        assert!(with.contains(&line), "{with}");
        // Everything but that one line is the bare manifest.
        assert_eq!(with.replacen(&line, "[deps]\n# lshape", 1), bare);

        let main_opted_out = opts(HtlPin::Main, true);
        assert_eq!(t_manifest(&ctx(&main_opted_out)), bare);

        // The tag is a tag, not a floating prefix: three numbers, `v` in front.
        let n: Vec<&str> = HTLX_TAG.trim_start_matches('v').split('.').collect();
        assert!(
            HTLX_TAG.starts_with('v') && n.len() == 3 && n.iter().all(|p| p.parse::<u64>().is_ok()),
            "HTLX_TAG {HTLX_TAG} is not an exact vX.Y.Z tag"
        );
    }

    /// With the dependency in the manifest the README's first command is the fetch, and
    /// the fetch appears once; without it the block is the one every project has had.
    #[test]
    fn the_readme_puts_the_fetch_first_when_there_is_something_to_fetch() {
        let ctx = |htlx| Ctx {
            name: "sample",
            module: "sample",
            script: true,
            htlx,
        };
        let with = t_readme(&ctx(true), None);
        let block: Vec<&str> = with.lines().skip_while(|l| *l != "```sh").skip(1).collect();
        assert!(block[0].starts_with("htl pkg install"), "{with}");
        // Once in the command block; the prose may name it again.
        let fetches = block
            .iter()
            .take_while(|l| **l != "```")
            .filter(|l| l.starts_with("htl pkg install"))
            .count();
        assert_eq!(fetches, 1, "{with}");
        assert!(with.contains("`htlx` ([htl-x]("), "{with}");
        assert!(with.contains("htl new --no-x"), "{with}");

        let without = t_readme(&ctx(false), None);
        let block: Vec<&str> = without
            .lines()
            .skip_while(|l| *l != "```sh")
            .skip(1)
            .collect();
        assert!(block[0].starts_with("htl check ."), "{without}");
        assert!(!without.contains("htlx"), "{without}");
    }

    /// The answer to that question, as bytes. Without a target the file is the one every
    /// project has had, and with one the section is appended verbatim — comment lines
    /// included, because they are what the next reader of the file learns the key from.
    #[test]
    fn the_config_records_the_target() {
        let block = |name: &str| {
            format!(
                "\n[build]\n\
                 # What runs this project's output: hb (the htl binary, the default when absent), bin,\n\
                 # cdylib, window. Written by htl new --target; see README \"Build targets\".\n\
                 target = \"{name}\"\n"
            )
        };
        let plain = t_htl_toml(None);
        assert!(!plain.contains("[build]"), "{plain}");

        let bin = t_htl_toml(Some(BuildTarget::Bin));
        assert_eq!(bin, format!("{plain}{}", block("bin")));

        let cdylib = t_htl_toml(Some(BuildTarget::Cdylib));
        assert_eq!(cdylib, format!("{plain}{}", block("cdylib")));

        let window = t_htl_toml(Some(BuildTarget::Window));
        assert_eq!(window, format!("{plain}{}", block("window")));
    }

    /// `--embed` resolves through the registry, so a missing entry is a panic at the
    /// first scaffold rather than a file that quietly stops being written.
    #[test]
    fn the_registry_holds_the_target_embed_asks_for() {
        assert!(target_names().contains(&DEFAULT_TARGET.name()));
        let bin = profile(DEFAULT_TARGET).unwrap();
        assert_eq!(bin.lib.path, "src/lib.rs");
        assert_eq!(bin.main.as_ref().unwrap().path, "src/main.rs");
        // The default target is the one shape that works either way.
        assert!(bin.target.entry().accepts(true) && bin.target.entry().accepts(false));
    }

    /// `hb` is a build target and not a scaffold: it is the tree `htl new` writes with no
    /// Rust in it, so the registry has no entry for it and the flag does not offer it.
    #[test]
    fn the_default_build_target_has_no_profile_and_is_not_offered() {
        assert!(profile(BuildTarget::Hb).is_none());
        assert!(!target_names().contains(&"hb"));
        let e = err(resolve_target(Some("hb"), false, false));
        assert!(
            e.contains("the `hb` target is what plain `htl new` writes"),
            "{e}"
        );
        assert!(
            e.contains("targets that scaffold: bin, cdylib, window"),
            "{e}"
        );
    }

    /// The refusal, as a string. A plain `unwrap_err()` would ask `&TargetProfile` for
    /// `Debug` — a derive on the whole registry to print a message no passing test sees.
    fn err<T>(r: Result<T>) -> String {
        r.err().expect("expected a refusal").to_string()
    }

    #[test]
    fn embed_and_target_bin_are_the_same_request() {
        let by_flag = resolve_target(None, true, false).unwrap().unwrap();
        let by_name = resolve_target(Some("bin"), false, false).unwrap().unwrap();
        assert_eq!(by_flag.target, by_name.target);
        // Both, agreeing, is not an error.
        assert!(resolve_target(Some("bin"), true, false).is_ok());
    }

    #[test]
    fn an_unknown_target_is_refused_with_the_registered_names() {
        // `.err().unwrap()`, not `unwrap_err()`: the Ok side is a `&TargetProfile`, and
        // making the registry `Debug` for the sake of a test message is the wrong trade.
        let e = err(resolve_target(Some("nope"), false, false));
        assert!(e.contains("unknown target `nope`"), "{e}");
        for n in target_names() {
            assert!(e.contains(n), "{e}");
        }
    }

    #[test]
    fn embed_disagreeing_with_target_is_refused() {
        let e = err(resolve_target(Some("other"), true, false));
        assert!(
            e.contains("--embed is the shorthand for --target bin"),
            "{e}"
        );
    }

    /// Both halves of the matrix hole, with the message that names a way out: `cdylib`
    /// answers [`Script::Forbids`], so `--lib` is what it needs, and `window` answers
    /// [`Script::Requires`], so `--lib` is what it cannot have. Each refusal lists the
    /// targets that would have fitted the flag as given, which is the half of the registry
    /// the other one is not in.
    #[test]
    fn a_target_that_disagrees_with_lib_names_the_targets_that_do_not() {
        assert!(Script::Requires.accepts(false) && !Script::Requires.accepts(true));

        let msg = script_mismatch(profile(BuildTarget::Cdylib).unwrap(), false);
        assert!(
            msg.contains("the `cdylib` target writes no entry script"),
            "{msg}"
        );
        assert!(msg.contains("targets that write one: bin, window"), "{msg}");

        let msg = script_mismatch(profile(BuildTarget::Window).unwrap(), true);
        assert!(
            msg.contains("the `window` target runs an entry script, which --lib leaves out"),
            "{msg}"
        );
        assert!(
            msg.contains("targets that work with --lib: bin, cdylib"),
            "{msg}"
        );
    }

    /// A C ABI library is not a project with an entry script, and the two are reconciled
    /// before anything is written rather than at the first file.
    #[test]
    fn the_cdylib_target_is_refused_without_lib_and_taken_with_it() {
        let e = err(resolve_target(Some("cdylib"), false, false));
        assert!(e.contains("so it needs --lib"), "{e}");
        let ffi = resolve_target(Some("cdylib"), false, true)
            .unwrap()
            .unwrap();
        assert_eq!(ffi.target, BuildTarget::Cdylib);
        // No binary to write, and the reference callers travel with the profile.
        assert!(ffi.main.is_none());
        let paths: Vec<&str> = ffi.extra.iter().map(|f| f.path).collect();
        assert_eq!(
            paths,
            vec![
                "examples/c/main.c",
                "examples/c/Makefile",
                "examples/python/run.py"
            ]
        );
    }

    /// The C ABI needs a shared object to load and a static library to link, and the
    /// runtime the generated wrappers call is behind a feature, so the dependency line
    /// is the table form rather than a bare requirement.
    #[test]
    fn the_cdylib_cargo_toml_is_a_c_library_with_the_ffi_feature() {
        let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
        let toml = t_cargo("sample", profile(BuildTarget::Cdylib).unwrap(), &release);
        assert!(
            toml.contains("[lib]\ncrate-type = [\"rlib\", \"cdylib\", \"staticlib\"]\n"),
            "{toml}"
        );
        assert!(
            toml.contains(&format!(
                "htl = {{ version = \"{}\", features = [\"ffi\"] }}\n",
                env!("CARGO_PKG_VERSION")
            )),
            "{toml}"
        );
        assert!(
            toml.contains("serde = { version = \"1\", features = [\"derive\"] }\n"),
            "{toml}"
        );
    }

    /// The same manifest under the other two pins. The assertions are whole lines, which is
    /// how they also say that neither pin left a `version` key behind for cargo to
    /// reconcile with a branch or a directory.
    #[test]
    fn the_cdylib_feature_survives_every_pin_kind() {
        let ffi = profile(BuildTarget::Cdylib).unwrap();
        let toml = t_cargo("sample", ffi, &HtlPin::Main);
        assert!(
            toml.contains(&format!(
                "\nhtl = {{ git = \"{REPOSITORY}\", branch = \"main\", features = [\"ffi\"] }}\n"
            )),
            "{toml}"
        );
        let toml = t_cargo("sample", ffi, &HtlPin::Path(PathBuf::from("../co")));
        assert!(
            toml.contains("\nhtl = { path = \"../co/crates/htl\", features = [\"ffi\"] }\n"),
            "{toml}"
        );
    }

    /// A crate of this repository beside `htl` follows the same pin, whatever kind it is:
    /// a release version, the same branch of the same git URL, the checkout's own
    /// `crates/htl-mq`. The two lines are compared key for key rather than asserted
    /// separately, because the failure this guards is one line being right and the other
    /// naming a different tree — two htls in one build, which cargo resolves and the
    /// linker does not.
    #[test]
    fn a_sibling_crate_follows_the_htl_pin() {
        let window = profile(BuildTarget::Window).unwrap();
        for pin in [
            HtlPin::Release("0.7.0".into()),
            HtlPin::Main,
            HtlPin::Path(PathBuf::from("../co")),
        ] {
            let toml = t_cargo("sample", window, &pin);
            let line = |name: &str| -> String {
                toml.lines()
                    .find(|l| l.starts_with(&format!("{name} = ")))
                    .unwrap_or_else(|| panic!("no `{name}` dependency in:\n{toml}"))
                    .to_string()
            };
            let htl = line("htl");
            let mq = line("htl-mq");
            let want = match &pin {
                HtlPin::Release(v) => (format!("htl = \"{v}\""), format!("htl-mq = \"{v}\"")),
                HtlPin::Main => (
                    format!("htl = {{ git = \"{REPOSITORY}\", branch = \"main\" }}"),
                    format!("htl-mq = {{ git = \"{REPOSITORY}\", branch = \"main\" }}"),
                ),
                HtlPin::Path(_) => (
                    "htl = { path = \"../co/crates/htl\" }".to_string(),
                    "htl-mq = { path = \"../co/crates/htl-mq\" }".to_string(),
                ),
            };
            assert_eq!(
                (htl.as_str(), mq.as_str()),
                (want.0.as_str(), want.1.as_str())
            );
        }
    }

    /// The window target is a binary with a window on it: no `[lib]` section, an
    /// `src/main.rs`, and the two host modules the templates name — the dependency's `mq`
    /// and the project's own `fx` — registered in one `preload`.
    #[test]
    fn the_window_target_is_a_binary_with_two_host_modules() {
        let window = resolve_target(Some("window"), false, false)
            .unwrap()
            .unwrap();
        assert_eq!(window.target, BuildTarget::Window);
        assert_eq!(window.main.as_ref().unwrap().path, "src/main.rs");
        assert!(window.extra.is_empty());

        let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
        let toml = t_cargo("sample", window, &release);
        assert!(!toml.contains("[lib]"), "{toml}");
        assert!(toml.contains("anyhow = \"1\"\n"), "{toml}");

        let ctx = Ctx {
            name: "sample",
            module: "sample",
            script: true,
            htlx: false,
        };
        let lib = window_lib_rs(&ctx);
        assert!(
            lib.contains("#[host_module(name = \"fx\", dts = \"src/fx.d.tl\""),
            "{lib}"
        );
        assert!(
            lib.contains("htl::include_bundle!(\"src/sample/init.tl\", host = [\"mq\"])"),
            "{lib}"
        );
        assert!(
            lib.contains("Fx.htl_preload(h)?;") && lib.contains("htl_mq::Mq.htl_preload(h)?;"),
            "{lib}"
        );
        assert!(!lib.contains("{{"), "{lib}");

        // The binary opens the window and drives the entry script's table; it holds no
        // logic of its own, and the engine it links is the library's.
        let main = window_main_rs(&ctx);
        assert!(
            main.contains(
                "include_bundle!(\"src/main.tl\", host = [\"mq\", \"sample\"], debug = true)"
            ),
            "{main}"
        );
        assert!(
            main.contains("htl_mq::run(h, game, htl_mq::conf(\"sample\", 800, 600))"),
            "{main}"
        );
        assert!(!main.contains("{{"), "{main}");
    }

    /// The frame loop is handed the table `src/main.tl` returns, so `--lib` — which is
    /// "no entry script" — is refused, and before anything is written.
    #[test]
    fn the_window_target_is_refused_with_lib() {
        let e = err(resolve_target(Some("window"), false, true));
        assert!(
            e.contains("the `window` target runs an entry script, which --lib leaves out"),
            "{e}"
        );
    }

    /// What the reader is told to run follows the project rather than the target's name:
    /// the C ABI target points at the two reference callers, and the default target at the
    /// binary it writes only when there is a script to run.
    #[test]
    fn the_readme_commands_come_from_the_target() {
        let ctx = |script| Ctx {
            name: "sample",
            module: "sample",
            script,
            htlx: false,
        };
        let bin = profile(DEFAULT_TARGET).unwrap();
        assert!((bin.readme_commands)(&ctx(true)).contains("cargo run"));
        assert!(!(bin.readme_commands)(&ctx(false)).contains("cargo run"));

        let ffi = (profile(BuildTarget::Cdylib).unwrap().readme_commands)(&ctx(false));
        assert!(ffi.contains("make -C examples/c run"), "{ffi}");
        assert!(ffi.contains("python3 examples/python/run.py"), "{ffi}");
        assert!(ffi.contains("include/sample.h"), "{ffi}");

        // The window target has an entry script by construction, and the run that writes a
        // PNG is the one a script can check.
        let win = (profile(BuildTarget::Window).unwrap().readme_commands)(&ctx(true));
        assert!(win.contains("cargo run              # the window"), "{win}");
        assert!(
            win.contains("HTL_MQ_FRAMES=60 HTL_MQ_SHOT=out.png cargo run"),
            "{win}"
        );
    }

    /// A crate whose only shape is the default `rlib` has no `[lib]` section; a target
    /// that needs more gets one from [`BuildTarget::crate_types`], which is the whole of
    /// what `Cargo.toml` has to know about the crate shape.
    #[test]
    fn cargo_toml_takes_the_crate_shape_from_the_target() {
        let release = HtlPin::Release(env!("CARGO_PKG_VERSION").into());
        let toml = t_cargo("sample", profile(DEFAULT_TARGET).unwrap(), &release);
        assert!(!toml.contains("[lib]"), "{toml}");
        assert!(toml.contains("anyhow = \"1\"\n"), "{toml}");
        // A release pin is a plain requirement, so it takes the short form and the
        // `anyhow` beside it is unchanged by the pin being a table in the other tests.
        assert!(
            toml.contains(&format!("htl = \"{}\"\n", env!("CARGO_PKG_VERSION"))),
            "{toml}"
        );

        let toml = t_cargo("sample", profile(BuildTarget::Cdylib).unwrap(), &release);
        assert!(
            toml.contains("[lib]\ncrate-type = [\"rlib\", \"cdylib\", \"staticlib\"]\n"),
            "{toml}"
        );
    }

    /// The refusal, or the empty string when the name is taken. The name and its
    /// identifier are what [`refuse_reserved_name`] is asked about, and `module_ident` is
    /// the only thing that turns one into the other, so the tests below go through it
    /// rather than spelling identifiers by hand.
    fn refusal(name: &str, writes_cargo: bool) -> String {
        match refuse_reserved_name(name, &module_ident(name), writes_cargo) {
            Ok(()) => String::new(),
            Err(e) => e.to_string(),
        }
    }

    /// A Rust keyword is a crate name cargo refuses, so a project with a target is
    /// refused too, in cargo's own sentence — and a plain project, which rustc never
    /// reads, keeps the name.
    #[test]
    fn a_rust_keyword_is_refused_by_a_target_and_taken_by_a_plain_project() {
        let e = refusal("pub", true);
        assert!(
            e.starts_with("invalid project name `pub`: it is a Rust keyword"),
            "{e}"
        );
        assert!(e.contains("`pub::preload`"), "what htl does with it:\n{e}");
        assert!(e.contains("another name"), "the way out:\n{e}");
        assert!(refusal("match", true).contains("it is a Rust keyword"));

        // Neither is a Lua keyword, so the tree with no Rust in it is written.
        assert_eq!(refusal("pub", false), "");
        assert_eq!(refusal("match", false), "");
    }

    /// `gen` is the one name cargo's list does not hold and the 2024 edition does: the
    /// crate compiles nowhere, so the scaffold refuses it with the edition as the reason.
    #[test]
    fn a_2024_keyword_cargo_still_accepts_is_refused() {
        let e = refusal("gen", true);
        assert!(e.contains("reserved by Rust's 2024 edition"), "{e}");
        assert_eq!(refusal("gen", false), "");
    }

    /// The other half of what `cargo new` refuses: a leading digit and a character no
    /// crate name can hold. A plain project takes both — `module_ident` makes an
    /// identifier out of them, and nothing else reads the name.
    #[test]
    fn the_names_cargo_refuses_for_their_spelling_are_refused_too() {
        assert!(
            refusal("123abc", true).contains("the name cannot start with a digit"),
            "{}",
            refusal("123abc", true)
        );
        let e = refusal("my lib", true);
        assert!(e.contains("invalid character ` `"), "{e}");
        assert_eq!(refusal("123abc", false), "");
        assert_eq!(refusal("my lib", false), "");
    }

    /// Every target writes `src/main.tl`'s `local <mod> = require("<mod>")`, so a Lua
    /// keyword is refused whether or not there is a crate, and the message quotes the
    /// line that would not have parsed.
    #[test]
    fn a_lua_keyword_is_refused_by_every_target() {
        for name in ["end", "function", "local", "nil"] {
            for writes_cargo in [false, true] {
                let e = refusal(name, writes_cargo);
                assert!(
                    e.contains(&format!(
                        "invalid project name `{name}`: it is a Lua keyword"
                    )),
                    "{e}"
                );
            }
        }
        let e = refusal("end", false);
        assert!(e.contains("`local end = require(\"end\")`"), "{e}");
    }

    /// Teal's contextual words: the three that break the tree the scaffold writes are
    /// refused, and the six that do not are taken. Which is which was measured with this
    /// checkout's binary (the `TEAL_TYPE_WORDS` doc says how); this holds it in place.
    #[test]
    fn the_teal_words_refused_are_the_three_that_break_a_scaffolded_project() {
        for name in ["record", "enum", "interface"] {
            let e = refusal(name, false);
            assert!(
                e.contains(&format!(
                    "invalid project name `{name}`: it is how Teal opens a type declaration"
                )),
                "{e}"
            );
        }
        for name in ["type", "where", "is", "as", "global", "macroexp"] {
            // `type` and `enum` are Rust keywords as well, and a crate is where that is
            // answered; the Teal half takes them.
            assert_eq!(refusal(name, false), "", "{name}");
        }
    }

    /// A name a keyword is only part of, and one whose separator makes the identifier, are
    /// names the scaffold has always written and still does — the refusals above are
    /// exact matches, not substring searches.
    #[test]
    fn a_name_that_merely_contains_a_keyword_is_taken() {
        for name in ["pubs", "my-lib", "matcher", "ending", "sample"] {
            assert_eq!(refusal(name, true), "", "{name}");
            assert_eq!(refusal(name, false), "", "{name}");
        }
    }

    /// The two lists are copies of somebody else's set, and a copy is worth counting:
    /// cargo's `is_keyword` holds 51 words and Lua 5.4 has 22. A word dropped by an edit
    /// is a name that stops being refused, which no other test would notice.
    #[test]
    fn the_keyword_lists_are_the_size_of_the_sets_they_copy() {
        assert_eq!(RUST_KEYWORDS.len(), 51);
        assert_eq!(LUA_KEYWORDS.len(), 22);
    }

    /// `mise.toml` is the command's pin the way `Cargo.toml`'s `htl = ` is the crate's, so
    /// it is written under the one pin kind that names a release, byte for byte, and not
    /// under the two that name a tree.
    #[test]
    fn mise_toml_pins_the_command_under_a_release_and_is_absent_otherwise() {
        assert_eq!(
            t_mise(&HtlPin::Release("0.7.0".into())).as_deref(),
            Some(
                "# The htl this project was written by. mise (https://mise.jdx.dev) reads this file:\n\
                 # `mise install` puts that release on PATH here, whatever `htl` is elsewhere.\n\
                 [tools]\n\
                 \"cargo:htl-cli\" = \"0.7.0\"\n"
            )
        );
        assert_eq!(t_mise(&HtlPin::Main), None);
        assert_eq!(t_mise(&HtlPin::Path(PathBuf::from("../co"))), None);
    }

    /// The plan is where the file joins the tree, for every target alike: a plain project
    /// under a release pin has it, the same project under this checkout's pin does not —
    /// which is also why the scaffold snapshots, taken from a checkout build, never see it.
    #[test]
    fn the_plan_carries_mise_toml_exactly_when_the_pin_is_a_release() {
        let planned = |htl: HtlPin| -> Vec<String> {
            let opts = Options {
                lib: false,
                target: None,
                htl,
                no_x: false,
            };
            plan(Path::new("p"), "sample", "sample", &opts)
                .into_iter()
                .map(|(path, _)| path.display().to_string().replace('\\', "/"))
                .collect()
        };
        assert!(planned(HtlPin::Release("0.7.0".into())).contains(&"p/mise.toml".to_string()));
        assert!(!planned(HtlPin::Main).contains(&"p/mise.toml".to_string()));
        assert!(
            !planned(HtlPin::Path(PathBuf::from("../co"))).contains(&"p/mise.toml".to_string())
        );
    }
}