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
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
//! User-configurable settings for pitchfork.
//!
//! Settings can be configured in multiple ways (in order of precedence):
//! 1. Environment variables (highest priority)
//! 2. Project-level `pitchfork.toml` or `pitchfork.local.toml` (in `[settings]` section)
//! 3. User-level `~/.config/pitchfork/config.toml` (in `[settings]` section)
//! 4. System-level `/etc/pitchfork/config.toml` (in `[settings]` section)
//! 5. Built-in defaults (lowest priority)
//!
//! Example pitchfork.toml with settings:
//! ```toml
//! [daemons.myapp]
//! run = "node server.js"
//!
//! [settings.general]
//! autostop_delay = "5m"
//! log_level = "debug"
//!
//! [settings.web]
//! auto_start = true
//! ```
//!
//! The structs below are the single declaration of every setting:
//! `#[derive(usage_rs::Config)]` generates the usage-config registry, the
//! reader that fills the structs from a resolution, and the spec `config`
//! block that documents them (carried into `pitchfork.usage.kdl` through
//! `#[usage(config = ...)]` on the CLI root). There is no `settings.toml`
//! and no build-script generator left to keep in step with this file.
//!
//! Resolution is usage-config's single origin-tracked merge, so explicitly
//! setting a value equal to the default in a higher-precedence file still
//! overrides a lower one, and `pitchfork settings` renders provenance from
//! the same merge that produced the values.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use usage_rs::config::{
Const, EnvLayer, FileLayer, FileScope, Layers, Resolved, SourceKind, Ty, Value, resolve,
};
/// The `api.*` settings: the standalone API server (JSON REST endpoints for
/// the Vue SPA). When `api.auto_start` is enabled and `api.bind_port` is set, the API server binds
/// independently of the web UI.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "api")]
pub struct SettingsApi {
/// Automatically start the standalone API server
///
/// When true, pitchfork starts a standalone API server on api.bind_address +
/// api.bind_port when the supervisor launches. The web UI does not need to
/// be enabled for this; you can run the API alone and serve the Vue SPA from
/// a separate static host (e.g. nginx, Vite dev server).
///
/// Default is false so the API is only available through the bundled web UI.
#[usage(env = "PITCHFORK_API_AUTO_START", default = false)]
pub auto_start: bool,
/// IP address the API server binds to
///
/// Use "0.0.0.0" to make the API reachable from other devices on your network.
/// Keep "127.0.0.1" (default) to restrict it to localhost.
#[usage(env = "PITCHFORK_API_BIND_ADDRESS", default = "127.0.0.1")]
pub bind_address: String,
/// Port the standalone API server listens on
///
/// Set to 0 (default) to disable the standalone API server.
/// Set to a valid port (e.g. 8081) and enable `api.auto_start` to start the API on its own port.
#[usage(env = "PITCHFORK_API_BIND_PORT", default = 0)]
pub bind_port: i64,
/// Number of consecutive ports to try if api.bind_port is in use
#[usage(env = "PITCHFORK_API_PORT_ATTEMPTS", default = 10)]
pub port_attempts: i64,
/// Authentication token for API access when bound to non-loopback addresses
///
/// When the API server or web UI is bound to a non-loopback address (e.g.,
/// "0.0.0.0"), this token is required on every API request via the
/// X-Pitchfork-Token header.
///
/// If left empty and the bind address is non-loopback, a random 32-byte
/// hex token is auto-generated on startup and printed to the supervisor log.
/// This token is injected into the served index.html, so the bundled Vue
/// SPA works without additional configuration.
///
/// For external API consumers (e.g., curl, mobile apps), set this to a
/// fixed value or pass it via the PITCHFORK_API_TOKEN environment variable.
#[usage(env = "PITCHFORK_API_TOKEN", default = "")]
pub token: String,
}
/// The `boot.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "boot")]
pub struct SettingsBoot {
/// Executable path written into boot registrations
///
/// Set an absolute path to a stable executable or symlink to keep boot
/// registrations independent of versioned package-manager install paths.
/// The path is preserved as written, including symlinks. It must exist
/// and be executable. No shell, PATH lookup, or tilde expansion is used.
///
/// Used by boot enable, explicit refresh, and automatic stale-path repair.
/// Set this in the user or system config so boot-time repair sees it too.
/// Project config files cannot select a boot executable.
/// Empty (default) uses the running binary's resolved path, as before.
#[usage(env = "PITCHFORK_BOOT_EXECUTABLE", default = "", scope = "global")]
pub executable: String,
}
/// The `general.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "general")]
pub struct SettingsGeneral {
/// Delay before auto-stopping daemons when leaving a directory
///
/// When using shell hooks with `auto = ["stop"]`, this controls how long pitchfork waits
/// before stopping a daemon after you leave its directory.
///
/// This delay prevents unnecessary stop/start cycles when briefly switching directories.
///
/// **Examples:**
/// - `"0s"` - Stop immediately (no delay)
/// - `"30s"` - Wait 30 seconds
/// - `"1m"` - Wait 1 minute (default)
/// - `"5m"` - Wait 5 minutes
///
/// Set to `"0s"` to disable the delay and stop daemons immediately.
#[usage(env = "PITCHFORK_AUTOSTOP_DELAY", default = "1m", ty = "duration")]
pub autostop_delay: String,
/// Supervisor background task refresh interval
///
/// Controls how often the supervisor refreshes its internal state and checks for:
/// - Daemon health status changes
/// - Configuration file updates
/// - Process state synchronization
///
/// Lower values provide more responsive status updates but use more resources.
///
/// **Recommended values:**
/// - `"5s"` - For development/testing
/// - `"10s"` - Default, balanced
/// - `"30s"` - For production with many daemons
#[usage(
env = "PITCHFORK_INTERVAL",
deprecated_env("PITCHFORK_INTERVAL_SECS"),
default = "10s",
ty = "duration"
)]
pub interval: String,
/// File log level (trace, debug, info, warn, error)
///
/// Controls the verbosity of log output written to log files.
/// Can be set independently from `log_level` to have more verbose file logs.
///
/// For example, set console to `"info"` but file to `"debug"` to keep
/// detailed logs for troubleshooting without cluttering the console.
#[usage(env = "PITCHFORK_LOG_FILE_LEVEL", default = "info")]
pub log_file_level: String,
/// Console log level (trace, debug, info, warn, error)
///
/// Controls the verbosity of log output to the console.
///
/// **Available levels:**
/// - `"trace"` - Most verbose, includes all internal details
/// - `"debug"` - Detailed information for debugging
/// - `"info"` - Normal operation messages (default)
/// - `"warn"` - Warnings and potential issues
/// - `"error"` - Only errors
#[usage(env = "PITCHFORK_LOG", default = "info")]
pub log_level: String,
/// Wrap daemon commands with mise x -- globally
///
/// When enabled, pitchfork wraps every daemon command with `mise x --` so that
/// [mise](https://mise.jdx.dev) sets up the correct tool versions, PATH,
/// and environment variables before the daemon runs.
///
/// This is especially useful when pitchfork is started as a login item or boot
/// daemon, where the shell profile (`.zshrc`, `.bashrc`) is not sourced and
/// tools installed via Homebrew or mise are not on PATH.
///
/// Individual daemons can override this with `mise = true` or `mise = false`
/// in their configuration.
#[usage(env = "PITCHFORK_MISE", default = false)]
pub mise: bool,
/// Explicit path to the mise binary
///
/// By default, pitchfork searches well-known locations for the mise binary:
/// - `~/.local/bin/mise`
/// - `~/.cargo/bin/mise`
/// - `/usr/local/bin/mise`
/// - `/opt/homebrew/bin/mise`
/// - on Windows, `mise.exe` on `PATH`
///
/// Set this to an absolute path if mise is installed elsewhere.
#[usage(env = "PITCHFORK_MISE_BIN", default = "")]
pub mise_bin: String,
/// Shell command used to execute daemon run scripts
///
/// Controls the shell used to execute daemon `run` commands, as well as
/// `ready_cmd` / `health_cmd` probes, lifecycle hooks and the log archive
/// hook.
///
/// The value is split with `shell_words::split` into a program and arguments,
/// then the daemon's `run` string is appended verbatim as the final argument
/// (passed to the shell's command flag, e.g. `sh -c "<run>"`).
///
/// This means the `run` string is interpreted directly by the shell, so
/// variable expansion (`$VAR`), globs (`*.txt`), pipes (`|`), and command
/// chaining (`&&`) all work as expected.
///
/// **Common configurations:**
/// - `"sh -c"` — Default, POSIX shell
/// - `"sh -o errexit -c"` — Exit on the first failing command
/// - `"bash -c"` — Use bash instead of sh
/// - `"bash -o errexit -o pipefail -c"` — `pipefail` is not a POSIX option,
/// so name a shell that has it rather than relying on `sh`
///
/// On Windows this setting applies only when it is set explicitly (in a
/// config file or via `PITCHFORK_SHELL`); otherwise
/// `general.windows_shell` is used. Setting it is the way to use one shell
/// on every platform, e.g. `"sh -c"` with Git for Windows' `sh.exe` on
/// `PATH`.
///
/// When `mise = true` is enabled for a daemon, the shell wraps inside
/// `mise x --`, e.g. `mise x -- sh -c "<run>"`.
#[usage(env = "PITCHFORK_SHELL", default = "sh -c")]
pub shell: String,
/// Shell command used to execute daemon run scripts on Windows
///
/// Used in place of `general.shell` on Windows, unless `general.shell` is
/// set explicitly. Split and used the same way: the program and arguments
/// come from this value, and the `run` string is appended as the final
/// argument, e.g. `cmd /C "<run>"`.
///
/// The default is `cmd /C`, which is always available, so `run` strings are
/// read by cmd.exe: use `%VAR%` rather than `$VAR`, and double quotes
/// rather than single quotes.
///
/// The split follows POSIX rules, so a path with spaces or backslashes has
/// to be quoted: `"'C:\Program Files\Git\bin\sh.exe' -c"`.
///
/// When the shell is cmd.exe with `/C` last, the `run` string is handed to
/// it as `/S /C "<run>"`, so double quotes in it reach cmd as written, e.g.
/// `run = '"C:\Program Files\app\app.exe" --name "a b"'`. A daemon with
/// `mise = true` is the exception: mise starts cmd itself and quotes the
/// string again, so a `run` containing `"` may not reach cmd intact there.
///
/// **Common configurations:**
/// - `"cmd /C"` — Default
/// - `"powershell -Command"` / `"pwsh -Command"` — PowerShell
/// - `"sh -c"` — Git for Windows' sh, when `Git\bin` is on `PATH`
#[usage(env = "PITCHFORK_WINDOWS_SHELL", default = "cmd /C")]
pub windows_shell: String,
/// Show timestamps in startup log output
///
/// When enabled, pitchfork prefixes each startup log line and result line
/// with a timestamp (e.g. `19:03:15`), making it easier to see how long
/// each daemon took to start.
///
/// When disabled (default), a dim bullet (`•`) is used instead to keep
/// the output compact and aligned with the spinner / status icons.
#[usage(env = "PITCHFORK_STARTUP_LOG_TIMESTAMPS", default = false)]
pub startup_log_timestamps: bool,
/// Default readiness delay in seconds when a daemon has no ready check configured
///
/// When a daemon has no other readiness check (output, HTTP, port, command),
/// pitchfork waits this long before considering it ready. Daemons can
/// override this with their own `ready_delay` setting.
#[usage(env = "PITCHFORK_READY_DELAY", default = "3s", ty = "duration")]
pub ready_delay: String,
/// Enable git worktree / jj workspace auto-discovery
///
/// When enabled (default), pitchfork discovers git worktrees and jj workspaces for proxy
/// hostname routing and supervisor config discovery. Each worktree gets its own namespace,
/// and its daemons answer at `<daemon>.<worktree>.<project>.<tld>`.
///
/// Set to `false` to disable all worktree/workspace discovery. The deprecated
/// `PITCHFORK_PROXY_WORKTREE` environment variable remains an alias during migration.
#[usage(
env = "PITCHFORK_WORKTREE",
deprecated_env("PITCHFORK_PROXY_WORKTREE"),
alias("proxy.worktree"),
default = true
)]
pub worktree: bool,
}
/// The `ipc.*` (inter-process communication) settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "ipc")]
pub struct SettingsIpc {
/// Number of connection retry attempts
///
/// How many times to retry connecting to the supervisor before giving up.
/// Each attempt uses exponential backoff between `connect_min_delay` and `connect_max_delay`.
#[usage(env = "PITCHFORK_IPC_CONNECT_ATTEMPTS", default = 5)]
pub connect_attempts: i64,
/// Maximum delay between connection retries
///
/// The maximum delay between connection retry attempts.
/// Exponential backoff will not exceed this value.
#[usage(
env = "PITCHFORK_IPC_CONNECT_MAX_DELAY",
default = "1s",
ty = "duration"
)]
pub connect_max_delay: String,
/// Minimum delay between connection retries
///
/// The initial delay between connection retry attempts.
/// The actual delay increases exponentially up to `connect_max_delay`.
#[usage(
env = "PITCHFORK_IPC_CONNECT_MIN_DELAY",
default = "100ms",
ty = "duration"
)]
pub connect_min_delay: String,
/// Maximum IPC requests per second per connection
///
/// Rate limiting for IPC connections to prevent local DoS attacks.
/// Uses a sliding window algorithm.
///
/// Most users won't need to change this. Increase if you have automated
/// tools making many rapid requests to the supervisor.
#[usage(env = "PITCHFORK_IPC_RATE_LIMIT", default = 100)]
pub rate_limit: i64,
/// Rate limit sliding window duration
///
/// The time window for rate limiting calculations.
/// `rate_limit` requests are allowed within each window.
#[usage(
env = "PITCHFORK_IPC_RATE_LIMIT_WINDOW",
default = "1s",
ty = "duration"
)]
pub rate_limit_window: String,
/// Default timeout for IPC requests
///
/// Maximum time to wait for a response from the supervisor for most operations.
///
/// Note: Daemon start operations may use a longer timeout calculated from
/// the daemon's `ready_delay` setting plus a buffer.
#[usage(env = "PITCHFORK_IPC_REQUEST_TIMEOUT", default = "5s", ty = "duration")]
pub request_timeout: String,
}
/// The `logs.archive_hook.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "logs.archive_hook")]
pub struct SettingsLogsArchiveHook {
/// Maximum log entries per archive hook invocation
///
/// Log entries selected for pruning are passed to the archive hook in batches of
/// this size. Smaller batches use less memory and are easier to retry, while larger
/// batches reduce hook invocation overhead.
#[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_BATCH_SIZE", default = 1000)]
pub batch_size: i64,
/// Command to run before retention deletes old log entries
///
/// When set, the given command is invoked before log entries are permanently
/// pruned by retention. The command receives the entries about to be deleted as
/// JSON Lines (JSONL) on stdin. Each line is an object with the fields:
///
/// - `id`: the SQLite row id
/// - `daemon_id`: the qualified daemon id (e.g. `"myproject/api"`)
/// - `timestamp`: the log timestamp in RFC 3339 format
/// - `message`: the raw log message text
///
/// The following environment variables are also available:
///
/// - `PITCHFORK_DAEMON_ID`: the qualified daemon id
/// - `PITCHFORK_ARCHIVE_REASON`: either `"age"` or `"count"`
///
/// If the command exits with a non-zero status, the pruning is skipped for that
/// batch. This prevents data loss when the archive destination is unavailable.
///
/// **Examples:**
///
/// ```toml
/// [settings.logs.archive_hook]
/// command = "gzip -c >> /var/log/pitchfork/archive.jsonl.gz"
/// ```
///
/// ```toml
/// [settings.logs.archive_hook]
/// command = "aws s3 cp - s3://my-bucket/pitchfork-logs/"
/// ```
#[usage(env = "PITCHFORK_LOG_ARCHIVE_HOOK_COMMAND", default = "")]
pub command: String,
}
/// The `logs.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "logs")]
pub struct SettingsLogs {
#[usage(flatten)]
pub archive_hook: SettingsLogsArchiveHook,
/// Count-based log retention (e.g. 10000)
///
/// Maximum number of log entries to keep per daemon in the SQLite log store.
///
/// When set, only the most recent N log entries are retained. Older entries are
/// automatically pruned.
///
/// When set to `0` (default), no count-based pruning is performed. You can combine
/// this with `time_retention` to enforce both a time limit and a line count limit.
///
/// Logs are pruned automatically by the supervisor during its interval watcher
/// cycle (no more than once per hour). No manual rotation command is needed.
#[usage(env = "PITCHFORK_LOG_LINE_RETENTION", default = 0)]
pub line_retention: i64,
/// Default log format for daemons (json | logfmt | text)
#[usage(env = "PITCHFORK_LOG_FORMAT", default = "text")]
pub log_format: String,
/// Time-based log retention duration (e.g. '7d', '30d')
///
/// Maximum age of log entries to keep in the SQLite log store.
///
/// When set, log entries older than this duration are automatically pruned.
/// Examples: `"7d"` for 7 days, `"30d"` for 30 days, `"1h"` for 1 hour.
///
/// When empty (default), no time-based pruning is performed. You can combine
/// this with `line_retention` to enforce both a time limit and a line count limit.
///
/// Logs are pruned automatically by the supervisor during its interval watcher
/// cycle (no more than once per hour). No manual rotation command is needed.
#[usage(env = "PITCHFORK_LOG_TIME_RETENTION", default = "", ty = "duration")]
pub time_retention: String,
/// Show timestamps in log output
///
/// When enabled (default), pitchfork prefixes each log line with a timestamp
/// (e.g. `07-10 10:30:00`).
///
/// When disabled, timestamps are omitted from `pitchfork logs` output. This is
/// useful when piping logs to tools like `lnav` that expect raw JSON or when
/// you want to process log output without the timestamp prefix.
///
/// Can be overridden per-invocation with `pitchfork logs --no-timestamp`.
#[usage(env = "PITCHFORK_LOG_TIMESTAMP", default = true)]
pub timestamp: bool,
/// strftime format for log timestamps in `pitchfork logs` output
///
/// Controls the date/time format used when displaying timestamps in `pitchfork logs`
/// output. Uses chrono strftime syntax.
///
/// Common format specifiers:
/// - `%Y` — full year (2024)
/// - `%m` — month (01-12)
/// - `%d` — day (01-31)
/// - `%H` — hour (00-23)
/// - `%M` — minute (00-59)
/// - `%S` — second (00-59)
///
/// Examples:
/// - `%m-%d %H:%M:%S` — `07-10 10:30:00` (default)
/// - `%Y-%m-%d %H:%M:%S` — `2024-07-10 10:30:00`
/// - `%H:%M:%S` — `10:30:00` (time only)
/// - `%Y/%m/%d %H:%M` — `2024/07/10 10:30`
///
/// Only affects the text display output, not `--json` or `--raw` modes.
#[usage(env = "PITCHFORK_LOG_TIMESTAMP_FORMAT", default = "%m-%d %H:%M:%S")]
pub timestamp_format: String,
}
/// The `proxy.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "proxy")]
pub struct SettingsProxy {
/// Automatically start daemons when accessed via proxy URL
///
/// Enabled by default. Opening a stopped daemon's proxy URL starts its
/// `depends` dependencies first, using the same startup order and readiness
/// checks as `pitchfork start`. Oneshot dependencies must complete successfully.
///
/// The first request waits for startup. Additional requests to the same daemon
/// receive a "Starting…" page that refreshes every two seconds until it is ready.
/// Opening a project or stack page does not start any daemons.
///
/// Set to `false` to return a 502 error for stopped daemons and require manual startup.
#[usage(env = "PITCHFORK_PROXY_AUTO_START", default = true)]
pub auto_start: bool,
/// Maximum time to wait for an auto-started daemon to become ready
///
/// Limits how long a proxy request waits for dependency startup, readiness
/// checks, and detection of the daemon's bound port. Defaults to 30 seconds.
///
/// On timeout, the request receives an error page, but startup continues in
/// the background. Reload to check again, or increase this setting for a
/// longer startup sequence, for example `"60s"`.
#[usage(
env = "PITCHFORK_PROXY_AUTO_START_TIMEOUT",
default = "30s",
ty = "duration"
)]
pub auto_start_timeout: String,
/// Automatically trust the generated proxy CA certificate
///
/// When enabled (default), pitchfork attempts to install its generated CA
/// certificate into the system trust store during HTTPS proxy startup.
///
/// On macOS, this triggers a system authorization dialog (Touch ID or password).
/// On Linux, use `pitchfork proxy setup` to install the CA with sudo while
/// keeping the supervisor unprivileged.
///
/// If auto-trust fails, pitchfork logs a warning and continues starting the
/// proxy. Use `pitchfork proxy doctor` to check trust, or
/// `pitchfork proxy trust` to install the CA manually (with sudo on Linux).
///
/// Set to `false` to disable auto-trust entirely.
#[usage(env = "PITCHFORK_PROXY_AUTO_TRUST", default = true)]
pub auto_trust: bool,
/// Run a loopback DNS resolver for the proxy TLD
///
/// While the proxy is running, answer UDP and TCP DNS queries on
/// `127.0.0.1:<proxy.dns_port>` for names under `proxy.tld`, including nested
/// project and worktree hostnames. Answers follow `proxy.host`, or the LAN
/// IPv4 address in LAN mode. Names outside the TLD receive REFUSED; queries
/// are never forwarded.
///
/// Run `pitchfork proxy setup` to configure system resolution separately.
/// Set to `false` when using another resolver or when DNS is not needed.
#[usage(env = "PITCHFORK_PROXY_DNS", default = true)]
pub dns: bool,
/// Port the loopback DNS resolver listens on
///
/// The resolver binds `127.0.0.1:<dns_port>` on both UDP and TCP.
///
/// The default avoids privileged port 53 and the mDNS port, 5353.
#[usage(env = "PITCHFORK_PROXY_DNS_PORT", default = 15353)]
pub dns_port: i64,
/// Enable the reverse proxy server for daemons
///
/// When enabled, pitchfork starts a reverse proxy that routes a stable
/// hostname to the daemon's actual listening port.
///
/// Every daemon with a `port` gets a hostname built from its name, its
/// worktree when it lives in one, and its project, unless it opts out with
/// `proxy = false`. A daemon without a port is not routed.
///
/// Example: `api.myproject.localhost:7777` -> `localhost:3000`
#[usage(env = "PITCHFORK_PROXY_ENABLE", default = false)]
pub enable: bool,
/// Bind address for the reverse proxy server
///
/// IP address the reverse proxy listens on.
///
/// **Security Warning:** The default `127.0.0.1` only allows local connections.
/// Setting this to `0.0.0.0` will expose the proxy on every network interface,
/// including externally routable ones -- anyone on the same LAN can then reach
/// your local daemons.
///
/// **Examples:**
/// - `"127.0.0.1"` - Local only (default, recommended)
/// - `"0.0.0.0"` - All interfaces (use with caution)
/// - `"::1"` - IPv6 loopback
#[usage(env = "PITCHFORK_PROXY_HOST", default = "127.0.0.1")]
pub host: String,
/// Enable HTTPS for the reverse proxy
///
/// When enabled (default), the proxy serves HTTPS instead of HTTP.
///
/// You must also configure `proxy.tls_cert` and `proxy.tls_key`, or pitchfork
/// will auto-generate a self-signed certificate stored in the state directory.
///
/// Set to `false` to use plain HTTP (e.g. for simple local development).
#[usage(env = "PITCHFORK_PROXY_HTTPS", default = true)]
pub https: bool,
/// Stop proxy-started daemons after this long without proxy activity
///
/// Disabled by default: an empty string or `"0"` disables the default timeout.
/// Set a duration such as `"15m"` or `"1h"` to enable idle shutdown for daemons
/// started through their proxy URL. A daemon's `proxy_idle_timeout` overrides
/// this setting; dependencies without an override inherit the requested
/// daemon's timeout.
///
/// HTTP requests count until their response ends. Streaming responses,
/// WebSockets, and TLS passthrough connections keep a daemon active while
/// open. DNS lookups, idle keep-alive connections, and traffic sent directly
/// to the daemon's port do not count.
///
/// Only proxy-started daemons are eligible. Explicitly starting a daemon
/// exempts it and its dependencies from idle shutdown. Live dependents and
/// tracked shell sessions also prevent shutdown.
///
/// Eligibility is checked every `general.interval` (10 seconds by default).
/// Dependencies stop after their dependents; shutdown may take longer than
/// the idle timeout. The timeout is recorded at startup, and activity
/// tracking resets after a supervisor restart.
#[usage(env = "PITCHFORK_PROXY_IDLE_TIMEOUT", default = "", ty = "duration")]
pub idle_timeout: String,
/// Enable LAN mode for the reverse proxy
///
/// When enabled, the proxy switches to the `.local` TLD and publishes slug
/// hostnames via mDNS so that other devices on the same network can reach
/// your daemons (e.g. `myapp.local` from a phone or another computer).
///
/// LAN mode:
/// - Forces `proxy.tld` to `local` (mDNS requirement)
/// - Publishes each slug as an mDNS address record (`<slug>.local → <LAN-IP>`)
/// - Binds the proxy to `0.0.0.0` instead of `127.0.0.1` (overridable via `proxy.host`)
/// - Auto-detects your LAN IP and re-publishes mDNS records if it changes
///
/// Other devices must trust the pitchfork CA certificate to use HTTPS.
/// Run `pitchfork proxy trust` on each device, or use `proxy.https = false`.
#[usage(env = "PITCHFORK_PROXY_LAN", default = false)]
pub lan: bool,
/// Pin a specific LAN IP address instead of auto-detecting
///
/// When set, skips auto-detection and uses this IP for mDNS publishing.
/// Implies `proxy.lan = true` if a non-empty value is provided.
#[usage(env = "PITCHFORK_PROXY_LAN_IP", default = "")]
pub lan_ip: String,
/// Port the reverse proxy server listens on
///
/// The port pitchfork's reverse proxy binds to. Must be in the range 1-65535.
///
/// Default is 443 (standard HTTPS port) since the proxy defaults to HTTPS.
/// Users can override this to any port (e.g. 7777) to avoid requiring
/// elevated privileges.
///
/// To use standard ports without running the supervisor as root, choose
/// an unprivileged listener such as 8443 and run `pitchfork proxy setup`
/// to redirect local traffic on macOS or Linux. On Linux, setup can also
/// grant permission to bind ports below 1024 directly.
#[usage(env = "PITCHFORK_PROXY_PORT", default = 443)]
pub port: i64,
/// Automatically sync slug hostnames to /etc/hosts (deprecated)
///
/// Deprecated and scheduled for removal after one release. Run
/// `pitchfork proxy setup`, check resolution with `pitchfork proxy doctor`,
/// then set `sync_hosts = false`. The loopback DNS resolver supports nested
/// hostnames without per-host entries.
///
/// When enabled (default), pitchfork adds entries to `/etc/hosts` for
/// registered slugs (e.g. `127.0.0.1 myapp.localhost`) so that browsers can
/// resolve them. Entries are managed in a marked block and cleaned up when
/// the proxy shuts down. Writing to `/etc/hosts` may require `sudo`, and it
/// only ever covers registered slugs, never wildcard names.
#[usage(env = "PITCHFORK_PROXY_SYNC_HOSTS", default = true)]
pub sync_hosts: bool,
/// Top-level domain used for proxy URLs
///
/// The TLD appended to daemon hostnames in proxy URLs.
///
/// With the default `localhost`, daemon URLs look like:
/// `api.myproject.localhost:7777` (daemon `api` of project `myproject`)
///
/// Run `pitchfork proxy setup` to configure system resolution, including
/// for custom TLDs such as `test`, or use `--pac` for applications that honor
/// automatic proxy settings. Restart the supervisor after changing the TLD.
#[usage(env = "PITCHFORK_PROXY_TLD", default = "localhost")]
pub tld: String,
/// Path to TLS certificate file (PEM format) for HTTPS proxy
///
/// Path to a PEM-encoded TLS certificate file used when `proxy.https = true`.
/// It is served as-is for every hostname, and must match `proxy.tls_key`.
///
/// If left empty and `proxy.https = true`, pitchfork generates a local
/// certificate authority at `$PITCHFORK_STATE_DIR/proxy/ca.pem` and signs a
/// certificate per hostname from it on the first TLS handshake, caching
/// them in `$PITCHFORK_STATE_DIR/proxy/host-certs/`. Trusting the CA once
/// with `pitchfork proxy trust` covers every proxy hostname.
///
/// With a custom certificate, pitchfork serves that certificate without
/// signing per-hostname certificates. It must cover every hostname you
/// use, and clients must trust its issuer. Setup skips CA installation;
/// set `proxy.auto_trust = false` to also disable startup CA trust.
#[usage(env = "PITCHFORK_PROXY_TLS_CERT", default = "")]
pub tls_cert: String,
/// Path to TLS private key file (PEM format) for HTTPS proxy
///
/// Path to a PEM-encoded private key file matching `proxy.tls_cert`. The
/// pair is checked at startup, so a mismatch is reported rather than
/// failing every handshake.
///
/// If left empty and `proxy.https = true`, pitchfork generates a CA key at
/// `$PITCHFORK_STATE_DIR/proxy/ca-key.pem` instead. See `proxy.tls_cert`.
#[usage(env = "PITCHFORK_PROXY_TLS_KEY", default = "")]
pub tls_key: String,
/// Enable wildcard subdomain matching for proxy routes
///
/// When enabled (default), extra labels to the left of a daemon's hostname
/// route to that same daemon.
///
/// For example, with a daemon reachable at `api.myproject.localhost`:
///
/// - `api.myproject.localhost` → exact match (always works)
///
/// - `tenant.api.myproject.localhost` → wildcard fallback to the same daemon
///
/// The same holds for a legacy slug, where `tenant.myapp.localhost` falls
/// back to the slug `myapp`.
///
/// This is useful for multi-tenant apps where each tenant gets a unique
/// subdomain (e.g. `acme.myapp.localhost`, `globex.myapp.localhost`) but
/// all share the same backend server.
///
/// Set to `false` to require exact hostname matches only.
#[usage(env = "PITCHFORK_PROXY_WILDCARD", default = true)]
pub wildcard: bool,
}
/// The `supervisor.*` settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "supervisor")]
pub struct SettingsSupervisor {
/// Automatically start the supervisor when a client command needs it
///
/// When enabled (default), commands such as `pitchfork start`, `pitchfork list`,
/// the TUI, and shell activation start a background supervisor automatically when
/// one is not already running.
///
/// Disable this when the supervisor is managed by systemd, launchd, or another
/// service manager:
///
/// ```toml
/// [settings.supervisor]
/// auto_start = false
/// ```
///
/// With auto-start disabled, client commands wait for the configured IPC
/// connection attempts and then fail with an actionable error instead of spawning
/// an unmanaged supervisor. Explicit `pitchfork supervisor start` and
/// `pitchfork supervisor run` commands are unaffected.
#[usage(env = "PITCHFORK_SUPERVISOR_AUTO_START", default = true)]
pub auto_start: bool,
/// Reconcile orphaned daemon processes when supervisor starts
///
/// When enabled, the supervisor scans the state file on startup for daemon
/// processes left behind by a previous supervisor instance that was killed
/// unexpectedly (for example, with `kill -9`) and reconciles them according
/// to `supervisor.orphan_policy` (re-adopt by default, or terminate).
///
/// Before acting, the recorded process identity (PID plus kernel start
/// time) is verified so that a PID recycled by the OS to an unrelated process
/// is never adopted or killed — in that case only the stale state entry is
/// cleared. When terminating, Linux and Windows also pin that identity with a
/// pidfd or open process handle, so a recycled PID cannot be signaled. If the
/// identity cannot be verified or pinned, reconciliation fails closed: the
/// live process and its running state are retained rather than risk acting on
/// the wrong process or allowing a duplicate instance to start.
///
/// Disabling this leaves orphaned processes and their state entries
/// completely untouched. This is a legacy escape hatch; prefer
/// `orphan_policy = "adopt"` (the default), which keeps daemons running
/// across a supervisor crash while resuming supervision.
#[usage(env = "PITCHFORK_CLEANUP_ORPHANS", default = true)]
pub cleanup_orphans: bool,
/// Enable container/PID1 mode for running inside Docker containers
///
/// When enabled, pitchfork operates as a proper PID 1 process inside a container:
/// - Installs a SIGCHLD handler to reap all orphaned/zombie child processes
/// - Routes SIGTERM/SIGINT through the graceful shutdown sequence
///
/// This is essential when running pitchfork as the entrypoint of a Docker container,
/// where PID 1 must reap zombie processes to prevent process table exhaustion.
///
/// Can also be enabled via the `--container` CLI flag on `pitchfork supervisor run`.
#[usage(env = "PITCHFORK_CONTAINER", default = false)]
pub container: bool,
/// Consecutive CPU-over-limit samples before killing a daemon
///
/// When a daemon has `cpu_limit` configured, the supervisor checks CPU usage at
/// each interval tick. To avoid killing daemons during transient spikes (e.g. JIT
/// warm-up, burst responses), the process is only killed after this many
/// **consecutive** samples exceed the limit. A single sample below the limit
/// resets the counter.
///
/// **Examples:**
/// - `1` - Kill immediately on first over-limit sample (no grace period)
/// - `3` - Require 3 consecutive over-limit samples (default)
/// - `5` - More tolerant of short bursts
///
/// With the default interval of `10s`, a threshold of `3` means a daemon must
/// exceed its CPU limit for ~30 seconds before being killed.
#[usage(env = "PITCHFORK_CPU_VIOLATION_THRESHOLD", default = 3)]
pub cpu_violation_threshold: i64,
/// Interval for checking cron schedules
///
/// How often to check if any cron-scheduled daemons should be triggered.
///
/// The default of 10 seconds supports sub-minute cron schedules.
/// Increase for lower resource usage if you don't need fine-grained scheduling.
#[usage(
env = "PITCHFORK_CRON_CHECK_INTERVAL",
default = "10s",
ty = "duration"
)]
pub cron_check_interval: String,
/// File watch debounce duration
///
/// When using `watch` patterns to auto-restart daemons on file changes,
/// this controls how long to wait after the last change before triggering
/// a restart.
///
/// This prevents rapid restart cycles when many files change at once
/// (e.g., during a build or git checkout).
#[usage(env = "PITCHFORK_FILE_WATCH_DEBOUNCE", default = "1s", ty = "duration")]
pub file_watch_debounce: String,
/// Default time between health probes
///
/// When a daemon has `health_cmd`, `health_http` or `health_port`
/// configured but does not set its own `interval`, the supervisor probes
/// it this often.
#[usage(
env = "PITCHFORK_HEALTH_CHECK_INTERVAL",
default = "10s",
ty = "duration"
)]
pub health_check_interval: String,
/// Default consecutive health-check failures before killing a daemon
///
/// When a daemon's `health_cmd`, `health_http` or `health_port` fails this
/// many times in a row, the daemon is killed as a crash so the retry logic
/// restarts it. Individual daemons can override this with `retries` in
/// their health check configuration.
#[usage(env = "PITCHFORK_HEALTH_CHECK_RETRIES", default = 3)]
pub health_check_retries: i64,
/// Default per-probe timeout for `health_cmd`
///
/// Maximum time to wait for a `health_cmd` shell command to finish before
/// counting the probe as failed and cancelling it.
#[usage(env = "PITCHFORK_HEALTH_CMD_TIMEOUT", default = "10s", ty = "duration")]
pub health_cmd_timeout: String,
/// Default per-request timeout for `health_http`
///
/// Maximum time to wait for a response from a `health_http` endpoint before
/// counting the probe as failed.
#[usage(env = "PITCHFORK_HEALTH_HTTP_TIMEOUT", default = "5s", ty = "duration")]
pub health_http_timeout: String,
/// Default per-connect timeout for `health_port`
///
/// Maximum time to wait for a TCP connection to a `health_port` to
/// establish before counting the probe as failed.
#[usage(env = "PITCHFORK_HEALTH_PORT_TIMEOUT", default = "5s", ty = "duration")]
pub health_port_timeout: String,
/// Timeout for HTTP ready checks
///
/// Maximum time to wait for a response when checking `ready_http` endpoints.
///
/// Increase if your services take a while to respond during startup.
#[usage(env = "PITCHFORK_HTTP_CLIENT_TIMEOUT", default = "5s", ty = "duration")]
pub http_client_timeout: String,
/// Daemon log buffer flush interval
///
/// How often daemon log output is flushed to disk.
/// Lower values mean logs appear faster in the UI but may impact performance.
#[usage(
env = "PITCHFORK_LOG_FLUSH_INTERVAL",
default = "500ms",
ty = "duration"
)]
pub log_flush_interval: String,
/// What to do with live orphaned daemons on supervisor startup: adopt or kill
///
/// When the supervisor starts and finds daemons in the state file whose
/// processes are still alive from a previous supervisor instance that died
/// uncleanly, this policy decides what happens (after the process identity
/// is verified via PID plus kernel start time):
///
/// - `adopt` (default): keep the process running and resume supervision.
/// The daemon keeps its state (status, ports, proxy routing) and is
/// monitored by polling. Log capture is unaffected, because a daemon's
/// output is read by a sibling sink process rather than by the supervisor,
/// so it continues uninterrupted across the crash. Exit codes of adopted
/// daemons cannot be observed, though;
/// an adopted daemon that dies unexpectedly is marked `errored` with an
/// unknown exit code, which makes it eligible for its configured retries.
/// - `kill`: terminate the orphaned process group so the new supervisor
/// starts with a clean slate, matching pre-adoption behavior.
///
/// Daemons whose recorded PID is dead, or whose PID now belongs to a
/// different process, have their state reset under either policy. If the
/// process identity cannot be verified, reconciliation fails closed and
/// retains the running state without adopting or killing.
///
/// The same policy applies when the interval watcher finds a running daemon
/// that has lost its monitor at runtime.
///
/// This setting has no effect when `cleanup_orphans` is disabled.
#[usage(env = "PITCHFORK_ORPHAN_POLICY", default = "adopt")]
pub orphan_policy: String,
/// Maximum port increment attempts when auto_bump_port is enabled
///
/// When `auto_bump_port = true` is set on a daemon, pitchfork will try incrementing
/// all of the daemon's ports by the same offset to find a free range. This setting
/// controls how many offsets are tried before giving up with an error.
///
/// For example, with `port = [3000]` and `port_bump_attempts = 10`, pitchfork will
/// try ports 3000, 3001, 3002, ... up to 3009 before reporting failure.
///
/// This is a global default; individual daemons can override it with
/// `port_bump_attempts` in their daemon configuration.
#[usage(env = "PITCHFORK_PORT_BUMP_ATTEMPTS", default = 10)]
pub port_bump_attempts: i64,
/// Interval between ready checks (HTTP, TCP, command)
///
/// How often to poll when checking if a daemon is ready using:
/// - `ready_http` - HTTP health endpoint
/// - `ready_port` - TCP port listening
/// - `ready_cmd` - Shell command exit code
///
/// Lower values detect readiness faster but use more resources.
#[usage(
env = "PITCHFORK_READY_CHECK_INTERVAL",
default = "500ms",
ty = "duration"
)]
pub ready_check_interval: String,
/// Delay between stop and start during restart
///
/// Brief pause after stopping a daemon before starting it again.
/// Helps ensure resources (like ports) are fully released.
#[usage(env = "PITCHFORK_RESTART_DELAY", default = "100ms", ty = "duration")]
pub restart_delay: String,
/// Maximum time to wait for a oneshot daemon to finish
///
/// A `oneshot = true` daemon is ready when its process exits `0`, so there is no
/// readiness check to bound the wait. `pitchfork start` gives up after this long
/// and reports a timeout; the task itself keeps running and is still recorded as
/// `completed` if it later exits successfully. A nonzero exit remains a failure.
///
/// Set to `0` for no limit. Raise it for long migrations, backfills, or seeds.
#[usage(env = "PITCHFORK_ONESHOT_TIMEOUT", default = "1h", ty = "duration")]
pub oneshot_timeout: String,
/// Maximum time to wait for daemon to stop gracefully
///
/// When stopping a daemon, pitchfork sends its configured signal (SIGTERM by default) and waits this long
/// for the process to exit gracefully before sending SIGKILL.
///
/// Increase for daemons that need time to clean up (e.g., flush data).
#[usage(env = "PITCHFORK_STOP_TIMEOUT", default = "5s", ty = "duration")]
pub stop_timeout: String,
/// Default user to run daemon processes as
///
/// Default Unix user for daemon processes spawned by the supervisor.
///
/// When set, all daemons run as this user unless an individual daemon sets
/// `user = "..."`. The value may be a username (for example `"postgres"`) or
/// a numeric UID (for example `"501"`).
///
/// If unset and the supervisor is running as root via `sudo`, daemons default to
/// the sudo-calling user from `SUDO_UID`/`SUDO_GID` instead of running as root.
/// A system boot service registered with `sudo pitchfork boot enable` records
/// that user as `--invoking-user` and defaults to them in the same way.
#[usage(env = "PITCHFORK_USER", default = "")]
pub user: String,
/// File watcher config refresh interval
///
/// How often the supervisor refreshes file watch configuration when using `watch` patterns.
///
/// This controls how quickly newly started/stopped daemons with watch patterns are reflected
/// in the active watcher set.
///
/// For polling watcher cadence, use `supervisor.watch_poll_interval`.
///
/// Lower values react faster to configuration/runtime changes but use more CPU.
/// The default `"10s"` is appropriate for most environments.
#[usage(
env = "PITCHFORK_WATCH_INTERVAL",
deprecated_env("PITCHFORK_WATCH_INTERVAL_MS"),
default = "10s",
ty = "duration"
)]
pub watch_interval: String,
/// Polling watcher filesystem scan interval
///
/// How often polling-based file watchers scan for changes.
///
/// This applies when daemon `watch_mode` is `poll`, or when `watch_mode = "auto"`
/// falls back to polling because native watchers are unavailable.
///
/// Lower values detect changes faster but use more CPU and I/O.
/// `"100ms"` is useful for highly interactive workflows;
/// `"500ms"` is a practical default for remote/networked filesystems.
#[usage(
env = "PITCHFORK_WATCH_POLL_INTERVAL",
default = "500ms",
ty = "duration"
)]
pub watch_poll_interval: String,
}
/// The `tui.*` (terminal UI) settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "tui")]
pub struct SettingsTui {
/// Status message display duration
///
/// How long status messages (like "Daemon started") remain visible
/// in the TUI before automatically clearing.
#[usage(
env = "PITCHFORK_TUI_MESSAGE_DURATION",
default = "3s",
ty = "duration"
)]
pub message_duration: String,
/// Daemon list refresh interval
///
/// How often the TUI refreshes the daemon list and status information.
///
/// Lower values provide more responsive updates but may increase CPU usage,
/// especially with many daemons.
///
/// **Recommended values:**
/// - `"1s"` - More responsive
/// - `"2s"` - Default, balanced
/// - `"5s"` - Lower resource usage
#[usage(env = "PITCHFORK_TUI_REFRESH_RATE", default = "2s", ty = "duration")]
pub refresh_rate: String,
/// Number of stat samples to keep for graphs
///
/// How many CPU/memory stat samples to keep for each daemon's graph.
/// With the default refresh rate of 2s, 60 samples = ~2 minutes of history.
///
/// Increase for longer history in graphs, at the cost of more memory.
#[usage(env = "PITCHFORK_TUI_STAT_HISTORY", default = 60)]
pub stat_history: i64,
/// Event loop tick rate
///
/// How often the TUI checks for keyboard input and other events.
/// This affects input responsiveness.
///
/// Most users won't need to change this. Lower values make the UI more
/// responsive but use more CPU.
#[usage(env = "PITCHFORK_TUI_TICK_RATE", default = "100ms", ty = "duration")]
pub tick_rate: String,
}
/// The `web.*` (web UI) settings.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
#[usage(prefix = "web")]
pub struct SettingsWeb {
/// Automatically start web UI when supervisor starts
///
/// When enabled, the web UI server will automatically start alongside the supervisor.
///
/// By default, this is disabled. You can also start the web UI manually with:
/// ```text
/// pitchfork supervisor start --web-port=3120
/// ```
#[usage(env = "PITCHFORK_WEB_AUTO_START", default = false)]
pub auto_start: bool,
/// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
///
/// Serves the web UI under a sub-path prefix, useful when running behind a reverse
/// proxy that routes a path prefix to pitchfork.
///
/// **Examples:**
/// - `""` - Serve at root `/` (default)
/// - `"ps"` - Serve at `/ps/`
/// - `"tools/pitchfork"` - Serve at `/tools/pitchfork/`
///
/// Equivalent to the `--web-path` CLI flag. The CLI flag takes priority over this setting.
#[usage(env = "PITCHFORK_WEB_PATH", default = "")]
pub base_path: String,
/// Web server bind address
///
/// IP address for the web UI to listen on.
///
/// **Security Warning:** The default `127.0.0.1` only allows local connections.
/// Setting this to `0.0.0.0` will expose the web UI to your network.
///
/// **Examples:**
/// - `"127.0.0.1"` - Local only (default, recommended)
/// - `"0.0.0.0"` - All interfaces (use with caution)
/// - `"192.168.1.100"` - Specific interface
#[usage(env = "PITCHFORK_WEB_BIND_ADDRESS", default = "127.0.0.1")]
pub bind_address: String,
/// Default web server port
///
/// The port number for the web UI. If this port is in use, pitchfork will
/// try subsequent ports up to `port_attempts` times.
#[usage(env = "PITCHFORK_WEB_BIND_PORT", default = 3120)]
pub bind_port: i64,
/// Initial number of log lines to display
///
/// How many lines of logs to show initially when viewing daemon logs in the web UI.
/// More lines means slower initial load but more history visible.
#[usage(env = "PITCHFORK_WEB_LOG_LINES", default = 100)]
pub log_lines: i64,
/// Number of ports to try if default is in use
///
/// If the default port is occupied, pitchfork will try this many consecutive
/// ports before giving up.
///
/// For example, with `bind_port = 3120` and `port_attempts = 10`,
/// it will try ports 3120, 3121, 3122, ... up to 3129.
#[usage(env = "PITCHFORK_WEB_PORT_ATTEMPTS", default = 10)]
pub port_attempts: i64,
/// Server-Sent Events poll interval for log streaming
///
/// How often the web UI checks for new log lines when streaming logs.
/// Lower values provide more real-time updates but use more resources.
#[usage(
env = "PITCHFORK_WEB_SSE_POLL_INTERVAL",
default = "500ms",
ty = "duration"
)]
pub sse_poll_interval: String,
}
/// Every setting pitchfork has.
///
/// `SETTINGS_PROPS`, `SETTINGS_REGISTRY`, `read`, and `spec_kdl` are generated
/// from these fields; the CLI's emitted spec carries the `config` block
/// through `#[usage(config = ...)]` on the root.
#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
// `file(...)` is intentionally repeatable in usage's configuration DSL.
#[allow(clippy::duplicated_attributes)]
#[usage(
file(path = "/etc/pitchfork/config.toml", scope = "system", format = "toml"),
file(
path = "~/.config/pitchfork/config.toml",
scope = "global",
format = "toml"
),
file(
path = ".config/pitchfork.toml",
findup,
scope = "project",
format = "toml"
),
file(
path = ".config/pitchfork.local.toml",
findup,
scope = "project",
format = "toml"
),
file(path = "pitchfork.toml", findup, scope = "project", format = "toml"),
file(
path = "pitchfork.local.toml",
findup,
scope = "project",
format = "toml"
)
)]
pub struct Settings {
#[usage(flatten)]
pub api: SettingsApi,
#[usage(flatten)]
pub boot: SettingsBoot,
#[usage(flatten)]
pub general: SettingsGeneral,
#[usage(flatten)]
pub ipc: SettingsIpc,
#[usage(flatten)]
pub logs: SettingsLogs,
#[usage(flatten)]
pub proxy: SettingsProxy,
#[usage(flatten)]
pub supervisor: SettingsSupervisor,
#[usage(flatten)]
pub tui: SettingsTui,
#[usage(flatten)]
pub web: SettingsWeb,
}
impl Default for Settings {
/// The declared defaults, read the same way any other resolution is.
fn default() -> Self {
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new())
.expect("no layers were given, so there is nothing to fail");
Settings::read(&resolved).expect("every pitchfork setting has a declared default")
}
}
/// Generate the `Duration` convenience getters the rest of the codebase uses
/// (e.g. `settings().general_autostop_delay()`), each parsing its humantime
/// string field and silently falling back to the schema default. Invalid
/// values were already warned about once at load time.
macro_rules! duration_getters {
($($name:ident => $group:ident . $field:ident, $default:literal;)+) => {
impl Settings {
$(
#[doc = concat!("Get `", stringify!($group), ".", stringify!($field), "` as Duration")]
#[allow(dead_code)]
pub fn $name(&self) -> std::time::Duration {
Self::parse_duration(&self.$group.$field).unwrap_or_else(|| {
humantime::parse_duration($default)
.unwrap_or(std::time::Duration::from_secs(1))
})
}
)+
}
};
}
duration_getters! {
general_autostop_delay => general.autostop_delay, "1m";
general_interval => general.interval, "10s";
general_ready_delay => general.ready_delay, "3s";
ipc_connect_max_delay => ipc.connect_max_delay, "1s";
ipc_connect_min_delay => ipc.connect_min_delay, "100ms";
ipc_rate_limit_window => ipc.rate_limit_window, "1s";
ipc_request_timeout => ipc.request_timeout, "5s";
logs_time_retention => logs.time_retention, "";
proxy_auto_start_timeout => proxy.auto_start_timeout, "30s";
supervisor_cron_check_interval => supervisor.cron_check_interval, "10s";
supervisor_file_watch_debounce => supervisor.file_watch_debounce, "1s";
supervisor_health_check_interval => supervisor.health_check_interval, "10s";
supervisor_health_cmd_timeout => supervisor.health_cmd_timeout, "10s";
supervisor_health_http_timeout => supervisor.health_http_timeout, "5s";
supervisor_health_port_timeout => supervisor.health_port_timeout, "5s";
supervisor_http_client_timeout => supervisor.http_client_timeout, "5s";
supervisor_log_flush_interval => supervisor.log_flush_interval, "500ms";
supervisor_oneshot_timeout => supervisor.oneshot_timeout, "1h";
supervisor_ready_check_interval => supervisor.ready_check_interval, "500ms";
supervisor_restart_delay => supervisor.restart_delay, "100ms";
supervisor_stop_timeout => supervisor.stop_timeout, "5s";
supervisor_watch_interval => supervisor.watch_interval, "10s";
supervisor_watch_poll_interval => supervisor.watch_poll_interval, "500ms";
tui_message_duration => tui.message_duration, "3s";
tui_refresh_rate => tui.refresh_rate, "2s";
tui_tick_rate => tui.tick_rate, "100ms";
web_sse_poll_interval => web.sse_poll_interval, "500ms";
}
impl Settings {
/// How long to wait for a `oneshot` daemon to finish.
///
/// `supervisor.oneshot_timeout = "0"` means no limit: a task's natural end
/// is its exit, and a long migration should not be called failed merely for
/// outlasting a default. That is an absent deadline, not a very large one,
/// so no task can outlive the substitute and be reported as timed out
/// despite the setting promising otherwise.
pub fn supervisor_oneshot_wait(&self) -> crate::config_types::OneshotWait {
let configured = self.supervisor_oneshot_timeout();
if configured.is_zero() {
crate::config_types::OneshotWait::Unlimited
} else {
crate::config_types::OneshotWait::For(configured)
}
}
/// `proxy.idle_timeout` as a grace period, or `None` when idle shutdown
/// is off (empty, zero, or invalid — invalid values were already warned
/// about at load time).
pub fn proxy_idle_timeout(&self) -> Option<std::time::Duration> {
Self::parse_duration(self.proxy.idle_timeout.trim()).filter(|d| !d.is_zero())
}
/// Resolve `general.ready_delay` as whole seconds.
///
/// The ready-check pipeline (RunOptions/IPC/supervisor) models the delay
/// in whole seconds. Reject subsecond values that would otherwise be
/// silently truncated to a zero delay by `as_secs()`.
pub fn general_ready_delay_secs(&self) -> Result<u64, String> {
let delay = self.general_ready_delay();
if delay.subsec_nanos() != 0 {
return Err(format!(
"settings.general.ready_delay must be a whole number of seconds, got \"{}\"",
self.general.ready_delay
));
}
Ok(delay.as_secs())
}
}
impl Settings {
/// Load settings from pitchfork.toml files, then overlay environment variables.
/// Settings are loaded from all pitchfork.toml files in precedence order:
/// 1. System-level: /etc/pitchfork/config.toml
/// 2. User-level: ~/.config/pitchfork/config.toml
/// 3. Project-level: pitchfork.toml files from root to current directory
///
/// Environment variables override all file-based settings.
///
/// The global [`settings()`] accessor resolves through
/// [`Settings::resolve_from_dir`] so it can keep the provenance; this
/// stays as the public one-shot entry point.
#[allow(dead_code)]
pub fn load() -> Self {
Self::load_from_dir(&crate::env::CWD)
}
/// Load settings for a specific project directory, then overlay environment variables.
///
/// This is used when operating on daemons from registered namespaces whose project
/// settings may differ from those of the invoking process's current directory.
pub fn load_from_dir(start_dir: &Path) -> Self {
Self::resolve_from_dir(start_dir).0
}
/// Resolve settings for `start_dir`, returning both the typed struct and
/// the origin-tracked resolution it was read from (for `pitchfork settings`).
pub(crate) fn resolve_from_dir(start_dir: &Path) -> (Self, Resolved) {
let env_layer = EnvLayer::from_process();
// Highest precedence first, below the environment.
let file_layers = Self::file_layers_from(start_dir);
let mut layers = Layers::new().then(&env_layer);
for layer in &file_layers {
layers = layers.then(layer);
}
let mut resolved = match resolve(Settings::SETTINGS_REGISTRY, layers) {
Ok(resolved) => resolved,
Err(e) => {
// Should not happen: every file was pre-validated above. Fall
// back to env + defaults rather than failing to start.
eprintln!("pitchfork: warning: failed to resolve settings from config files: {e}");
resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env_layer)).unwrap_or_else(
|_| {
resolve(Settings::SETTINGS_REGISTRY, Layers::new())
.expect("resolving only defaults cannot fail")
},
)
}
};
sanitize_durations(&mut resolved);
for warning in usage_rs::config::explain::warnings(&resolved) {
warn!("{warning}");
}
// Lossy, because the alternative is worse than the problem: `read` is all or nothing,
// so one field the merge could not hand to its type used to cost every *other* setting
// too — `Settings::default()` throws away the environment and every config file over a
// single bad value. Here the offending field falls back to its own declared default and
// nothing else is touched. Warn and keep going is pitchfork's call to make: a
// supervisor that refuses to start because one duration is misspelled is a supervisor
// that took the whole machine's daemons down with it.
let (settings, errors) = Settings::read_lossy(&resolved);
for error in &errors.0 {
warn!("{error}");
}
// Every setting declares a default, so the only way this is `None` is a setting added
// without one — a hole in the declaration rather than anything a user did.
let settings = settings.unwrap_or_else(|| {
warn!("a setting has no value and no default; falling back to built-in defaults");
Settings::default()
});
(settings, resolved)
}
/// The config file layers for `start_dir`, highest precedence first.
///
/// Project files are found by walking up from `start_dir`; within one
/// directory `pitchfork.local.toml` outranks `pitchfork.toml`, which
/// outranks the same pair under `.config/`, and any file in a nearer
/// directory outranks every file in a farther one. Below the project
/// files come the user-level and system-level configs.
///
/// Files that exist but cannot be parsed are warned about and skipped,
/// matching the previous loader: a broken file must not stop pitchfork
/// from starting.
fn file_layers_from(start_dir: &Path) -> Vec<FileLayer> {
let mut candidates: Vec<(PathBuf, FileScope)> = xx::file::find_up_all(
start_dir,
&[
"pitchfork.local.toml",
"pitchfork.toml",
".config/pitchfork.local.toml",
".config/pitchfork.toml",
],
)
.into_iter()
.map(|path| (path, FileScope::Project))
.collect();
let extras = crate::extra_configs::paths_for(start_dir)
.into_iter()
.rev()
.map(|p| (p, FileScope::Project));
candidates.splice(0..0, extras);
candidates.push((
crate::env::PITCHFORK_GLOBAL_CONFIG_USER.clone(),
FileScope::Global,
));
candidates.push((
crate::env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone(),
FileScope::System,
));
candidates
.into_iter()
.filter(|(path, _)| readable_settings_file(path))
.map(|(path, scope)| FileLayer::at(path, scope).under("settings"))
.collect()
}
/// Parse a duration string (humantime format) to Duration
pub fn parse_duration(s: &str) -> Option<std::time::Duration> {
humantime::parse_duration(s).ok()
}
/// Resolve the mise binary path.
///
/// If `general.mise_bin` is explicitly set, returns that path.
/// Otherwise, searches well-known install locations:
/// - `~/.local/bin/mise`
/// - `~/.cargo/bin/mise`
/// - `/usr/local/bin/mise`
/// - `/opt/homebrew/bin/mise`
/// - on Windows, `mise.exe` on `PATH`
///
/// Returns `None` if mise cannot be found.
pub fn resolve_mise_bin(&self) -> Option<std::path::PathBuf> {
self.resolve_mise_bin_with_path(std::env::var_os("PATH").as_deref())
}
/// [`Self::resolve_mise_bin`] with `path` in place of the `PATH` variable.
fn resolve_mise_bin_with_path(
&self,
path: Option<&std::ffi::OsStr>,
) -> Option<std::path::PathBuf> {
// Explicit configuration takes priority
if !self.general.mise_bin.is_empty() {
let p = PathBuf::from(&self.general.mise_bin);
if p.is_file() {
return Some(p);
}
warn!(
"mise_bin is set to {:?} but the file does not exist",
self.general.mise_bin
);
return None;
}
// Search well-known install paths
let home = crate::env::HOME_DIR.as_path();
let candidates = [
home.join(".local/bin/mise"),
home.join(".cargo/bin/mise"),
PathBuf::from("/usr/local/bin/mise"),
PathBuf::from("/opt/homebrew/bin/mise"),
];
candidates.into_iter().find(|p| p.is_file()).or_else(|| {
// Windows package managers install mise to locations of their
// own, none of them above, so look for it on PATH instead.
if cfg!(windows) {
find_in_path("mise.exe", path)
} else {
None
}
})
}
/// Resolve the shell used for daemon `run` scripts, `ready_cmd` /
/// `health_cmd` probes, lifecycle hooks and the log archive hook, split
/// into a program and its arguments.
///
/// `general.shell` applies everywhere. On Windows it applies only when it
/// was set explicitly (`shell_is_explicit`); a Windows machine that leaves
/// it at its default uses `general.windows_shell` instead, because the
/// `sh` that `general.shell` defaults to is not on a stock Windows `PATH`.
/// [`crate::settings::resolve_shell`] supplies that flag from the origin
/// of the merged value; it is a parameter here so the precedence can be
/// tested without a resolution.
///
/// `Err` names the key whose value is empty or could not be split.
pub fn resolve_shell(&self, shell_is_explicit: bool) -> Result<Vec<String>, String> {
let (key, configured) = if cfg!(windows) && !shell_is_explicit {
("general.windows_shell", &self.general.windows_shell)
} else {
("general.shell", &self.general.shell)
};
match shell_words::split(configured) {
Ok(parts) if !parts.is_empty() => Ok(parts),
Ok(_) => Err(format!("{key} setting is empty")),
Err(e) => Err(format!("failed to parse {key} setting {configured:?}: {e}")),
}
}
/// Return `supervisor.port_bump_attempts` as `u32`, clamping out-of-range
/// values to the schema default (10) and zero to 1.
///
/// This is the single source of truth for the fallback so that call-sites
/// don't each duplicate the hardcoded `10`.
pub fn default_port_bump_attempts(&self) -> u32 {
let v = u32::try_from(self.supervisor.port_bump_attempts).unwrap_or_else(|_| {
warn!(
"supervisor.port_bump_attempts value {} is out of range (0-{}), clamping to 10",
self.supervisor.port_bump_attempts,
u32::MAX
);
10
});
if v == 0 {
warn!("supervisor.port_bump_attempts is 0; defaulting to 1");
1
} else {
v
}
}
}
/// Whether `path` holds a settings file this loader can hand to a `FileLayer`.
///
/// Mirrors the previous loader's per-file error handling: a missing file is
/// the ordinary case, and a file that exists but cannot be read or parsed —
/// or whose `settings` key is not a table — is warned about and skipped
/// rather than turned into a startup failure.
fn readable_settings_file(path: &Path) -> bool {
if !path.exists() {
return false;
}
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
Err(e) => {
eprintln!(
"pitchfork: warning: failed to read {}: {}",
path.display(),
e
);
return false;
}
};
let table: toml::Table = match content.parse() {
Ok(table) => table,
Err(e) => {
eprintln!(
"pitchfork: warning: failed to parse {}: {}",
path.display(),
e
);
return false;
}
};
match table.get("settings") {
None => true,
Some(toml::Value::Table(_)) => true,
Some(_) => {
eprintln!(
"pitchfork: warning: invalid [settings] in {}: not a table",
path.display()
);
false
}
}
}
/// Validate every duration-typed setting in a resolution.
///
/// The registry's `duration` type stores the humantime text as-is, so an
/// invalid value would otherwise ride into the struct. This warns once and
/// rewrites the value to the schema default through [`Resolved::coerced`],
/// so `pitchfork settings get/list` and the typed getters all agree —
/// matching the previous loader, which rejected invalid durations at load
/// time. A value equal to the declared default is left alone (the
/// `logs.time_retention` default is the empty string, meaning "disabled").
/// Duration settings where `0s` is never meaningful: the value is passed
/// straight into `tokio::time::timeout` for a health probe, so a zero
/// timeout fails every probe immediately and would crash-kill a healthy
/// daemon after the retry threshold. Same defect family as the per-daemon
/// health timeout rejection in `config_types.rs` (`parse_positive_timeout`).
const NON_ZERO_DURATION_KEYS: &[&str] = &[
"supervisor.health_cmd_timeout",
"supervisor.health_http_timeout",
"supervisor.health_port_timeout",
];
fn sanitize_durations(resolved: &mut Resolved) {
let registry = Settings::SETTINGS_REGISTRY;
for id in registry.ids() {
let meta = registry.get(id);
if !matches!(meta.ty.inner(), Ty::Duration) {
continue;
}
let Some(Value::String(text)) = resolved.get(id) else {
continue;
};
let default_text = match meta.default {
Some(Const::Str(s)) => s,
_ => "",
};
if text == default_text {
continue;
}
let reason = match humantime::parse_duration(text) {
Err(_) => Some(format!("invalid duration {text:?}")),
Ok(d) if d.is_zero() && NON_ZERO_DURATION_KEYS.contains(&meta.key) => Some(format!(
"supervisor health probe timeout must be greater than 0, got {text:?}"
)),
Ok(_) => None,
};
let Some(reason) = reason else {
continue;
};
let origin = resolved
.origin(id)
.map(|o| o.describe().to_string())
.unwrap_or_default();
warn!("{reason} (set by {origin}), using default");
resolved.coerced(
id,
Value::String(default_text.to_string()),
format!("{reason}; the default stands"),
);
}
}
/// Global settings instance, kept beside the resolution it was read from
/// (RwLock<Arc> to support runtime reload).
type SettingsState = (Arc<Settings>, Arc<Resolved>);
static SETTINGS: std::sync::RwLock<Option<SettingsState>> = std::sync::RwLock::new(None);
fn settings_state() -> SettingsState {
// Fast path: if already initialized, clone the Arc pointers.
{
let lock = SETTINGS.read().unwrap();
if let Some(state) = lock.as_ref() {
return state.clone();
}
}
// Slow path: initialize on first access
let mut lock = SETTINGS.write().unwrap();
if let Some(state) = lock.as_ref() {
return state.clone();
}
let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
let state = (Arc::new(settings), Arc::new(resolved));
*lock = Some(state.clone());
state
}
/// Get the global settings instance
pub fn settings() -> Arc<Settings> {
settings_state().0
}
/// The origin-tracked resolution behind [`settings()`], for the settings CLI.
pub(crate) fn settings_resolved() -> Arc<Resolved> {
settings_state().1
}
/// Whether `general.shell` was set by the user rather than left at its default.
///
/// Asked of the merge, not of the text, the same way `pitchfork settings`
/// decides what to mark as default: `shell = "sh -c"` written in a config file
/// is the same string as the default, and only its origin tells them apart.
fn shell_is_explicit(resolved: &Resolved) -> bool {
resolved
.origin_key("general.shell")
.is_some_and(|origin| origin.kind != SourceKind::DEFAULTS)
}
/// The file called `name` in the first directory of `path` (a `PATH`-style
/// list) that holds one, as an absolute path.
///
/// A relative entry is looked up from this process's working directory, but
/// the result is used from a daemon's, so it is made absolute here.
fn find_in_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
std::env::split_paths(path?)
.map(|dir| dir.join(name))
.find(|candidate| candidate.is_file())
.and_then(|found| std::path::absolute(found).ok())
}
/// Resolve the shell for daemon `run` scripts, command probes and hooks from
/// the global settings. See [`Settings::resolve_shell`].
pub fn resolve_shell() -> Result<Vec<String>, String> {
let (settings, resolved) = settings_state();
settings.resolve_shell(shell_is_explicit(&resolved))
}
/// Reload settings from config files.
///
/// Called when the supervisor receives a ReloadConfig IPC request,
/// typically after `pitchfork settings set` modifies a config file.
///
/// Old Arc references remain valid until all holders drop them,
/// so no use-after-free can occur.
pub fn reload_settings() {
let (settings, resolved) = Settings::resolve_from_dir(&crate::env::CWD);
let mut lock = SETTINGS.write().unwrap();
*lock = Some((Arc::new(settings), Arc::new(resolved)));
}
// ============================================================================
// Partial (all-Option) mirror structs
//
// These exist for `pitchfork.toml` round-trips: `PitchforkToml` deserializes
// its `[settings]` table into `SettingsPartial`, merges per-file overrides,
// and serializes it back out (`pitchfork settings set`, `proxy add`, ...).
// Settings *resolution* no longer goes through these — usage-config's
// origin-tracked merge replaced the apply/merge chain.
// ============================================================================
macro_rules! settings_partial {
(
$(#[$meta:meta])*
$name:ident {
$(@group $group_field:ident: $group_ty:ty,)*
$($(#[$fdoc:meta])* $field:ident: $ty:ty,)*
}
) => {
$(#[$meta])*
#[derive(
Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(default)]
pub struct $name {
$(
#[serde(default, skip_serializing_if = "is_empty_partial")]
pub $group_field: $group_ty,
)*
$(
$(#[$fdoc])*
#[serde(skip_serializing_if = "Option::is_none", default)]
pub $field: Option<$ty>,
)*
}
#[allow(dead_code)]
impl $name {
/// Whether any field (or nested group field) is set.
pub fn has_any_set(&self) -> bool {
false
$(|| self.$group_field.has_any_set())*
$(|| self.$field.is_some())*
}
pub fn is_empty(&self) -> bool {
!self.has_any_set()
}
/// Merge another partial onto this one.
/// All `Some` values in `other` override the corresponding values in `self`.
pub fn merge_from(&mut self, other: &Self) {
$(self.$group_field.merge_from(&other.$group_field);)*
$(
if other.$field.is_some() {
self.$field = other.$field.clone();
}
)*
}
}
};
}
/// serde `skip_serializing_if` helper for nested partial groups.
fn is_empty_partial<T: HasAnySet>(v: &T) -> bool {
!v.has_any_set()
}
/// Internal trait so one serde skip helper serves every partial group.
trait HasAnySet {
fn has_any_set(&self) -> bool;
}
macro_rules! impl_has_any_set {
($($name:ident),+ $(,)?) => {
$(impl HasAnySet for $name {
fn has_any_set(&self) -> bool {
$name::has_any_set(self)
}
})+
};
}
settings_partial! {
/// Partial mirror of [`SettingsApi`].
SettingsApiPartial {
/// Automatically start the standalone API server
auto_start: bool,
/// IP address the API server binds to
bind_address: String,
/// Port the standalone API server listens on
bind_port: i64,
/// Number of consecutive ports to try if api.bind_port is in use
port_attempts: i64,
/// Authentication token for API access when bound to non-loopback addresses
token: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsBoot`].
SettingsBootPartial {
/// Absolute executable path written into boot registrations
executable: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsGeneral`].
SettingsGeneralPartial {
/// Delay before auto-stopping daemons when leaving a directory
autostop_delay: String,
/// Supervisor background task refresh interval
interval: String,
/// File log level (trace, debug, info, warn, error)
log_file_level: String,
/// Console log level (trace, debug, info, warn, error)
log_level: String,
/// Wrap daemon commands with mise x -- globally
mise: bool,
/// Explicit path to the mise binary
mise_bin: String,
/// Shell command used to execute daemon run scripts
shell: String,
/// Shell command used to execute daemon run scripts on Windows
windows_shell: String,
/// Show timestamps in startup log output
startup_log_timestamps: bool,
/// Default readiness delay in seconds when a daemon has no ready check configured
ready_delay: String,
/// Enable git worktree / jj workspace auto-discovery
worktree: bool,
}
}
settings_partial! {
/// Partial mirror of [`SettingsIpc`].
SettingsIpcPartial {
/// Number of connection retry attempts
connect_attempts: i64,
/// Maximum delay between connection retries
connect_max_delay: String,
/// Minimum delay between connection retries
connect_min_delay: String,
/// Maximum IPC requests per second per connection
rate_limit: i64,
/// Rate limit sliding window duration
rate_limit_window: String,
/// Default timeout for IPC requests
request_timeout: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsLogsArchiveHook`].
SettingsLogsArchiveHookPartial {
/// Maximum log entries per archive hook invocation
batch_size: i64,
/// Command to run before retention deletes old log entries
command: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsLogs`].
SettingsLogsPartial {
@group archive_hook: SettingsLogsArchiveHookPartial,
/// Count-based log retention (e.g. 10000)
line_retention: i64,
/// Default log format for daemons (json | logfmt | text)
log_format: String,
/// Time-based log retention duration (e.g. '7d', '30d')
time_retention: String,
/// Show timestamps in log output
timestamp: bool,
/// strftime format for log timestamps in `pitchfork logs` output
timestamp_format: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsProxy`].
SettingsProxyPartial {
/// Automatically start daemons when accessed via proxy URL
auto_start: bool,
/// Maximum time to wait for an auto-started daemon to become ready
auto_start_timeout: String,
/// Automatically install the proxy TLS certificate into the system trust store
auto_trust: bool,
/// Run a loopback DNS resolver for the proxy TLD
dns: bool,
/// Port the loopback DNS resolver listens on
dns_port: i64,
/// Enable the reverse proxy server for daemons
enable: bool,
/// Bind address for the reverse proxy server
host: String,
/// Enable HTTPS for the reverse proxy
https: bool,
/// Stop proxy-started daemons after this long without proxy activity
idle_timeout: String,
/// Enable LAN mode for the reverse proxy
lan: bool,
/// Pin a specific LAN IP address instead of auto-detecting
lan_ip: String,
/// Port the reverse proxy server listens on
port: i64,
/// Automatically sync slug hostnames to /etc/hosts (deprecated)
sync_hosts: bool,
/// Top-level domain used for proxy URLs
tld: String,
/// Path to TLS certificate file (PEM format) for HTTPS proxy
tls_cert: String,
/// Path to TLS private key file (PEM format) for HTTPS proxy
tls_key: String,
/// Enable wildcard subdomain matching for proxy routes
wildcard: bool,
/// Compatibility alias for general.worktree
worktree: bool,
}
}
settings_partial! {
/// Partial mirror of [`SettingsSupervisor`].
SettingsSupervisorPartial {
/// Automatically start the supervisor when a client command needs it
auto_start: bool,
/// Reconcile orphaned daemon processes when supervisor starts
cleanup_orphans: bool,
/// Enable container/PID1 mode for running inside Docker containers
container: bool,
/// Consecutive CPU-over-limit samples before killing a daemon
cpu_violation_threshold: i64,
/// Interval for checking cron schedules
cron_check_interval: String,
/// File watch debounce duration
file_watch_debounce: String,
/// Default time between health probes
health_check_interval: String,
/// Default consecutive health-check failures before killing a daemon
health_check_retries: i64,
/// Default per-probe timeout for health_cmd
health_cmd_timeout: String,
/// Default per-request timeout for health_http
health_http_timeout: String,
/// Default per-connect timeout for health_port
health_port_timeout: String,
/// Timeout for HTTP ready checks
http_client_timeout: String,
/// Daemon log buffer flush interval
log_flush_interval: String,
/// What to do with live orphaned daemons on supervisor startup: adopt or kill
orphan_policy: String,
/// Maximum port increment attempts when auto_bump_port is enabled
port_bump_attempts: i64,
/// Maximum time to wait for a oneshot daemon to finish
oneshot_timeout: String,
/// Interval between ready checks (HTTP, TCP, command)
ready_check_interval: String,
/// Delay between stop and start during restart
restart_delay: String,
/// Maximum time to wait for daemon to stop gracefully
stop_timeout: String,
/// Default user to run daemon processes as
user: String,
/// File watcher config refresh interval
watch_interval: String,
/// Polling watcher filesystem scan interval
watch_poll_interval: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsTui`].
SettingsTuiPartial {
/// Status message display duration
message_duration: String,
/// Daemon list refresh interval
refresh_rate: String,
/// Number of stat samples to keep for graphs
stat_history: i64,
/// Event loop tick rate
tick_rate: String,
}
}
settings_partial! {
/// Partial mirror of [`SettingsWeb`].
SettingsWebPartial {
/// Automatically start web UI when supervisor starts
auto_start: bool,
/// URL path prefix for the web UI (e.g. "ps" serves at /ps/)
base_path: String,
/// Web server bind address
bind_address: String,
/// Default web server port
bind_port: i64,
/// Initial number of log lines to display
log_lines: i64,
/// Number of ports to try if default is in use
port_attempts: i64,
/// Server-Sent Events poll interval for log streaming
sse_poll_interval: String,
}
}
settings_partial! {
/// Partial mirror of [`Settings`], for `[settings]` tables in
/// pitchfork.toml files.
SettingsPartial {
@group api: SettingsApiPartial,
@group boot: SettingsBootPartial,
@group general: SettingsGeneralPartial,
@group ipc: SettingsIpcPartial,
@group logs: SettingsLogsPartial,
@group proxy: SettingsProxyPartial,
@group supervisor: SettingsSupervisorPartial,
@group tui: SettingsTuiPartial,
@group web: SettingsWebPartial,
}
}
impl_has_any_set!(
SettingsApiPartial,
SettingsBootPartial,
SettingsGeneralPartial,
SettingsIpcPartial,
SettingsLogsArchiveHookPartial,
SettingsLogsPartial,
SettingsProxyPartial,
SettingsSupervisorPartial,
SettingsTuiPartial,
SettingsWebPartial,
);
impl SettingsPartial {
/// Move supported legacy keys to their canonical locations before a
/// read-modify-write cycle serializes this partial again.
pub(crate) fn canonicalize_aliases(&mut self) {
if self.general.worktree.is_none() {
self.general.worktree = self.proxy.worktree.take();
} else {
self.proxy.worktree = None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn find_in_path_takes_the_first_directory_that_has_the_file() {
let empty = tempfile::tempdir().unwrap();
let first = tempfile::tempdir().unwrap();
let second = tempfile::tempdir().unwrap();
std::fs::write(first.path().join("mise.exe"), "").unwrap();
std::fs::write(second.path().join("mise.exe"), "").unwrap();
// A directory with the name, not a file, does not count.
std::fs::create_dir(empty.path().join("mise.exe")).unwrap();
let path = std::env::join_paths([empty.path(), first.path(), second.path()]).unwrap();
assert_eq!(
find_in_path("mise.exe", Some(&path)),
Some(first.path().join("mise.exe"))
);
assert_eq!(find_in_path("missing.exe", Some(&path)), None);
assert_eq!(find_in_path("mise.exe", None), None);
}
#[cfg(windows)]
#[test]
fn resolve_mise_bin_finds_mise_exe_on_path_on_windows() {
let dir = tempfile::tempdir().unwrap();
let mise = dir.path().join("mise.exe");
std::fs::write(&mise, "").unwrap();
let path = std::env::join_paths([dir.path()]).unwrap();
// No `mise_bin`, and none of the Unix locations exist on Windows.
let settings = Settings::default();
assert_eq!(settings.resolve_mise_bin_with_path(Some(&path)), Some(mise));
assert_eq!(settings.resolve_mise_bin_with_path(None), None);
}
#[test]
fn find_in_path_returns_an_absolute_path_for_a_relative_entry() {
// A relative entry is found against the supervisor's working
// directory, but the path is used from the daemon's, so it has to be
// made absolute. Created in the working directory itself, which
// always exists, unlike a build directory Cargo may put elsewhere.
let dir = tempfile::tempdir_in(".").unwrap();
std::fs::write(dir.path().join("mise.exe"), "").unwrap();
let relative = dir
.path()
.strip_prefix(std::env::current_dir().unwrap())
.unwrap_or(dir.path());
assert!(relative.is_relative(), "{relative:?}");
let found = find_in_path("mise.exe", Some(relative.as_os_str())).unwrap();
assert!(found.is_absolute(), "{found:?}");
assert!(found.is_file());
}
#[test]
fn shell_defaults() {
let settings = Settings::default();
assert_eq!(settings.general.shell, "sh -c");
assert_eq!(settings.general.windows_shell, "cmd /C");
}
#[test]
fn shell_precedence() {
let mut settings = Settings::default();
settings.general.shell = "unix-sh -c".to_string();
settings.general.windows_shell = "win-sh /C".to_string();
let unix = vec!["unix-sh".to_string(), "-c".to_string()];
let windows = vec!["win-sh".to_string(), "/C".to_string()];
// An explicit general.shell wins on every platform.
assert_eq!(settings.resolve_shell(true).unwrap(), unix);
// Left at its default, general.shell yields to windows_shell on
// Windows and is the only setting consulted elsewhere.
let expected = if cfg!(windows) { windows } else { unix };
assert_eq!(settings.resolve_shell(false).unwrap(), expected);
}
#[test]
fn shell_is_explicit_comes_from_the_origin_not_the_text() {
// `PITCHFORK_SHELL="sh -c"` is the same string as the default, and
// must still count as set: on Windows it decides whether
// windows_shell is consulted at all.
let untouched =
resolve(Settings::SETTINGS_REGISTRY, Layers::new()).expect("resolving defaults");
assert!(!shell_is_explicit(&untouched));
let layer = EnvLayer::new([("PITCHFORK_SHELL".to_string(), "sh -c".to_string())]);
let explicit = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer))
.expect("resolving an override");
assert!(shell_is_explicit(&explicit));
}
#[test]
fn an_unusable_shell_names_the_key_it_came_from() {
let mut settings = Settings::default();
settings.general.shell = "sh -c 'unbalanced".to_string();
let err = settings.resolve_shell(true).unwrap_err();
assert!(err.contains("general.shell"), "{err}");
settings.general.shell = String::new();
let err = settings.resolve_shell(true).unwrap_err();
assert!(err.contains("general.shell setting is empty"), "{err}");
settings.general.windows_shell = String::new();
let key = if cfg!(windows) {
"general.windows_shell"
} else {
"general.shell"
};
let err = settings.resolve_shell(false).unwrap_err();
assert!(err.contains(key), "{err}");
}
#[test]
fn test_default_settings() {
let settings = Settings::default();
// Test general settings
assert_eq!(settings.general.autostop_delay, "1m");
assert_eq!(settings.general.interval, "10s");
assert_eq!(settings.general.log_level, "info");
assert_eq!(settings.general.ready_delay, "3s");
// Test IPC settings
assert_eq!(settings.ipc.connect_attempts, 5);
assert_eq!(settings.ipc.request_timeout, "5s");
assert_eq!(settings.ipc.rate_limit, 100);
// Test web settings
assert!(!settings.web.auto_start);
assert_eq!(settings.web.bind_address, "127.0.0.1");
assert_eq!(settings.web.bind_port, 3120);
assert_eq!(settings.web.log_lines, 100);
// Test TUI settings
assert_eq!(settings.tui.refresh_rate, "2s");
assert_eq!(settings.tui.stat_history, 60);
// Test supervisor settings
assert!(settings.supervisor.auto_start);
assert_eq!(settings.supervisor.ready_check_interval, "500ms");
assert_eq!(settings.supervisor.file_watch_debounce, "1s");
assert_eq!(settings.supervisor.user, "");
}
#[test]
fn a_bad_value_costs_only_its_own_setting() {
// `Settings::read` is all or nothing, and the fallback for its failure used to be
// `Settings::default()` — one field the merge could not hand to its type demoting all
// sixty-eight settings and discarding the environment along with them.
let env = EnvLayer::new([("PITCHFORK_LOG".to_string(), "debug".to_string())]);
let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
// The one door into a resolution the merge does not check: a post-merge hook, which is
// what `sanitize_durations` is. A bool where an integer belongs is what a buggy one
// could write.
let registry = Settings::SETTINGS_REGISTRY;
let rate_limit = registry.lookup("ipc.rate_limit").unwrap().id;
resolved.coerced(rate_limit, Value::Bool(true), "a hook that got it wrong");
assert!(
Settings::read(&resolved).is_err(),
"the strict read still refuses it"
);
let (settings, errors) = Settings::read_lossy(&resolved);
let settings = settings.expect("every setting declares a default");
assert_eq!(
settings.ipc.rate_limit, 100,
"the bad field takes its declared default"
);
assert_eq!(
settings.general.log_level, "debug",
"and PITCHFORK_LOG is not collateral damage"
);
assert_eq!(errors.0.len(), 1, "{errors}");
assert_eq!(errors.0[0].key, "ipc.rate_limit");
}
#[test]
fn every_setting_declares_a_default() {
// What makes the `None` arm of the lossy read unreachable: a setting with no value and
// no default is a hole in this file, not something a user can cause. Adding one without
// a default should fail here rather than silently demote the whole struct at runtime.
let missing: Vec<&str> = Settings::SETTINGS_PROPS
.iter()
.filter(|meta| meta.default.is_none())
.map(|meta| meta.key)
.collect();
assert!(
missing.is_empty(),
"these settings declare no default: {missing:?}"
);
}
#[test]
fn test_registry_matches_previous_schema() {
// The emitted config block is the settings documentation now; make
// sure the registry still declares what settings.toml used to.
let keys: Vec<&str> = Settings::SETTINGS_PROPS
.iter()
.map(|meta| meta.key)
.collect();
// 75 before either change, plus `supervisor.oneshot_timeout` from main,
// `proxy.dns` / `proxy.dns_port`, `proxy.idle_timeout`, and `boot.executable`.
assert_eq!(keys.len(), 80, "{keys:?}");
assert!(keys.contains(&"boot.executable"));
assert!(keys.contains(&"general.autostop_delay"));
assert!(keys.contains(&"supervisor.oneshot_timeout"));
assert!(keys.contains(&"logs.archive_hook.command"));
assert!(keys.contains(&"supervisor.health_check_interval"));
assert!(keys.contains(&"supervisor.watch_interval"));
assert!(keys.contains(&"proxy.dns"));
assert!(keys.contains(&"proxy.dns_port"));
assert!(keys.contains(&"proxy.idle_timeout"));
let registry = Settings::SETTINGS_REGISTRY;
let interval = registry.get(registry.lookup("general.interval").unwrap().id);
assert_eq!(interval.envs, &["PITCHFORK_INTERVAL"]);
assert_eq!(interval.deprecated_envs, &["PITCHFORK_INTERVAL_SECS"]);
let watch = registry.get(registry.lookup("supervisor.watch_interval").unwrap().id);
assert_eq!(watch.deprecated_envs, &["PITCHFORK_WATCH_INTERVAL_MS"]);
let log_level = registry.get(registry.lookup("general.log_level").unwrap().id);
assert_eq!(log_level.envs, &["PITCHFORK_LOG"]);
let worktree = registry.get(registry.lookup("general.worktree").unwrap().id);
assert_eq!(worktree.envs, &["PITCHFORK_WORKTREE"]);
assert_eq!(worktree.deprecated_envs, &["PITCHFORK_PROXY_WORKTREE"]);
assert_eq!(worktree.aliases, &["proxy.worktree"]);
assert_eq!(
registry.lookup("proxy.worktree").unwrap().id,
registry.lookup("general.worktree").unwrap().id,
);
let spec = Settings::spec_kdl();
let files = [
"file \"/etc/pitchfork/config.toml\" scope=\"system\" format=\"toml\"",
"file \"~/.config/pitchfork/config.toml\" scope=\"global\" format=\"toml\"",
"file \".config/pitchfork.toml\" findup=#true format=\"toml\"",
"file \".config/pitchfork.local.toml\" findup=#true format=\"toml\"",
"file \"pitchfork.toml\" findup=#true format=\"toml\"",
"file \"pitchfork.local.toml\" findup=#true format=\"toml\"",
];
let positions: Vec<usize> = files
.iter()
.map(|file| spec.find(file).unwrap_or_else(|| panic!("missing {file}")))
.collect();
assert!(
positions.windows(2).all(|pair| pair[0] < pair[1]),
"config files must be documented from lowest to highest precedence:\n{spec}"
);
}
#[test]
fn every_registry_key_round_trips_through_the_partial() {
// A setting added to the derive structs but missed in `settings_partial!`
// makes `pitchfork settings set` report success and write nothing.
for meta in Settings::SETTINGS_PROPS {
let value = match meta.ty.inner() {
Ty::Bool => toml::Value::Boolean(true),
Ty::Int | Ty::Uint => toml::Value::Integer(1),
_ => toml::Value::String("x".to_string()),
};
let parts: Vec<&str> = meta.key.split('.').collect();
let mut table = toml::Table::new();
let mut cursor = &mut table;
for part in &parts[..parts.len() - 1] {
cursor = cursor
.entry(part.to_string())
.or_insert_with(|| toml::Value::Table(toml::Table::new()))
.as_table_mut()
.unwrap();
}
cursor.insert(parts[parts.len() - 1].to_string(), value);
let partial: SettingsPartial = table.clone().try_into().unwrap();
let back = toml::Table::try_from(&partial).unwrap();
assert_eq!(
back, table,
"{} is declared in the registry but not mirrored in SettingsPartial",
meta.key
);
}
}
#[test]
fn test_parse_duration() {
assert_eq!(Settings::parse_duration("1s"), Some(Duration::from_secs(1)));
assert_eq!(
Settings::parse_duration("500ms"),
Some(Duration::from_millis(500))
);
assert_eq!(
Settings::parse_duration("1m"),
Some(Duration::from_secs(60))
);
assert_eq!(
Settings::parse_duration("2h"),
Some(Duration::from_secs(7200))
);
assert_eq!(Settings::parse_duration("invalid"), None);
}
#[test]
fn test_env_override() {
// The environment is described rather than reached for, so this test
// does not mutate process env vars (the old test needed a mutex).
let env = EnvLayer::new([
("PITCHFORK_AUTOSTOP_DELAY".to_string(), "10m".to_string()),
("PITCHFORK_INTERVAL".to_string(), "5s".to_string()),
(
"PITCHFORK_IPC_CONNECT_ATTEMPTS".to_string(),
"20".to_string(),
),
(
"PITCHFORK_SUPERVISOR_AUTO_START".to_string(),
"false".to_string(),
),
("PITCHFORK_WEB_AUTO_START".to_string(), "true".to_string()),
]);
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.autostop_delay, "10m");
assert_eq!(settings.general.interval, "5s");
assert_eq!(settings.ipc.connect_attempts, 20);
assert!(!settings.supervisor.auto_start);
assert!(settings.web.auto_start);
// Fields with no corresponding env var set remain at defaults
assert_eq!(settings.general.log_level, "info");
assert_eq!(settings.ipc.rate_limit, 100);
}
#[test]
fn test_deprecated_env_still_works_and_warns() {
let env = EnvLayer::new([
("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
]);
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.interval, "30s");
assert!(!settings.general.worktree);
let warnings = usage_rs::config::explain::warnings(&resolved);
assert!(
warnings
.iter()
.any(|w| w.contains("PITCHFORK_INTERVAL_SECS is deprecated")),
"{warnings:?}"
);
assert!(
warnings
.iter()
.any(|w| w.contains("PITCHFORK_PROXY_WORKTREE is deprecated")),
"{warnings:?}"
);
// The current name wins over the deprecated alias when both are set.
let env = EnvLayer::new([
("PITCHFORK_INTERVAL_SECS".to_string(), "30s".to_string()),
("PITCHFORK_INTERVAL".to_string(), "7s".to_string()),
("PITCHFORK_PROXY_WORKTREE".to_string(), "false".to_string()),
("PITCHFORK_WORKTREE".to_string(), "true".to_string()),
]);
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.interval, "7s");
assert!(settings.general.worktree);
}
#[test]
fn test_invalid_duration_from_env_falls_back_to_default() {
// The previous loader rejected invalid durations at load time; the
// sanitize pass reproduces that through Resolved::coerced.
let env = EnvLayer::new([(
"PITCHFORK_AUTOSTOP_DELAY".to_string(),
"not_a_duration".to_string(),
)]);
let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
sanitize_durations(&mut resolved);
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.autostop_delay, "1m");
assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
}
#[test]
fn test_zero_health_timeout_from_env_falls_back_to_default() {
// A zero health probe timeout goes straight into tokio::time::timeout
// and fails every probe immediately; the sanitize pass falls back to
// the schema default like any other invalid duration.
let env = EnvLayer::new([
("PITCHFORK_HEALTH_CMD_TIMEOUT".to_string(), "0s".to_string()),
(
"PITCHFORK_HEALTH_HTTP_TIMEOUT".to_string(),
"0s".to_string(),
),
(
"PITCHFORK_HEALTH_PORT_TIMEOUT".to_string(),
"0s".to_string(),
),
]);
let mut resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&env)).unwrap();
sanitize_durations(&mut resolved);
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.supervisor.health_cmd_timeout, "10s");
assert_eq!(
settings.supervisor_health_cmd_timeout(),
Duration::from_secs(10)
);
assert_eq!(settings.supervisor.health_http_timeout, "5s");
assert_eq!(settings.supervisor.health_port_timeout, "5s");
}
#[test]
fn test_invalid_duration_fallback() {
let mut settings = Settings::default();
// Set invalid duration values
settings.general.autostop_delay = "invalid".to_string();
settings.general.interval = "not_a_duration".to_string();
// Convenience methods should fallback to default values
assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60)); // default "1m"
assert_eq!(settings.general_interval(), Duration::from_secs(10)); // default "10s"
}
#[test]
fn oneshot_wait_defaults_to_an_hour() {
use crate::config_types::OneshotWait;
let settings = Settings::default();
assert_eq!(
settings.supervisor_oneshot_timeout(),
Duration::from_secs(3600)
);
assert_eq!(
settings.supervisor_oneshot_wait(),
OneshotWait::For(Duration::from_secs(3600))
);
}
#[test]
fn oneshot_wait_of_zero_means_no_deadline_at_all() {
// A task's natural end is its exit, so `0` has to read as "wait",
// never as "give up immediately" — and never as a distant substitute
// deadline that a long enough task could still outlive.
use crate::config_types::OneshotWait;
let mut settings = Settings::default();
for value in ["0", "0s"] {
settings.supervisor.oneshot_timeout = value.to_string();
assert!(settings.supervisor_oneshot_timeout().is_zero());
assert_eq!(
settings.supervisor_oneshot_wait(),
OneshotWait::Unlimited,
"{value} should wait without a deadline"
);
assert_eq!(settings.supervisor_oneshot_wait().duration(), None);
}
}
#[test]
fn oneshot_wait_honours_a_configured_value() {
use crate::config_types::OneshotWait;
let mut settings = Settings::default();
settings.supervisor.oneshot_timeout = "6h".to_string();
assert_eq!(
settings.supervisor_oneshot_wait(),
OneshotWait::For(Duration::from_secs(6 * 3600))
);
assert_eq!(
settings.supervisor_oneshot_wait().duration(),
Some(Duration::from_secs(6 * 3600))
);
}
#[test]
fn test_duration_methods_all_fields() {
let settings = Settings::default();
assert_eq!(settings.general_autostop_delay(), Duration::from_secs(60));
assert_eq!(settings.general_interval(), Duration::from_secs(10));
assert_eq!(settings.general_ready_delay(), Duration::from_secs(3));
assert_eq!(settings.ipc_connect_min_delay(), Duration::from_millis(100));
assert_eq!(settings.ipc_connect_max_delay(), Duration::from_secs(1));
assert_eq!(settings.ipc_request_timeout(), Duration::from_secs(5));
assert_eq!(settings.ipc_rate_limit_window(), Duration::from_secs(1));
assert_eq!(settings.web_sse_poll_interval(), Duration::from_millis(500));
assert_eq!(settings.tui_refresh_rate(), Duration::from_secs(2));
assert_eq!(settings.tui_tick_rate(), Duration::from_millis(100));
assert_eq!(settings.tui_message_duration(), Duration::from_secs(3));
assert_eq!(
settings.supervisor_ready_check_interval(),
Duration::from_millis(500)
);
assert_eq!(
settings.supervisor_file_watch_debounce(),
Duration::from_secs(1)
);
assert_eq!(
settings.supervisor_log_flush_interval(),
Duration::from_millis(500)
);
assert_eq!(settings.supervisor_stop_timeout(), Duration::from_secs(5));
assert_eq!(
settings.supervisor_restart_delay(),
Duration::from_millis(100)
);
assert_eq!(
settings.supervisor_cron_check_interval(),
Duration::from_secs(10)
);
assert_eq!(
settings.supervisor_http_client_timeout(),
Duration::from_secs(5)
);
}
#[test]
fn test_general_ready_delay_secs() {
let mut settings = Settings::default();
// Default "3s" resolves to whole seconds.
assert_eq!(settings.general_ready_delay_secs(), Ok(3));
// Subsecond values are rejected, not silently truncated by as_secs().
settings.general.ready_delay = "500ms".to_string();
let err = settings.general_ready_delay_secs().unwrap_err();
assert!(err.contains("500ms"), "unexpected error: {err}");
assert!(
err.contains("whole number of seconds"),
"unexpected error: {err}"
);
settings.general.ready_delay = "1.5s".to_string();
let err = settings.general_ready_delay_secs().unwrap_err();
assert!(err.contains("1.5s"), "unexpected error: {err}");
// Empty string falls back to the schema default "3s".
settings.general.ready_delay = String::new();
assert_eq!(settings.general_ready_delay_secs(), Ok(3));
// Whole-second values resolve as seconds.
settings.general.ready_delay = "90s".to_string();
assert_eq!(settings.general_ready_delay_secs(), Ok(90));
}
/// A directory tree, cleaned up when the test ends.
struct Tree(std::path::PathBuf);
impl Tree {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir()
.join(format!("pitchfork_settings_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn write(&self, rel: &str, text: &str) -> std::path::PathBuf {
let path = self.0.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(&path, text).unwrap();
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn test_settings_read_from_pitchfork_toml_settings_table() {
let tree = Tree::new("table");
let path = tree.write(
"pitchfork.toml",
r#"
[daemons.myapp]
run = "node server.js"
[settings.general]
autostop_delay = "5m"
log_level = "debug"
[settings.web]
auto_start = true
bind_port = 8080
[settings.supervisor]
auto_start = false
user = "postgres"
"#,
);
let layer = FileLayer::at(&path, FileScope::Project).under("settings");
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.autostop_delay, "5m");
assert_eq!(settings.general.log_level, "debug");
assert!(settings.web.auto_start);
assert_eq!(settings.web.bind_port, 8080);
assert!(!settings.supervisor.auto_start);
assert_eq!(settings.supervisor.user, "postgres");
// Unset fields fall back to defaults, and [daemons] is not a warning.
assert_eq!(settings.general.interval, "10s");
assert_eq!(settings.ipc.connect_attempts, 5);
assert!(resolved.warnings.is_empty(), "{:?}", resolved.warnings);
}
#[test]
fn test_proxy_worktree_config_alias_still_works() {
let tree = Tree::new("proxy_worktree_alias");
let path = tree.write("pitchfork.toml", "[settings.proxy]\nworktree = false\n");
let layer = FileLayer::at(&path, FileScope::Project).under("settings");
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert!(!settings.general.worktree);
assert_eq!(
resolved.get(
Settings::SETTINGS_REGISTRY
.lookup("general.worktree")
.unwrap()
.id
),
Some(&Value::Bool(false)),
);
}
#[test]
fn test_explicit_default_value_in_higher_file_still_overrides() {
// "Bug 5": the old merge_from skipped values equal to the default, so
// a higher-precedence file explicitly setting log_level = "info"
// could not override "warn" from a lower one. usage-config's
// origin-tracked merge does this natively; pin it.
let tree = Tree::new("bug5");
let lower = tree.write("lower.toml", "[settings.general]\nlog_level = \"warn\"\n");
let higher = tree.write("higher.toml", "[settings.general]\nlog_level = \"info\"\n");
let lower = FileLayer::at(&lower, FileScope::Global).under("settings");
let higher = FileLayer::at(&higher, FileScope::Project).under("settings");
let resolved = resolve(
Settings::SETTINGS_REGISTRY,
Layers::new().then(&higher).then(&lower),
)
.unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.log_level, "info");
// And the provenance says the higher file set it, not the default.
let id = Settings::SETTINGS_REGISTRY
.lookup("general.log_level")
.unwrap()
.id;
let origin = resolved.origin(id).unwrap().describe();
assert!(origin.contains("higher.toml"), "{origin}");
}
#[test]
fn boot_executable_rejects_project_config() {
let tree = Tree::new("boot-scope");
let project = tree.write(
"pitchfork.toml",
"[settings.boot]\nexecutable = \"/tmp/project/pitchfork\"\n",
);
let global = tree.write(
"config.toml",
"[settings.boot]\nexecutable = \"/opt/pitchfork/stable\"\n",
);
let project = FileLayer::at(&project, FileScope::Project).under("settings");
let global = FileLayer::at(&global, FileScope::Global).under("settings");
let resolved = resolve(
Settings::SETTINGS_REGISTRY,
Layers::new().then(&project).then(&global),
)
.unwrap();
assert_eq!(
Settings::read(&resolved).unwrap().boot.executable,
"/opt/pitchfork/stable"
);
assert!(resolved.warnings.iter().any(|warning| {
warning.message.contains("boot.executable") && warning.message.contains("cannot be set")
}));
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&project)).unwrap();
assert!(
Settings::read(&resolved)
.unwrap()
.boot
.executable
.is_empty()
);
}
#[test]
fn test_file_precedence_local_over_base_and_nearer_dir_wins() {
let tree = Tree::new("precedence");
tree.write("pitchfork.toml", "[settings.general]\ninterval = \"9s\"\n");
tree.write(
"pitchfork.local.toml",
"[settings.general]\ninterval = \"2s\"\n",
);
tree.write(
".config/pitchfork.toml",
"[settings.general]\ninterval = \"7s\"\n[settings.web]\nbind_port = 9999\n",
);
let layers = Settings::file_layers_from(&tree.0);
let mut chain = Layers::new();
for layer in &layers {
chain = chain.then(layer);
}
let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
let settings = Settings::read(&resolved).unwrap();
// pitchfork.local.toml > pitchfork.toml > .config/pitchfork.toml
assert_eq!(settings.general.interval, "2s");
// A key only the lowest file sets still applies.
assert_eq!(settings.web.bind_port, 9999);
// A nested directory's file outranks everything above it.
let deep = tree.0.join("a").join("b");
std::fs::create_dir_all(&deep).unwrap();
tree.write(
"a/b/pitchfork.toml",
"[settings.general]\ninterval = \"1s\"\n",
);
let layers = Settings::file_layers_from(&deep);
let mut chain = Layers::new();
for layer in &layers {
chain = chain.then(layer);
}
let resolved = resolve(Settings::SETTINGS_REGISTRY, chain).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.interval, "1s");
}
#[test]
fn test_broken_file_is_skipped_rather_than_fatal() {
let tree = Tree::new("broken");
let broken = tree.write("pitchfork.toml", "[invalid toml [[");
// The broken file is skipped with a warning, so the resolution still
// happens and produces the defaults.
let layers = Settings::file_layers_from(&tree.0);
assert!(
layers.iter().all(|layer| !layer.paths().contains(&broken)),
"the broken project file must not become a settings layer"
);
}
#[test]
fn test_unknown_settings_keys_do_not_fail_the_load() {
// Forward compatibility: a config written for a newer pitchfork must
// still load. Unknown keys are warned about rather than fatal.
let tree = Tree::new("unknown");
let path = tree.write(
"pitchfork.toml",
"[settings.general]\nlog_level = \"debug\"\nfrom_the_future = true\n",
);
let layer = FileLayer::at(&path, FileScope::Project).under("settings");
let resolved = resolve(Settings::SETTINGS_REGISTRY, Layers::new().then(&layer)).unwrap();
let settings = Settings::read(&resolved).unwrap();
assert_eq!(settings.general.log_level, "debug");
assert_eq!(resolved.warnings.len(), 1, "{:?}", resolved.warnings);
}
#[test]
fn test_partial_merge_from() {
let mut base = SettingsPartial::default();
base.general.log_level = Some("warn".to_string());
base.web.bind_address = Some("0.0.0.0".to_string());
let mut overlay = SettingsPartial::default();
overlay.general.log_level = Some("debug".to_string());
overlay.tui.refresh_rate = Some("1s".to_string());
base.merge_from(&overlay);
assert_eq!(base.general.log_level.as_deref(), Some("debug"));
assert_eq!(base.web.bind_address.as_deref(), Some("0.0.0.0"));
assert_eq!(base.tui.refresh_rate.as_deref(), Some("1s"));
// An empty partial changes nothing.
let sealed = base.clone();
base.merge_from(&SettingsPartial::default());
assert_eq!(base.general.log_level, sealed.general.log_level);
assert!(SettingsPartial::default().is_empty());
assert!(base.has_any_set());
}
#[test]
fn test_partial_serialization_skips_unset() {
let mut partial = SettingsPartial::default();
partial.general.interval = Some("5s".to_string());
let toml = toml::to_string_pretty(&partial).unwrap();
assert_eq!(toml, "[general]\ninterval = \"5s\"\n");
}
}