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
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
|
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: build.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Build command - compile packages from ports
******************************************************************************/
module commands.build
import sys.args
import sys.process
import io.file
import io.dir
import io.path
import io.console
import core.str
import core.port
import core.config
import core.database
import core.resolver
import util.version as ver
import types
import util.color
import util.prompt
import util.checksum
import util.archive
import util.mtree
import util.http as uhttp
import exitcodes as ec
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
// Build context
type BuildContext = struct
port: types.Port
work_dir: string
pkg_dir: string
src_dir: string
cfg: config.Config
noclean: bool
force_clean: bool
log_file: string
logging: bool
quiet: bool
end BuildContext
// Load a port from path or find it by name
fn load_or_find_port(port_path: string): types.PortResult
// Check if it's a valid port directory (must contain package.toml)
// This prevents confusion with binary files or other directories with same name
if dir.dir_exists(port_path)
let toml_path = path.join_path(port_path, "package.toml")
if file.fileExists(toml_path)
color.print_action("Loading port from: " + port_path)
return port.load(port_path)
end if
end if
// Not a valid port directory, search by name
color.print_action("Finding port: " + port_path)
return port.find(port_path)
end load_or_find_port
fn execute(opts: types.GlobalOptions): int
// Parse arguments
let argc = args.count()
// Port argument should be after the command
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Parse flags
mut noclean = false
mut force_clean = false
mut quiet_flag = false
mut verbose_flag = false
mut install_flag = false
mut port_path = ""
mut i = opts.cmd_index + 1
while i < argc
let arg = args.get(i)
// Skip global flags with values
if arg == "--root" or arg == "--prefix"
i = i + 2
continue
elif arg == "--no-chroot-scripts"
i = i + 1 // valueless flag: skip only itself
continue
end if
if arg == "--noclean" or arg == "-n"
noclean = true
elif arg == "--clean" or arg == "-c"
force_clean = true
elif arg == "--quiet" or arg == "-q"
quiet_flag = true
elif arg == "--verbose" or arg == "-v"
verbose_flag = true
elif arg == "--install"
install_flag = true
elif arg == "--no-install"
install_flag = false
elif not str.starts_with(arg, "-")
if str.length(port_path) == 0
port_path = arg
end if
end if
i = i + 1
end while
if str.length(port_path) == 0
print_usage()
return ec.EXIT_USAGE()
end if
// Handle "." for current directory
if port_path == "."
port_path = res.unwrap_or(dir.current_dir(), "")
end if
// Load configuration
let cfg = config.load()
uhttp.enable_proxy(config.get_use_proxy(cfg))
// Try to find the port by name if path doesn't exist
let result = load_or_find_port(port_path)
if not result.success
color.print_error(result.error)
return ec.EXIT_PKG_NOT_FOUND()
end if
let p = result.port
color.print_success("Loaded port: " + p.info.name + " " + p.info.version)
// Dry-run: show build plan without executing
if opts.dry_run
color.print_info("Dry run — would build: " + p.info.name + " " + p.info.version)
let dry_resolve = resolver.resolve_build_deps(p.info.name)
if dry_resolve.success and dry_resolve.count > 1
color.print_info("Dependencies to build first:")
mut di = 0
while di < dry_resolve.count - 1
let dep_port = port.find(dry_resolve.packages[di])
if dep_port.success
color.print_info(" " + dry_resolve.packages[di] + " " + dep_port.port.info.version)
else
color.print_info(" " + dry_resolve.packages[di])
end if
di = di + 1
end while
end if
color.print_info("Dry run — no changes made")
return ec.EXIT_SUCCESS()
end if
// Resolve, build, and install missing dependencies before building
if not resolve_and_build_deps(p, opts, cfg)
// Check if the failure was due to circular dependencies
let check_result = resolver.resolve_build_deps(p.info.name)
if not check_result.success and str.starts_with(check_result.error, "Circular")
color.print_error("Cannot build " + p.info.name + " — circular dependency")
return ec.EXIT_DEPS_CIRCULAR()
end if
color.print_error("Cannot build " + p.info.name + " — missing dependencies")
return ec.EXIT_DEPS_UNMET()
end if
// Determine quiet mode: CLI flag overrides config, verbose overrides quiet
mut quiet_mode = config.get_quiet(cfg)
if quiet_flag
quiet_mode = true
end if
if verbose_flag
quiet_mode = false
end if
// Create build context
let ctx = create_context(p, cfg, noclean, force_clean, quiet_mode)
// Step 1: Setup directories
if not setup_directories(ctx)
color.print_error("Failed to create build directories")
return ec.EXIT_ERROR()
end if
// Initialize logging after directories are created
init_log(ctx)
if ctx.logging and str.length(ctx.log_file) > 0
log_info(ctx, "Log file: " + ctx.log_file)
end if
// Step 2: Download sources
if not download_sources(ctx)
log_error(ctx, "Failed to download sources")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_DOWNLOAD_FAILED()
end if
// Step 3: Verify checksums
if not verify_checksums(ctx)
log_error(ctx, "Checksum verification failed")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_CHECKSUM_FAILED()
end if
// Step 4: Extract sources
if not extract_sources(ctx)
log_error(ctx, "Failed to extract sources")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_EXTRACT_FAILED()
end if
// Step 5: Apply patches
if not apply_patches(ctx)
log_error(ctx, "Failed to apply patches")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_PATCH_FAILED()
end if
// Step 6: Run build script
if not run_build(ctx)
log_error(ctx, "Build failed")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_BUILD_FAILED()
end if
// Step 7: Compress man pages (if enabled)
if config.get_compress_man(ctx.cfg)
compress_man_pages(ctx)
end if
// Step 8: Create package
if not create_package(ctx)
log_error(ctx, "Failed to create package")
print_log_location(ctx)
cleanup_build(ctx)
return ec.EXIT_PACKAGE_FAILED()
end if
// Success!
let pkg_name = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_name)
log_success(ctx, "Package created: " + pkg_path)
// Cleanup work directory on success
cleanup_build(ctx)
// Step 9: Install the built package (only with --install)
if install_flag
color.print_action("Installing " + p.info.name + "...")
let self_exe = args.get(0)
let install_cmd = self_exe + " install -y -f \"" + pkg_path + "\""
let install_pid = process.process_spawn_shell(install_cmd)
if install_pid < 0
color.print_error("Failed to launch installer for " + p.info.name)
return ec.EXIT_INSTALL_FAILED()
end if
let install_exit = process.process_wait(install_pid)
if install_exit != 0
color.print_error("Failed to install " + p.info.name)
return ec.EXIT_INSTALL_FAILED()
end if
else
color.print_success("Package ready (use --install to install, or: coral install \"" + pkg_path + "\")")
end if
return ec.EXIT_SUCCESS()
end execute
proc print_usage()
println("Usage: coral build [options] <port-path>")
println("")
println("Build a package from a port directory.")
println("")
println("Arguments:")
println(" <port-path> Path to port directory (use . for current)")
println("")
println("Options:")
println(" --install Install the package after building")
println(" --no-install Build only, do not install (default)")
println(" -n, --noclean Don't clean work/pkg directories after build")
println(" -c, --clean Force cleanup even if disabled in config")
println(" -q, --quiet Hide subprocess output (still logged to file)")
println(" -v, --verbose Show all output (overrides quiet)")
println("")
println("Examples:")
println(" coral build /usr/zports/base/vim")
println(" coral build --install base/vim")
println(" coral build --noclean .")
println(" coral build --quiet vim")
end print_usage
// Resolve all build dependencies recursively, build from source, and install each.
// Returns true if all dependencies are satisfied (either already installed or built+installed).
fn resolve_and_build_deps(p: types.Port, opts: types.GlobalOptions, cfg: config.Config): bool
// Resolve the full dependency tree (runtime + build deps, recursive)
let resolve_result = resolver.resolve_build_deps(p.info.name)
if not resolve_result.success
color.print_error("Dependency resolution failed: " + resolve_result.error)
return false
end if
// The result includes the target package as the last element — strip it
mut dep_count = resolve_result.count
if dep_count > 0
let last = resolve_result.packages[dep_count - 1]
if str.equals(last, p.info.name)
dep_count = dep_count - 1
end if
end if
// No deps to build
if dep_count == 0
return true
end if
// Look up version info for each dep to display in the build plan
mut dep_versions: [string] = new [string](256)
mut i = 0
while i < dep_count
let dep_port_result = port.find(resolve_result.packages[i])
if dep_port_result.success
dep_versions[i] = dep_port_result.port.info.version
else
dep_versions[i] = ""
end if
i = i + 1
end while
// Show build plan and ask for confirmation
if not prompt.confirm_build_plan(resolve_result.packages, dep_versions, dep_count, p.info.name, opts)
color.print_info("Build cancelled")
return false
end if
// Build and install each dependency in topological order
i = 0
while i < dep_count
let dep_name = resolve_result.packages[i]
println("")
color.print_action("[" + int_to_str(i + 1) + "/" + int_to_str(dep_count) + "] Building dependency: " + dep_name)
// Build the dependency from source
if not build_single_port(dep_name, cfg, opts)
color.print_error("Failed to build dependency: " + dep_name)
return false
end if
// Install the built package
let dep_port_result = port.find(dep_name)
if not dep_port_result.success
color.print_error("Cannot find port after build: " + dep_name)
return false
end if
let dp = dep_port_result.port
let pkg_filename = dp.info.name + "-" + dp.info.version + "-" + int_to_str(dp.info.release) + ".pkg.tar.xz"
let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_filename)
if not file.fileExists(pkg_path)
color.print_error("Built package not found: " + pkg_path)
return false
end if
color.print_action("Installing " + dep_name + "...")
let self_exe = args.get(0)
let install_cmd = self_exe + " install -y \"" + pkg_path + "\""
let pid = process.process_spawn_shell(install_cmd)
if pid < 0
color.print_error("Failed to launch installer for " + dep_name)
return false
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Failed to install " + dep_name)
return false
end if
color.print_success("Dependency ready: " + dep_name)
i = i + 1
end while
println("")
color.print_success("All " + int_to_str(dep_count) + " dependencies built and installed")
return true
end resolve_and_build_deps
// Build a single port from source. Used for dependency builds.
// Returns true if build succeeds and package archive is created.
fn build_single_port(name: string, cfg: config.Config, opts: types.GlobalOptions): bool
let port_result = port.find(name)
if not port_result.success
color.print_error("Port not found: " + name)
return false
end if
let p = port_result.port
// Determine quiet mode
mut quiet_mode = config.get_quiet(cfg)
if opts.verbose
quiet_mode = false
end if
if opts.quiet
quiet_mode = true
end if
let ctx = create_context(p, cfg, false, false, quiet_mode)
// Run the full build pipeline
if not setup_directories(ctx)
color.print_error("Failed to create build directories for " + name)
return false
end if
init_log(ctx)
if not download_sources(ctx)
log_error(ctx, "Failed to download sources for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
if not verify_checksums(ctx)
log_error(ctx, "Checksum verification failed for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
if not extract_sources(ctx)
log_error(ctx, "Failed to extract sources for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
if not apply_patches(ctx)
log_error(ctx, "Failed to apply patches for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
if not run_build(ctx)
log_error(ctx, "Build failed for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
// Compress man pages (if enabled)
if config.get_compress_man(cfg)
compress_man_pages(ctx)
end if
if not create_package(ctx)
log_error(ctx, "Failed to create package for " + name)
print_log_location(ctx)
cleanup_build(ctx)
return false
end if
let pkg_filename = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
let pkg_path = path.join_path(config.get_packages_dir(cfg), pkg_filename)
log_success(ctx, "Package created: " + pkg_path)
cleanup_build(ctx)
return true
end build_single_port
fn create_context(p: types.Port, cfg: config.Config, noclean: bool, force_clean: bool, quiet: bool): BuildContext
// New directory structure:
// /usr/zports/pkgs/build/<pkgname>/src/ - extracted sources, compilation
// /usr/zports/pkgs/build/<pkgname>/stage/ - DESTDIR for make install
let build_base = config.get_build_dir(cfg)
let pkg_build_dir = path.join_path(build_base, p.info.name)
let work_dir = path.join_path(pkg_build_dir, "src")
let pkg_dir = path.join_path(pkg_build_dir, "stage")
// Generate log file path with timestamp (in package build root, not src/)
let logging_enabled = config.get_logging(cfg)
mut log_path = ""
if logging_enabled
log_path = path.join_path(pkg_build_dir, "coral-build-" + p.info.name + "-" + get_timestamp() + ".log")
end if
return BuildContext{
port: p,
work_dir: work_dir,
pkg_dir: pkg_dir,
src_dir: "",
cfg: cfg,
noclean: noclean,
force_clean: force_clean,
log_file: log_path,
logging: logging_enabled,
quiet: quiet
}
end create_context
// Get current timestamp for log filename
fn get_timestamp(): string
// Use date command to get timestamp
let tmp_file = "/tmp/coral_ts_" + int_to_str(process.getpid()) + ".txt"
let cmd = "date '+%Y%m%d-%H%M%S' > \"" + tmp_file + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
let ts = res.unwrap_or(file.readFile(tmp_file), "")
// Cleanup
let rm_cmd = "rm -f \"" + tmp_file + "\""
let rm_pid = process.process_spawn_shell(rm_cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
return str.trim(ts, '\n')
end get_timestamp
// Initialize log file with header
proc init_log(ctx: BuildContext)
if not ctx.logging
return
end if
mut header = "=== Coral Build Log ===\n"
header = header + "Package: " + ctx.port.info.name + "\n"
header = header + "Version: " + ctx.port.info.version + "\n"
header = header + "Work Dir: " + ctx.work_dir + "\n"
header = header + "Log File: " + ctx.log_file + "\n"
header = header + "========================\n\n"
file.writeFile(ctx.log_file, header)
end init_log
// Log a message to file and optionally to screen
proc log_msg(ctx: BuildContext, msg: string, show_screen: bool)
// Always write to log file if logging enabled
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, msg + "\n")
end if
// Show on screen unless quiet mode suppresses it
if show_screen
println(msg)
end if
end log_msg
// Log info message (always show on screen)
proc log_info(ctx: BuildContext, msg: string)
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[INFO] " + msg + "\n")
end if
color.print_info(msg)
end log_info
// Log success message (always show on screen)
proc log_success(ctx: BuildContext, msg: string)
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[OK] " + msg + "\n")
end if
color.print_success(msg)
end log_success
// Log error message (always show on screen)
proc log_error(ctx: BuildContext, msg: string)
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[ERROR] " + msg + "\n")
end if
color.print_error(msg)
end log_error
// Log action message (always show on screen)
proc log_action(ctx: BuildContext, msg: string)
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[ACTION] " + msg + "\n")
end if
color.print_action(msg)
end log_action
// Log warning message (always show on screen)
proc log_warning(ctx: BuildContext, msg: string)
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[WARN] " + msg + "\n")
end if
color.print_warning(msg)
end log_warning
// Print log file location (for debugging failed builds)
proc print_log_location(ctx: BuildContext)
if ctx.logging and str.length(ctx.log_file) > 0
color.print_info("Build log: " + ctx.log_file)
end if
end print_log_location
// Run a shell command with output captured to log
// Returns exit code
fn run_logged_cmd(ctx: BuildContext, cmd: string): int
if ctx.logging and str.length(ctx.log_file) > 0
file.appendFile(ctx.log_file, "[CMD] " + cmd + "\n")
end if
// Build command that logs output to file
// Redirects all output to log file to avoid tee pipeline issues
// (tee caused SIGPIPE on long builds and masked exit codes)
mut full_cmd = cmd
if ctx.logging and str.length(ctx.log_file) > 0
// Both quiet and normal mode: log to file only
// Real-time terminal output is sacrificed for build reliability
full_cmd = "(" + cmd + ") >> \"" + ctx.log_file + "\" 2>&1"
else
if ctx.quiet
// No logging, quiet mode: suppress output
full_cmd = "(" + cmd + ") >/dev/null 2>&1"
end if
// No logging, not quiet: just run normally
end if
// Flush stdout before spawning subprocess to ensure proper output ordering
console.flushOutput()
let pid = process.process_spawn_shell(full_cmd)
if pid < 0
return -1
end if
return process.process_wait(pid)
end run_logged_cmd
fn setup_directories(ctx: BuildContext): bool
color.print_info("Setting up build directories...")
// Create work directory
if dir.dir_exists(ctx.work_dir)
// Clean existing work dir
let cmd = "rm -rf \"" + ctx.work_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
end if
if not res.is_ok(dir.create_dir_all(ctx.work_dir))
return false
end if
// Create pkg directory (for DESTDIR)
if dir.dir_exists(ctx.pkg_dir)
let cmd = "rm -rf \"" + ctx.pkg_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
end if
if not res.is_ok(dir.create_dir_all(ctx.pkg_dir))
return false
end if
// Ensure sources directory exists
let sources_dir = config.get_sources_dir(ctx.cfg)
if not dir.dir_exists(sources_dir)
if not res.is_ok(dir.create_dir_all(sources_dir))
return false
end if
end if
// Ensure packages directory exists
let packages_dir = config.get_packages_dir(ctx.cfg)
if not dir.dir_exists(packages_dir)
if not res.is_ok(dir.create_dir_all(packages_dir))
return false
end if
end if
return true
end setup_directories
fn download_sources(ctx: BuildContext): bool
if ctx.port.sources.count == 0
color.print_info("No sources to download")
return true
end if
color.print_info("Downloading sources...")
let sources_dir = config.get_sources_dir(ctx.cfg)
mut i = 0
while i < ctx.port.sources.count
let src = ctx.port.sources.sources[i]
let filename = src.file
let dest = path.join_path(sources_dir, filename)
// Check if already cached with valid checksum
if file.fileExists(dest)
if verify_single_checksum(dest, src.checksum)
color.print_info("Using cached: " + filename)
i = i + 1
continue
else
// Cached file has wrong checksum, re-download
color.print_warning("Cached file checksum mismatch, re-downloading: " + filename)
end if
end if
// Try each mirror URL in order
mut download_success = false
mut url_idx = 0
while url_idx < src.url_count
let url = src.urls[url_idx]
if url_idx > 0
color.print_info("Trying mirror: " + url)
end if
// Check if this is a local file (no http:// or https:// prefix)
if is_local_source(url)
// Local file - copy from port directory to sources cache
if copy_local_source(url, dest, ctx.port.port_dir)
if verify_single_checksum(dest, src.checksum)
download_success = true
break
else
color.print_warning("Checksum mismatch for local file, trying next...")
let rm_cmd = "rm -f \"" + dest + "\""
let rm_pid = process.process_spawn_shell(rm_cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
end if
end if
else
// Remote URL - download via HTTP
if uhttp.download(url, dest)
// Verify checksum after download
if verify_single_checksum(dest, src.checksum)
download_success = true
break
else
color.print_warning("Checksum mismatch from mirror, trying next...")
// Delete bad file
let rm_cmd = "rm -f \"" + dest + "\""
let rm_pid = process.process_spawn_shell(rm_cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
end if
end if
end if
url_idx = url_idx + 1
end while
if not download_success
color.print_error("Failed to download: " + filename + " (all sources failed)")
return false
end if
i = i + 1
end while
return true
end download_sources
// Check if a URL is a local file path (not http:// or https://)
fn is_local_source(url: string): bool
if str.starts_with(url, "http://")
return false
end if
if str.starts_with(url, "https://")
return false
end if
return true
end is_local_source
// Copy a local source file from port directory to sources cache
fn copy_local_source(source_path: string, dest: string, port_dir: string): bool
// Resolve the source path
mut full_path = source_path
// If it's a relative path, resolve relative to port directory
if not str.starts_with(source_path, "/")
full_path = path.join_path(port_dir, source_path)
end if
// Check if file exists
if not file.fileExists(full_path)
color.print_error("Local source file not found: " + full_path)
return false
end if
color.print_info("Copying local source: " + source_path)
// Copy the file
let cmd = "cp \"" + full_path + "\" \"" + dest + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Failed to copy local source: " + source_path)
return false
end if
color.print_success("Copied: " + source_path)
return true
end copy_local_source
// Verify a single file's checksum
fn verify_single_checksum(file_path: string, expected: string): bool
// Handle special checksum values
if str.equals(expected, "SKIP") or str.equals(expected, "BOOTSTRAP") or str.equals(expected, "skip")
return true
end if
if str.length(expected) == 0
return true
end if
return checksum.verify_checksum_with_algo(file_path, expected)
end verify_single_checksum
fn verify_checksums(ctx: BuildContext): bool
if ctx.port.sources.count == 0
return true
end if
color.print_info("Verifying checksums...")
let sources_dir = config.get_sources_dir(ctx.cfg)
mut i = 0
while i < ctx.port.sources.count
let src = ctx.port.sources.sources[i]
let filename = src.file
let file_path = path.join_path(sources_dir, filename)
let expected = src.checksum
// Handle special checksum values
if str.equals(expected, "SKIP") or str.equals(expected, "BOOTSTRAP") or str.equals(expected, "skip")
color.print_warning("Checksum verification skipped: " + filename)
elif str.length(expected) > 0
if not checksum.verify_checksum_with_algo(file_path, expected)
color.print_error("Checksum mismatch: " + filename)
return false
end if
color.print_success("Checksum verified: " + filename)
else
color.print_warning("No checksum for: " + filename)
end if
i = i + 1
end while
return true
end verify_checksums
fn extract_sources(ctx: BuildContext): bool
if ctx.port.sources.count == 0
return true
end if
color.print_info("Extracting sources...")
let sources_dir = config.get_sources_dir(ctx.cfg)
mut i = 0
while i < ctx.port.sources.count
let src = ctx.port.sources.sources[i]
let filename = src.file
let archive_path = path.join_path(sources_dir, filename)
// Check extract flag
if not src.extract
// Copy file to work_dir instead of extracting (for patches, etc.)
let dest_path = path.join_path(ctx.work_dir, filename)
let cp_cmd = "cp \"" + archive_path + "\" \"" + dest_path + "\""
let cp_pid = process.process_spawn_shell(cp_cmd)
if cp_pid > 0
let exit_code = process.process_wait(cp_pid)
if exit_code != 0
color.print_error("Failed to copy: " + filename)
return false
end if
end if
color.print_info("Copied (no extract): " + filename)
i = i + 1
continue
end if
if not archive.extract(archive_path, ctx.work_dir)
color.print_error("Failed to extract: " + filename)
return false
end if
color.print_success("Extracted: " + filename)
i = i + 1
end while
return true
end extract_sources
fn apply_patches(ctx: BuildContext): bool
if ctx.port.patches.count == 0
return true
end if
log_info(ctx, "Applying patches...")
let strip = ctx.port.patches.strip
// Find the source directory (first subdirectory in work_dir)
let find_srcdir = "cd \"" + ctx.work_dir + "\" && ls -d */ 2>/dev/null | head -1 | tr -d '/'"
mut i = 0
while i < ctx.port.patches.count
let patch_file = ctx.port.patches.files[i]
let patch_path = path.join_path(ctx.port.port_dir, patch_file)
if not file.fileExists(patch_path)
log_error(ctx, "Patch file not found: " + patch_file)
return false
end if
// Apply patch from within the source directory
let cmd = "cd \"" + ctx.work_dir + "/$(" + find_srcdir + ")\" && patch -p" + int_to_str(strip) + " < \"" + patch_path + "\""
let exit_code = run_logged_cmd(ctx, cmd)
if exit_code != 0
log_error(ctx, "Failed to apply patch: " + patch_file)
return false
end if
log_success(ctx, "Applied patch: " + patch_file)
i = i + 1
end while
return true
end apply_patches
fn run_build(ctx: BuildContext): bool
log_action(ctx, "Building " + ctx.port.info.name + "...")
// Look for build.sh in port directory
let build_script = path.join_path(ctx.port.port_dir, "build.sh")
if not file.fileExists(build_script)
log_error(ctx, "No build.sh found in port directory")
return false
end if
// Set up environment
let destdir = ctx.pkg_dir
let cflags = config.get_cflags(ctx.cfg)
let cxxflags = config.get_cxxflags(ctx.cfg)
let jobs = config.get_jobs(ctx.cfg)
mut jobs_str = ""
if jobs > 0
jobs_str = int_to_str(jobs)
else
// Auto-detect: use getconf (portable across illumos/Linux, unlike nproc)
jobs_str = "$(getconf NPROCESSORS_ONLN 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)"
end if
// Find the extracted source directory (first directory in work_dir)
// Typically the tarball extracts to a subdirectory like "zlib-1.3.1"
let find_srcdir_cmd = "cd \"" + ctx.work_dir + "\" && ls -d */ 2>/dev/null | head -1 | tr -d '/'"
// Determine PREFIX: package.toml override → coral.conf → default (/usr)
mut prefix = config.get_prefix(ctx.cfg)
if str.length(ctx.port.prefix) > 0
prefix = ctx.port.prefix
end if
// Determine SYSCONFDIR: package.toml override → coral.conf → default (/etc)
mut sysconfdir = config.get_sysconfdir(ctx.cfg)
if str.length(ctx.port.sysconfdir) > 0
sysconfdir = ctx.port.sysconfdir
end if
// PKG_ROOT is the alternate root (empty means /)
let pkg_root = config.get_root(ctx.cfg)
// Build the command with all environment variables
// Per Hammerhead porting guide: no uname wrappers, replace bundled config.guess/config.sub,
// use system config.guess for BUILD_TRIPLE (returns x86_64-zygaena-hammerhead)
mut cmd = "cd \"" + ctx.work_dir + "\" && "
cmd = cmd + "export SRCDIR=\"" + ctx.work_dir + "/$(" + find_srcdir_cmd + ")\" && "
cmd = cmd + "export PKGDIR=\"" + destdir + "\" && "
cmd = cmd + "export DESTDIR=\"" + destdir + "\" && "
cmd = cmd + "export PREFIX=\"" + prefix + "\" && "
cmd = cmd + "export SYSCONFDIR=\"" + sysconfdir + "\" && "
cmd = cmd + "export PKG_ROOT=\"" + pkg_root + "\" && "
cmd = cmd + "export JOBS=\"" + jobs_str + "\" && "
cmd = cmd + "export CFLAGS=\"" + cflags + "\" && "
cmd = cmd + "export CXXFLAGS=\"" + cxxflags + "\" && "
cmd = cmd + "export LDFLAGS=\"-R" + prefix + "/lib\" && "
cmd = cmd + "export PKG_CONFIG_PATH=\"" + prefix + "/lib/pkgconfig\" && "
cmd = cmd + "export MAKEFLAGS=\"-j" + jobs_str + "\" && "
cmd = cmd + "export PKG_NAME=\"" + ctx.port.info.name + "\" && "
cmd = cmd + "export PKG_VERSION=\"" + ctx.port.info.version + "\" && "
cmd = cmd + "export BUILD_TRIPLE=\"$(/usr/share/autoconf/build-aux/config.guess 2>/dev/null || echo x86_64-zygaena-hammerhead)\" && "
cmd = cmd + "export PATH=\"/usr/gnu/bin:$PATH\" && "
cmd = cmd + "export MAKE=gmake && "
cmd = cmd + "export TAR=gtar && "
cmd = cmd + "for _f in config.guess config.sub; do find \"$SRCDIR\" -name \"$_f\" -exec cp /usr/share/autoconf/build-aux/\"$_f\" {} \\; 2>/dev/null; done; "
cmd = cmd + "zsh \"" + build_script + "\""
log_info(ctx, "Running build script...")
let exit_code = run_logged_cmd(ctx, cmd)
if exit_code != 0
log_error(ctx, "Build script failed with exit code: " + int_to_str(exit_code))
return false
end if
log_success(ctx, "Build completed successfully")
return true
end run_build
// Compress uncompressed man pages in the staging directory
proc compress_man_pages(ctx: BuildContext)
// Find uncompressed man pages and gzip them
// Uses -exec {} + (batch mode) to avoid shell escaping issues with \;
// Uses -type f to skip symlinks (avoids creating dangling refs)
let script = "find '" + ctx.pkg_dir + "' -type f -path '*/man/man*/*' ! -name '*.gz' ! -name '*.bz2' ! -name '*.xz' -exec gzip -9 {} +"
let pid = process.process_spawn_shell(script)
if pid > 0
let exit_code = process.process_wait(pid)
if exit_code == 0
log_info(ctx, "Compressed man pages")
end if
end if
end compress_man_pages
fn create_package(ctx: BuildContext): bool
color.print_action("Creating package...")
// Validate that staging directory has content (not just metadata files)
if not validate_staging_dir(ctx.pkg_dir)
color.print_error("Staging directory is empty - build produced no files")
color.print_error("Check that build.sh installs files to $DESTDIR or $PKGDIR")
return false
end if
// Generate .PKGINFO
if not generate_pkginfo(ctx)
return false
end if
// Generate .MANIFEST (mtree file inventory)
if not generate_manifest_file(ctx)
return false
end if
// Create the package archive
let pkg_name = ctx.port.info.name + "-" + ctx.port.info.version + "-" + int_to_str(ctx.port.info.release) + ".pkg.tar.xz"
let pkg_path = path.join_path(config.get_packages_dir(ctx.cfg), pkg_name)
if not archive.create_package(ctx.pkg_dir, pkg_path)
color.print_error("Failed to create package archive")
return false
end if
return true
end create_package
// Validate that staging directory has actual content (not empty)
fn validate_staging_dir(pkg_dir: string): bool
// Count files in staging directory, excluding metadata files
// A valid package should have at least one real file
let cmd = "find \"" + pkg_dir + "\" -type f ! -name '.PKGINFO' ! -name '.MANIFEST' ! -name '.FOOTPRINT' | head -1"
let tmp_file = "/tmp/coral_validate_" + int_to_str(process.getpid()) + ".txt"
let full_cmd = cmd + " > \"" + tmp_file + "\""
let pid = process.process_spawn_shell(full_cmd)
if pid < 0
return false
end if
process.process_wait(pid)
// Read result
let content = res.unwrap_or(file.readFile(tmp_file), "")
// Clean up
let rm_cmd = "rm -f \"" + tmp_file + "\""
let rm_pid = process.process_spawn_shell(rm_cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
// If content is empty, staging dir has no real files
if str.length(content) == 0
return false
end if
// Trim newlines and check again
let trimmed = str.trim(content, '\n')
if str.length(trimmed) == 0
return false
end if
return true
end validate_staging_dir
fn generate_pkginfo(ctx: BuildContext): bool
let pkginfo_path = path.join_path(ctx.pkg_dir, ".PKGINFO")
mut content = "[package]\n"
content = content + "name = \"" + ctx.port.info.name + "\"\n"
content = content + "version = \"" + ctx.port.info.version + "\"\n"
content = content + "release = " + int_to_str(ctx.port.info.release) + "\n"
content = content + "description = \"" + ctx.port.info.description + "\"\n"
content = content + "url = \"" + ctx.port.info.url + "\"\n"
content = content + "license = \"" + ctx.port.info.license + "\"\n"
content = content + "maintainer = \"" + ctx.port.info.maintainer + "\"\n"
content = content + "arch = \"" + ctx.port.info.arch + "\"\n"
// Emit [dependencies] section if there are any
let has_runtime = ctx.port.deps.runtime_count > 0
let has_build = ctx.port.deps.build_count > 0
if has_runtime or has_build
content = content + "\n[dependencies]\n"
if has_runtime
content = content + "runtime = ["
mut i = 0
while i < ctx.port.deps.runtime_count
if i > 0
content = content + ", "
end if
content = content + "\"" + ctx.port.deps.runtime[i] + "\""
i = i + 1
end while
content = content + "]\n"
end if
if has_build
content = content + "build = ["
mut i = 0
while i < ctx.port.deps.build_count
if i > 0
content = content + ", "
end if
content = content + "\"" + ctx.port.deps.build[i] + "\""
i = i + 1
end while
content = content + "]\n"
end if
end if
return res.is_ok(file.writeFile(pkginfo_path, content))
end generate_pkginfo
fn generate_manifest_file(ctx: BuildContext): bool
let manifest_path = path.join_path(ctx.pkg_dir, ".MANIFEST")
// Generate mtree manifest using native fs operations
// BUG-033 (GC candidate overflow) fixed in Reef 0.5.6
// uid/gid resolution now uses zero-allocation stat.uid_name()/gid_name()
let content = mtree.generate_manifest(ctx.pkg_dir)
if str.length(content) == 0
return false
end if
return res.is_ok(file.writeFile(manifest_path, content))
end generate_manifest_file
proc cleanup_build(ctx: BuildContext)
// Check if cleanup is disabled by --noclean flag
if ctx.noclean
color.print_info("Skipping cleanup (--noclean specified)")
return
end if
// Determine cleanup behavior from config and flags
mut clean_work = config.get_clean_work(ctx.cfg)
mut clean_pkg = config.get_clean_pkg(ctx.cfg)
// --clean flag forces cleanup
if ctx.force_clean
clean_work = true
clean_pkg = true
end if
// Clean work directory
if clean_work and dir.dir_exists(ctx.work_dir)
color.print_info("Cleaning work directory: " + ctx.work_dir)
let cmd = "rm -rf \"" + ctx.work_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
let exit_code = process.process_wait(pid)
if exit_code == 0
color.print_success("Cleaned work directory")
else
color.print_warning("Failed to clean work directory")
end if
end if
end if
// Clean pkg directory (DESTDIR staging)
if clean_pkg and dir.dir_exists(ctx.pkg_dir)
color.print_info("Cleaning pkg directory: " + ctx.pkg_dir)
let cmd = "rm -rf \"" + ctx.pkg_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
let exit_code = process.process_wait(pid)
if exit_code == 0
color.print_success("Cleaned pkg directory")
else
color.print_warning("Failed to clean pkg directory")
end if
end if
end if
end cleanup_build
// Helper: extract filename from URL
fn extract_filename(url: string): string
let last_slash = str.last_index_of_char(url, '/')
if last_slash < 0
return url
end if
let filename = str.substring(url, last_slash + 1, str.length(url) - last_slash - 1)
// Remove query string if present
let query_pos = str.index_of_char(filename, '?')
if query_pos > 0
return str.substring(filename, 0, query_pos)
end if
return filename
end extract_filename
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: clean.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Clean command - remove build artifacts and caches
******************************************************************************/
module commands.clean
import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import types
import util.color
import exitcodes as ec
import core.result as res
export
fn execute(): int
end export
fn execute(): int
let argc = args.count()
if argc < 3
print_usage()
return ec.EXIT_USAGE()
end if
let subcommand = args.get(2)
// Load config
let cfg = config.load()
if subcommand == "status"
return show_status(cfg)
elif subcommand == "sources"
return clean_sources(cfg)
elif subcommand == "packages"
return clean_packages(cfg)
elif subcommand == "build"
return clean_build(cfg)
elif subcommand == "all"
return clean_all(cfg)
else
color.print_error("Unknown subcommand: " + subcommand)
print_usage()
return ec.EXIT_USAGE()
end if
end execute
fn show_status(cfg: config.Config): int
color.print_action("Build artifact status:")
println("")
// Built packages
let packages_dir = config.get_packages_dir(cfg)
let pkg_count = count_files(packages_dir, ".pkg.tar.xz")
mut pkg_protected = ""
if config.get_keep_packages(cfg)
pkg_protected = " [protected]"
end if
println(" Packages (" + packages_dir + "):" + pkg_protected)
println(" " + int_to_str(pkg_count) + " built package(s)")
// Source tarballs
let sources_dir = config.get_sources_dir(cfg)
let src_count = count_files(sources_dir, "")
mut src_protected = ""
if config.get_keep_sources(cfg)
src_protected = " [protected]"
end if
println(" Sources (" + sources_dir + "):" + src_protected)
println(" " + int_to_str(src_count) + " source archive(s)")
// Build workspace
let build_dir = config.get_build_dir(cfg)
let build_count = count_subdirs(build_dir)
println(" Build (" + build_dir + "):")
println(" " + int_to_str(build_count) + " build workspace(s)")
return ec.EXIT_SUCCESS()
end show_status
fn clean_sources(cfg: config.Config): int
// Respect keep_sources config unless --force is passed
if config.get_keep_sources(cfg) and not args.has_flag("force")
color.print_warning("Source cache is configured to be preserved (keep_sources = true)")
color.print_info("Use --force to override")
return ec.EXIT_SUCCESS()
end if
let sources_dir = config.get_sources_dir(cfg)
color.print_action("Cleaning source archives...")
println(" Location: " + sources_dir)
if not dir.dir_exists(sources_dir)
color.print_info("No sources directory to clean")
return ec.EXIT_SUCCESS()
end if
let cmd = "rm -rf \"" + sources_dir + "\"/*"
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
color.print_success("Source archives cleaned")
return ec.EXIT_SUCCESS()
end clean_sources
fn clean_packages(cfg: config.Config): int
// Respect keep_packages config unless --force is passed
if config.get_keep_packages(cfg) and not args.has_flag("force")
color.print_warning("Package cache is configured to be preserved (keep_packages = true)")
color.print_info("Use --force to override")
return ec.EXIT_SUCCESS()
end if
let packages_dir = config.get_packages_dir(cfg)
color.print_action("Cleaning built packages...")
println(" Location: " + packages_dir)
if not dir.dir_exists(packages_dir)
color.print_info("No packages directory to clean")
return ec.EXIT_SUCCESS()
end if
let cmd = "rm -rf \"" + packages_dir + "\"/*"
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
color.print_success("Built packages cleaned")
return ec.EXIT_SUCCESS()
end clean_packages
fn clean_build(cfg: config.Config): int
let build_dir = config.get_build_dir(cfg)
color.print_action("Cleaning build workspaces...")
println(" Location: " + build_dir)
if not dir.dir_exists(build_dir)
color.print_info("No build directory to clean")
return ec.EXIT_SUCCESS()
end if
let cmd = "rm -rf \"" + build_dir + "\"/*"
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
color.print_success("Build workspaces cleaned")
return ec.EXIT_SUCCESS()
end clean_build
fn clean_all(cfg: config.Config): int
color.print_action("Cleaning all build artifacts...")
println("")
clean_sources(cfg)
clean_packages(cfg)
clean_build(cfg)
println("")
color.print_success("All build artifacts cleaned")
return ec.EXIT_SUCCESS()
end clean_all
fn count_files(dir_path: string, extension: string): int
if not dir.dir_exists(dir_path)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(dir_path), new [string](0))
let count = entries.length()
if str.length(extension) == 0
return count
end if
mut matched = 0
mut i = 0
while i < count
if str.ends_with(entries[i], extension)
matched = matched + 1
end if
i = i + 1
end while
return matched
end count_files
fn count_subdirs(dir_path: string): int
if not dir.dir_exists(dir_path)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(dir_path), new [string](0))
let count = entries.length()
// Count only directories (packages being built)
mut dirs = 0
mut i = 0
while i < count
let entry = entries[i]
if str.length(entry) > 0 and entry[0] != '.'
let full_path = path.join_path(dir_path, entry)
if dir.dir_exists(full_path)
dirs = dirs + 1
end if
end if
i = i + 1
end while
return dirs
end count_subdirs
proc print_usage()
println("Usage: coral clean <target>")
println("")
println("Remove build artifacts and cached files.")
println("")
println("Targets:")
println(" status Show what can be cleaned")
println(" sources Remove downloaded source archives")
println(" packages Remove built binary packages")
println(" build Remove build workspaces")
println(" all Remove all of the above")
println("")
println("Locations:")
println(" sources: /usr/zports/pkgs/sources/")
println(" packages: /usr/zports/pkgs/packages/")
println(" build: /usr/zports/pkgs/build/")
println("")
println("Options:")
println(" --force Override keep_packages/keep_sources config protection")
println("")
println("Note: This does NOT affect installed packages or the package database.")
println(" Use 'coral remove' to uninstall packages.")
println("")
println("Examples:")
println(" coral clean status")
println(" coral clean build")
println(" coral clean all")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: db.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Database command - manage package database indexes
******************************************************************************/
module commands.db
import sys.args
import io.file
import io.dir
import core.str
import core.config
import core.pkgdb
import core.portindex
import types
import util.color
import exitcodes as ec
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Subcommand should be at cmd_index + 1
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
let subcommand = args.get(opts.cmd_index + 1)
if subcommand == "init"
return db_init(root_path)
elif subcommand == "rebuild"
return db_rebuild(root_path)
elif subcommand == "status"
return db_status(root_path)
elif subcommand == "dump"
return db_dump(root_path)
else
color.print_error("Unknown subcommand: " + subcommand)
print_usage()
return ec.EXIT_USAGE()
end if
end execute
fn db_init(root_path: string): int
if str.length(root_path) > 0
color.print_action("Initializing package database in " + root_path + "...")
else
color.print_action("Initializing package database...")
end if
println("")
// Check if database already exists (use rooted version if root is set)
let exists = check_indexes_exist(root_path)
if exists
color.print_warning("Database indexes already exist")
color.print_info("Use 'coral db rebuild' to regenerate indexes")
return ec.EXIT_SUCCESS()
end if
// Initialize the database directory (use rooted version if root is set)
if not init_pkgdb(root_path)
color.print_error("Failed to create database directory")
return ec.EXIT_DB_ERROR()
end if
// Build initial indexes (use rooted version if root is set)
if not rebuild_pkgdb(root_path)
color.print_error("Failed to build initial indexes")
return ec.EXIT_DB_ERROR()
end if
// Build ports index
portindex.rebuild_port_index()
let stats = get_pkgdb_stats(root_path)
let port_count = portindex.get_port_count()
color.print_success("Database initialized successfully")
println(" Packages indexed: " + int_to_str(stats.package_count))
println(" Files indexed: " + int_to_str(stats.file_count))
println(" Ports indexed: " + int_to_str(port_count))
return ec.EXIT_SUCCESS()
end db_init
fn db_rebuild(root_path: string): int
if str.length(root_path) > 0
color.print_action("Rebuilding package database indexes in " + root_path + "...")
else
color.print_action("Rebuilding package database indexes...")
end if
println("")
// Check if db directory exists (use rooted version if root is set)
if not init_pkgdb(root_path)
color.print_error("Failed to access database directory")
color.print_info("Run 'coral db init' first")
return ec.EXIT_DB_ERROR()
end if
// Rebuild indexes from source of truth (use rooted version if root is set)
if not rebuild_pkgdb(root_path)
color.print_error("Failed to rebuild indexes")
return ec.EXIT_DB_ERROR()
end if
// Rebuild ports index
portindex.rebuild_port_index()
let stats = get_pkgdb_stats(root_path)
let port_count = portindex.get_port_count()
color.print_success("Database indexes rebuilt successfully")
println(" Packages indexed: " + int_to_str(stats.package_count))
println(" Files indexed: " + int_to_str(stats.file_count))
println(" Ports indexed: " + int_to_str(port_count))
return ec.EXIT_SUCCESS()
end db_rebuild
fn db_dump(root_path: string): int
color.print_action("Dumping files index contents...")
println("")
mut paths: [string] = new [string](256)
mut owners: [string] = new [string](256)
let count = pkgdb.dump_files_index_rooted(root_path, paths, owners, 256)
if count == 0
color.print_warning("No files in index or index not loaded")
return ec.EXIT_DB_ERROR()
end if
println("Files in index: " + int_to_str(count))
println("")
mut i = 0
while i < count
println(" [" + int_to_str(i) + "] '" + paths[i] + "' -> '" + owners[i] + "'")
i = i + 1
end while
return ec.EXIT_SUCCESS()
end db_dump
fn db_status(root_path: string): int
if str.length(root_path) > 0
color.print_action("Package database status for " + root_path + ":")
else
color.print_action("Package database status:")
end if
println("")
let stats = get_pkgdb_stats(root_path)
if not check_indexes_exist(root_path)
color.print_warning("Database indexes not found")
color.print_info("Run 'coral db init' to create indexes")
println("")
if str.length(root_path) > 0
println(" Source of truth: " + root_path + "/var/lib/coral/installed/")
else
println(" Source of truth: /var/lib/coral/installed/")
end if
println(" Packages installed: " + int_to_str(stats.package_count))
return ec.EXIT_DB_INDEX_STALE()
end if
if str.length(root_path) > 0
println(" Index location: " + root_path + types.get_index_dir())
else
println(" Index location: " + types.get_index_dir())
end if
println(" Packages indexed: " + int_to_str(stats.package_count))
println(" Files indexed: " + int_to_str(stats.file_count))
if stats.packages_db_size > 0
println(" packages.db size: " + format_size(stats.packages_db_size))
end if
if stats.files_db_size > 0
println(" files.db size: " + format_size(stats.files_db_size))
end if
// Ports index status
if portindex.port_index_exists()
let port_count = portindex.get_port_count()
println(" Ports indexed: " + int_to_str(port_count))
else
println(" Ports index: not built")
end if
return ec.EXIT_SUCCESS()
end db_status
// Helper functions for rooted pkgdb operations
fn check_indexes_exist(root_path: string): bool
if str.length(root_path) > 0
return pkgdb.indexes_exist_rooted(root_path)
end if
return pkgdb.indexes_exist()
end check_indexes_exist
fn init_pkgdb(root_path: string): bool
if str.length(root_path) > 0
return pkgdb.init_db_rooted(root_path)
end if
return pkgdb.init_db()
end init_pkgdb
fn rebuild_pkgdb(root_path: string): bool
if str.length(root_path) > 0
return pkgdb.rebuild_indexes_rooted(root_path)
end if
return pkgdb.rebuild_indexes()
end rebuild_pkgdb
fn get_pkgdb_stats(root_path: string): pkgdb.IndexStats
if str.length(root_path) > 0
return pkgdb.get_index_stats_rooted(root_path)
end if
return pkgdb.get_index_stats()
end get_pkgdb_stats
fn format_size(bytes: int): string
if bytes < 1024
return int_to_str(bytes) + " B"
elif bytes < 1024 * 1024
return int_to_str(bytes / 1024) + " KB"
elif bytes < 1024 * 1024 * 1024
return int_to_str(bytes / (1024 * 1024)) + " MB"
else
return int_to_str(bytes / (1024 * 1024 * 1024)) + " GB"
end if
end format_size
proc print_usage()
println("Usage: coral db <command>")
println("")
println("Manage package database indexes.")
println("")
println("Commands:")
println(" init Initialize database (run once during system setup)")
println(" rebuild Rebuild indexes from installed packages")
println(" status Show database status and statistics")
println("")
println("The package database provides fast lookups for installed packages")
println("and file ownership. The source of truth is always the installed/")
println("directory; indexes can be safely rebuilt at any time.")
println("")
println("Examples:")
println(" coral db init")
println(" coral db rebuild")
println(" coral db status")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: depends.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Depends command - show package dependency tree
******************************************************************************/
module commands.depends
import sys.args
import core.str
import core.port
import core.portindex
import core.database
import core.resolver
import types
import util.color
import exitcodes as ec
export
fn execute(): int
end export
fn execute(): int
let argc = args.count()
if argc < 3
print_usage()
return ec.EXIT_USAGE()
end if
let pkg_name = args.get(2)
// Check for --reverse flag (show what depends on this package)
if args.has_flag("reverse") or args.has_flag("r")
show_reverse_deps(pkg_name)
return ec.EXIT_SUCCESS()
end if
// Show forward dependencies
show_deps(pkg_name)
return ec.EXIT_SUCCESS()
end execute
proc show_deps(name: string)
// Find the port
let result = port.find(name)
if not result.success
color.print_error("Port not found: " + name)
return
end if
let p = result.port
color.print_action("Dependencies for " + name + ":")
println("")
// Show runtime dependencies
if p.deps.runtime_count == 0
color.print_info("No runtime dependencies")
else
color.print_info("Runtime dependencies:")
show_dep_tree(name, 0)
end if
println("")
// Show build dependencies
if p.deps.build_count > 0
color.print_info("Build dependencies:")
mut i = 0
while i < p.deps.build_count
print(" ")
let dep = p.deps.build[i]
print(dep)
if database.is_installed(dep)
println(" [installed]")
else
println("")
end if
i = i + 1
end while
end if
end show_deps
proc show_dep_tree(name: string, depth: int)
if depth > 10
return
end if
let result = port.find(name)
if not result.success
return
end if
let p = result.port
mut i = 0
while i < p.deps.runtime_count
let dep = p.deps.runtime[i]
// Print with indentation
print_indent(depth)
print(dep)
if database.is_installed(dep)
println(" [installed]")
else
println("")
end if
// Recurse
show_dep_tree(dep, depth + 1)
i = i + 1
end while
end show_dep_tree
proc show_reverse_deps(name: string)
color.print_action("Packages that depend on " + name + ":")
println("")
mut found = 0
// Try ports index first (fast path)
if portindex.port_index_exists()
mut results: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](512)
let result_count = portindex.find_reverse_deps(name, results, 512)
mut i = 0
while i < result_count
let entry = results[i]
print(" ")
print(entry.category)
print("/")
print(entry.name)
if database.is_installed(entry.name)
println(" [installed]")
else
println("")
end if
found = found + 1
i = i + 1
end while
else
// Fall back to filesystem scan
mut cats: [string] = new [string](32)
let cat_count = port.get_categories(cats, 32)
mut i = 0
while i < cat_count
let category = cats[i]
mut ports: [string] = new [string](256)
let port_count = port.list_category(category, ports, 256)
mut j = 0
while j < port_count
let port_name = ports[j]
if depends_on(port_name, name)
print(" ")
print(category)
print("/")
print(port_name)
if database.is_installed(port_name)
println(" [installed]")
else
println("")
end if
found = found + 1
end if
j = j + 1
end while
i = i + 1
end while
end if
if found == 0
color.print_info("No packages depend on " + name)
else
println("")
color.print_info("Total: " + int_to_str(found) + " package(s)")
end if
end show_reverse_deps
fn depends_on(pkg_name: string, dep_name: string): bool
let result = port.find(pkg_name)
if not result.success
return false
end if
let p = result.port
// Check runtime deps
mut i = 0
while i < p.deps.runtime_count
if p.deps.runtime[i] == dep_name
return true
end if
i = i + 1
end while
// Check build deps
i = 0
while i < p.deps.build_count
if p.deps.build[i] == dep_name
return true
end if
i = i + 1
end while
return false
end depends_on
proc print_indent(depth: int)
mut i = 0
while i < depth
print(" ")
i = i + 1
end while
print(" ") // Base indent
end print_indent
proc print_usage()
println("Usage: coral depends <package> [options]")
println("")
println("Show dependency tree for a package.")
println("")
println("Arguments:")
println(" <package> Name of package to show dependencies for")
println("")
println("Options:")
println(" -r, --reverse Show packages that depend on this package")
println("")
println("Examples:")
println(" coral depends vim")
println(" coral depends vim --reverse")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: files.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Files command - list files owned by a package
******************************************************************************/
module commands.files
import sys.args
import core.str
import core.config
import core.database
import types
import util.color
import exitcodes as ec
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Package name should be at cmd_index + 1
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
let pkg_name = args.get(opts.cmd_index + 1)
// Check if installed (use rooted version if root is set)
if not check_installed(pkg_name, root_path)
color.print_error(pkg_name + " is not installed")
return ec.EXIT_PKG_NOT_FOUND()
end if
// Get files (use rooted version if root is set)
mut files: [string] = new [string](4096)
let file_count = get_files_list(pkg_name, files, 4096, root_path)
if file_count == 0
color.print_info("No files recorded for " + pkg_name)
return ec.EXIT_SUCCESS()
end if
color.print_action("Files owned by " + pkg_name + ":")
println("")
mut i = 0
while i < file_count
println("/" + files[i])
i = i + 1
end while
println("")
color.print_info("Total: " + int_to_str(file_count) + " files")
return ec.EXIT_SUCCESS()
end execute
// Helper functions for rooted operations
fn check_installed(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end check_installed
fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.get_files_rooted(name, files, max_count, root_path)
end if
return database.get_files(name, files, max_count)
end get_files_list
proc print_usage()
println("Usage: coral files <package>")
println("")
println("List all files owned by an installed package.")
println("")
println("Arguments:")
println(" <package> Name of installed package")
println("")
println("Examples:")
println(" coral files vim")
println(" coral files hello")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: info.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Info command - display package information
******************************************************************************/
module commands.info
import sys.args
import core.str
import core.config
import core.database
import core.port
import types
import util.color
import exitcodes as ec
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Package name should be at cmd_index + 1
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
let pkg_name = args.get(opts.cmd_index + 1)
// Check if installed (use rooted version if root is set)
let is_installed = check_installed(pkg_name, root_path)
// Find port
let port_result = port.find(pkg_name)
if not is_installed and not port_result.success
color.print_error("Package not found: " + pkg_name)
return ec.EXIT_PKG_NOT_FOUND()
end if
// Print package info
if is_installed
let installed_pkg = get_installed_pkg(pkg_name, root_path)
print_installed_info(installed_pkg)
if port_result.success
let p = port_result.port
// Check if upgrade available
if str.compare(installed_pkg.info.version, p.info.version) < 0
println("")
color.print_info("Upgrade available: " + p.info.version)
end if
end if
else
// Not installed, show port info
let p = port_result.port
print_port_info(p)
end if
return ec.EXIT_SUCCESS()
end execute
// Helper functions for rooted operations
fn check_installed(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end check_installed
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_installed_pkg
proc print_usage()
println("Usage: coral info <package>")
println("")
println("Display detailed information about a package.")
println("")
println("Arguments:")
println(" <package> Name of package to show info for")
println("")
println("Examples:")
println(" coral info vim")
println(" coral info hello")
end print_usage
proc print_installed_info(pkg: types.InstalledPackage)
color.print_action("Package: " + pkg.info.name)
println("")
println("Status: installed")
println("Version: " + pkg.info.version + "-" + int_to_str(pkg.info.release))
println("Description: " + pkg.info.description)
println("URL: " + pkg.info.url)
println("License: " + pkg.info.license)
println("Maintainer: " + pkg.info.maintainer)
println("Architecture: " + pkg.info.arch)
println("")
println("Install date: " + pkg.install_date)
println("Reason: " + pkg.install_reason)
println("Files: " + int_to_str(pkg.files_count))
end print_installed_info
proc print_port_info(p: types.Port)
color.print_action("Port: " + p.info.name)
println("")
println("Status: not installed")
println("Version: " + p.info.version + "-" + int_to_str(p.info.release))
println("Description: " + p.info.description)
println("URL: " + p.info.url)
println("License: " + p.info.license)
println("Maintainer: " + p.info.maintainer)
println("Architecture: " + p.info.arch)
// Show dependencies if any
if p.deps.runtime_count > 0
println("")
print("Depends on: ")
mut i = 0
while i < p.deps.runtime_count
if i > 0
print(", ")
end if
print(p.deps.runtime[i])
i = i + 1
end while
println("")
end if
if p.deps.build_count > 0
println("")
print("Build deps: ")
mut i = 0
while i < p.deps.build_count
if i > 0
print(", ")
end if
print(p.deps.build[i])
i = i + 1
end while
println("")
end if
end print_port_info
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: install.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Install command - install packages from archives
******************************************************************************/
module commands.install
import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.pkgdb
import core.package
import core.groups
import core.repository
import core.signing
import core.resolver
import core.port
import core.portindex
import util.checksum
import util.mtree
import util.http as uhttp
import util.prompt
import util.version as ver
import types
import util.color
import util.priv
import exitcodes as ec
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Package arguments start after the command
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
uhttp.enable_proxy(config.get_use_proxy(cfg))
// Auto-refresh port index if configured
if config.get_auto_refresh(cfg)
portindex.rebuild_port_index()
end if
// Show root/prefix if set (verbose mode)
if opts.verbose
let root = config.get_root(cfg)
let prefix = config.get_prefix(cfg)
if str.length(root) > 0
color.print_info("Using root: " + root)
end if
if str.length(prefix) > 0
color.print_info("Using prefix: " + prefix)
end if
end if
// Collect all packages to install (expanding groups)
mut packages: [string] = new [string](256)
mut pkg_count = 0
mut direct_files: [string] = new [string](16)
mut direct_count = 0
// Process each package argument (starting after the command)
mut i = opts.cmd_index + 1
while i < argc and pkg_count < 256
let pkg_arg = args.get(i)
// Skip flags and their values
if pkg_arg == "--root" or pkg_arg == "--prefix"
i = i + 2 // Skip flag and its value
continue
elif pkg_arg == "--no-chroot-scripts"
i = i + 1 // valueless flag: skip only itself
continue
end if
if str.starts_with(pkg_arg, "-")
i = i + 1
continue
end if
// Check if this is a direct file path to a .pkg.tar.xz
if str.ends_with(pkg_arg, ".pkg.tar.xz") and file.fileExists(pkg_arg)
direct_files[direct_count] = pkg_arg
direct_count = direct_count + 1
i = i + 1
continue
end if
// Check if this is a group reference
if groups.is_group(pkg_arg)
// Expand group to member packages
mut group_members: [string] = new [string](128)
let member_count = groups.expand_group(pkg_arg, group_members, 128)
if member_count == 0
color.print_error("Group not found or empty: " + pkg_arg)
i = i + 1
continue
end if
color.print_info("Expanding group " + pkg_arg + " (" + int_to_str(member_count) + " packages)")
// Add all group members to packages list
mut j = 0
while j < member_count and pkg_count < 256
packages[pkg_count] = group_members[j]
pkg_count = pkg_count + 1
j = j + 1
end while
else
// Regular package
packages[pkg_count] = pkg_arg
pkg_count = pkg_count + 1
end if
i = i + 1
end while
// Handle direct file installs — bypass resolver, install immediately
if direct_count > 0
let root = get_root(cfg)
let root_for_db = config.get_root(cfg)
if str.length(root_for_db) > 0
if not database.init_db_rooted(root_for_db)
color.print_error("Failed to initialize database in " + root_for_db)
return ec.EXIT_DB_ERROR()
end if
else
if not database.init_db()
color.print_error("Failed to initialize package database")
return ec.EXIT_DB_ERROR()
end if
end if
mut di = 0
while di < direct_count
if not install_package(direct_files[di], cfg, root_for_db, opts)
color.print_error("Failed to install: " + direct_files[di])
return ec.EXIT_INSTALL_FAILED()
end if
di = di + 1
end while
if pkg_count == 0
return ec.EXIT_SUCCESS()
end if
end if
// Resolve dependencies for all packages
// Use rooted resolver if installing to alternate root
mut install_order: [string] = new [string](512)
let root_for_resolve = config.get_root(cfg)
mut install_count = 0
if str.length(root_for_resolve) > 0
install_count = resolver.get_install_order_rooted(packages, pkg_count, install_order, 512, root_for_resolve)
else
install_count = resolver.get_install_order(packages, pkg_count, install_order, 512)
end if
// When force/reinstall is set, add requested packages that the resolver
// skipped (because they're already installed) back into the install order
if opts.force and install_count < pkg_count
mut fi = 0
while fi < pkg_count
let pkg = packages[fi]
if not array_contains(install_order, install_count, pkg)
install_order[install_count] = pkg
install_count = install_count + 1
end if
fi = fi + 1
end while
end if
if install_count == 0 and pkg_count > 0
color.print_warning("No packages to install (all already installed or not found)")
return ec.EXIT_SUCCESS()
end if
// Separate new installs from already-installed (for display)
mut to_install: [string] = new [string](512)
mut install_idx = 0
mut dep_idx = 0
while dep_idx < install_count
to_install[install_idx] = install_order[dep_idx]
install_idx = install_idx + 1
dep_idx = dep_idx + 1
end while
// Ask for confirmation (unless -y flag)
mut empty_upgrade: [string] = new [string](1)
if not prompt.confirm_install(to_install, install_idx, empty_upgrade, 0, opts)
color.print_info("Installation cancelled")
return ec.EXIT_CANCELLED()
end if
// Dry-run: show what would be done and exit
if opts.dry_run
color.print_info("Dry run — no changes made")
return ec.EXIT_SUCCESS()
end if
// Get root path for installation
let root = get_root(cfg)
// Initialize database in the target root
let root_for_db = config.get_root(cfg)
if str.length(root_for_db) > 0
if not database.init_db_rooted(root_for_db)
color.print_error("Failed to initialize database in " + root_for_db)
return ec.EXIT_DB_ERROR()
end if
else
if not database.init_db()
color.print_error("Failed to initialize package database")
return ec.EXIT_DB_ERROR()
end if
end if
// Install all packages in resolved order (dependencies first)
i = 0
while i < install_count
let pkg_arg = install_order[i]
// Install this package
if not install_package(pkg_arg, cfg, root_for_db, opts)
color.print_error("Failed to install: " + pkg_arg)
color.print_error("Aborting installation - dependency failed")
return ec.EXIT_INSTALL_FAILED()
end if
i = i + 1
end while
return ec.EXIT_SUCCESS()
end execute
// Helper to check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
mut i = 0
while i < count
if str.equals(arr[i], s)
return true
end if
i = i + 1
end while
return false
end array_contains
proc print_usage()
println("Usage: coral install <package...>")
println("")
println("Install one or more packages.")
println("")
println("Arguments:")
println(" <package> Package name or path to .pkg.tar.xz file")
println("")
println("Options:")
println(" -y, --yes Don't ask for confirmation")
println(" --force Force reinstall if already installed")
println("")
println("Examples:")
println(" coral install vim")
println(" coral install /path/to/package.pkg.tar.xz")
println(" coral install vim nano htop")
end print_usage
fn install_package(pkg_arg: string, cfg: config.Config, root_path: string, opts: types.GlobalOptions): bool
// Determine if this is a file path or package name
let pkg_path = resolve_package_path(pkg_arg, cfg)
if str.length(pkg_path) == 0
color.print_error("Package not found: " + pkg_arg)
return false
end if
// Verify signature if required (for local packages not already verified by resolve_package_path)
let require_signed = config.get_require_signed_packages(cfg)
if require_signed
let sig_path = pkg_path + ".sig"
if file.fileExists(sig_path)
color.print_info("Verifying package signature...")
let verify_result = signing.verify_package(pkg_path, sig_path)
if not verify_result.success or not verify_result.valid
color.print_error("Signature verification failed: " + verify_result.error)
return false
end if
color.print_success("Signature verified (key: " + verify_result.keyid + ")")
else
color.print_error("Package signature required but not found: " + sig_path)
return false
end if
end if
color.print_action("Installing " + pkg_arg + "...")
// Create extraction directory
let extract_dir = create_extract_dir(cfg)
if str.length(extract_dir) == 0
color.print_error("Failed to create extraction directory")
return false
end if
// Extract package
color.print_info("Extracting package...")
let result = package.extract_package(pkg_path, extract_dir)
if not result.success
color.print_error(result.error)
cleanup_extract_dir(extract_dir)
return false
end if
// Read package info
let info = package.read_pkginfo(extract_dir)
if str.length(info.name) == 0
color.print_error("Failed to read package info")
cleanup_extract_dir(extract_dir)
return false
end if
color.print_info("Package: " + info.name + " " + info.version)
// Check for conflicts with installed packages
if info.conflicts_count > 0
mut ci = 0
while ci < info.conflicts_count
let conflict = info.conflicts[ci]
if check_installed(conflict, root_path)
color.print_error("Package " + info.name + " conflicts with installed package: " + conflict)
if not opts.force
color.print_error("Use --force to override conflict check")
cleanup_extract_dir(extract_dir)
return false
end if
color.print_warning("Proceeding despite conflict (--force specified)")
end if
ci = ci + 1
end while
end if
// Check if already installed (in target root)
let already_installed = check_installed(info.name, root_path)
mut is_upgrade = false
mut old_version = ""
if already_installed
// Get old package info to check version
let old_pkg = get_old_installed(info.name, root_path)
old_version = old_pkg.info.version
if not str.equals(old_version, info.version)
// Different version — upgrade
is_upgrade = true
color.print_info("Upgrading " + info.name + " " + old_version + " -> " + info.version)
else
// Same version — skip or reinstall with --force
if not opts.force
color.print_warning(info.name + " " + info.version + " is already installed (use --force to reinstall)")
cleanup_extract_dir(extract_dir)
return true
end if
color.print_info("Reinstalling " + info.name + "...")
end if
end if
let install_root = get_root(cfg)
// Resolve script execution context; abort early if confinement is required but impossible.
// Defense-in-depth: main.reef already bars non-root for all non-query commands, so this abort
// is currently unreachable via the CLI. Kept so confinement fails safely if that global gate is
// ever relaxed.
if package.script_wants_chroot(install_root, config.get_chroot_scripts(cfg)) and not priv.is_root()
color.print_error("--root " + install_root + " runs maintainer scripts confined to the target via chroot, which requires root privileges.")
color.print_error("Re-run as root, or pass --no-chroot-scripts to run them on the host (unconfined).")
cleanup_extract_dir(extract_dir)
return false
end if
let script_ctx = package.resolve_script_ctx(install_root, config.get_chroot_scripts(cfg), priv.is_root())
if is_upgrade
// Upgrade flow: pre-upgrade → remove old files → install new files → post-upgrade
// Run pre-upgrade from stored scripts (old package)
let old_scripts = database.get_scripts_dir(info.name)
if database.has_stored_scripts(info.name)
color.print_info("Running pre-upgrade script...")
if not package.run_stored_pre_upgrade(script_ctx, old_scripts, old_version, info.version)
color.print_error("Pre-upgrade script failed, aborting")
cleanup_extract_dir(extract_dir)
return false
end if
end if
// Remove old files
color.print_info("Removing old version files...")
mut old_files: [string] = new [string](4096)
let old_file_count = get_old_files(info.name, old_files, 4096, root_path)
if old_file_count > 0
package.remove_files(old_files, old_file_count, install_root)
end if
// Load old manifest for config file checksum protection
mut old_manifest_entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
let old_manifest_count = load_old_manifest(info.name, root_path, old_manifest_entries, 8192)
// Install new files (with upgrade config protection)
color.print_info("Installing files...")
if old_manifest_count > 0
if not package.install_files_upgrade(extract_dir, install_root, old_manifest_entries, old_manifest_count)
color.print_error("Failed to install files")
cleanup_extract_dir(extract_dir)
return false
end if
else
if not package.install_files(extract_dir, install_root)
color.print_error("Failed to install files")
cleanup_extract_dir(extract_dir)
return false
end if
end if
// Run post-upgrade from new package's scripts
if package.has_scripts(extract_dir)
color.print_info("Running post-upgrade script...")
if not package.run_post_upgrade(script_ctx, extract_dir, old_version, info.version)
color.print_warning("Post-upgrade script failed")
end if
end if
else
// Fresh install flow
// Run pre-install script (abort on failure)
if package.has_scripts(extract_dir)
color.print_info("Running pre-install script...")
if not package.run_pre_install(script_ctx, extract_dir, info.version)
color.print_error("Pre-install script failed")
cleanup_extract_dir(extract_dir)
return false
end if
end if
// Install files to target root
color.print_info("Installing files...")
if not package.install_files(extract_dir, install_root)
color.print_error("Failed to install files")
cleanup_extract_dir(extract_dir)
return false
end if
// Run post-install script (warn on failure, don't abort)
if package.has_scripts(extract_dir)
color.print_info("Running post-install script...")
if not package.run_post_install(script_ctx, extract_dir, info.version)
color.print_warning("Post-install script failed")
end if
end if
end if
// Register in database (use rooted version if root is set)
color.print_info("Registering package...")
if not register_installed_fast_rooted(info, extract_dir, root_path)
color.print_error("Failed to register package in database")
// Files are installed but not registered - warn but don't fail
end if
// Store scripts for later use (removal)
if package.has_scripts(extract_dir)
if not store_scripts_rooted(info.name, extract_dir, root_path)
color.print_warning("Failed to store scripts for removal")
end if
end if
// Store config files list for upgrade handling
if not store_config_files_rooted(info.name, extract_dir, root_path)
color.print_warning("Failed to store config files list")
end if
// Update package database indexes
if not pkgdb.rebuild_indexes_rooted(root_path)
color.print_warning("Failed to update package indexes")
end if
// Cleanup
cleanup_extract_dir(extract_dir)
color.print_success("Installed " + info.name + " " + info.version)
return true
end install_package
// Check if package is installed, using rooted check if root is set
fn check_installed(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end check_installed
// Register package using rooted version if root is set
fn register_installed_fast_rooted(info: types.PackageInfo, extract_dir: string, root_path: string): bool
mut files: [string] = new [string](1)
mut pkg = new_installed_pkg(info, files, 0)
if str.length(root_path) > 0
return database.register_from_extract_dir_rooted(pkg, extract_dir, root_path)
end if
return database.register_from_extract_dir(pkg, extract_dir)
end register_installed_fast_rooted
// Store scripts using rooted version if root is set
fn store_scripts_rooted(name: string, extract_dir: string, root_path: string): bool
if str.length(root_path) > 0
return database.store_scripts_rooted(name, extract_dir, root_path)
end if
return database.store_scripts(name, extract_dir)
end store_scripts_rooted
// Store config files using rooted version if root is set
fn store_config_files_rooted(name: string, extract_dir: string, root_path: string): bool
if str.length(root_path) > 0
return database.store_config_files_rooted(name, extract_dir, root_path)
end if
return database.store_config_files(name, extract_dir)
end store_config_files_rooted
// Find package file - either direct path, repository, or search in packages directory
fn resolve_package_path(pkg_arg: string, cfg: config.Config): string
// If it's a file path that exists, use it directly
if file.fileExists(pkg_arg)
return pkg_arg
end if
// Search in local packages cache first
let packages_dir = config.get_packages_dir(cfg)
// Find all matching packages and select highest version
let entries = res.unwrap_or(dir.list_dir(packages_dir), new [string](0))
let entry_count = entries.length()
// Collect all matching package files
mut best_file = ""
mut best_version = ""
mut best_release = 0
mut i = 0
while i < entry_count
let entry = entries[i]
// Check if entry starts with package name and has correct suffix
if str.starts_with(entry, pkg_arg + "-") and str.ends_with(entry, ".pkg.tar.xz")
// Extract version from filename
let entry_version = ver.extract_version_from_filename(entry, pkg_arg)
let entry_release = ver.extract_release_from_filename(entry)
// Compare with current best
if str.length(best_file) == 0
// First match
best_file = entry
best_version = entry_version
best_release = entry_release
else
// Compare versions
let cmp = ver.compare_versions(entry_version, best_version)
if cmp > 0
// Entry has higher version
best_file = entry
best_version = entry_version
best_release = entry_release
elif cmp == 0 and entry_release > best_release
// Same version but higher release
best_file = entry
best_version = entry_version
best_release = entry_release
end if
end if
end if
i = i + 1
end while
// Return the best matching package
if str.length(best_file) > 0
return path.join_path(packages_dir, best_file)
end if
// Also try with .pkg.tar.xz appended
let direct_path = path.join_path(packages_dir, pkg_arg + ".pkg.tar.xz")
if file.fileExists(direct_path)
return direct_path
end if
// Try to build from source if configured
if config.get_fallback_to_source(cfg)
let port_result = port.find(pkg_arg)
if port_result.success
color.print_info("No binary package found for " + pkg_arg + ", building from source...")
let build_cmd = "coral build -y " + pkg_arg
let build_pid = process.process_spawn_shell(build_cmd)
if build_pid > 0
let build_exit = process.process_wait(build_pid)
if build_exit == 0
// Build succeeded, look for the package it produced
let p = port_result.port
let built_pkg = p.info.name + "-" + p.info.version + "-" + int_to_str(p.info.release) + ".pkg.tar.xz"
let built_path = path.join_path(packages_dir, built_pkg)
if file.fileExists(built_path)
return built_path
end if
end if
end if
color.print_warning("Source build failed for " + pkg_arg + ", trying repositories...")
end if
end if
// Try to find in repositories and download
let remote_result = repository.find_remote_package(pkg_arg)
if remote_result.success
let remote_pkg = remote_result.pkg
color.print_info("Found " + pkg_arg + " " + remote_pkg.version + " in repository: " + remote_pkg.repo_name)
// Download the package
let downloaded_path = repository.download_package(remote_pkg)
if str.length(downloaded_path) > 0
// Verify checksum if available
if str.length(remote_pkg.sha256) > 0
color.print_info("Verifying checksum...")
if not checksum.verify_checksum(downloaded_path, remote_pkg.sha256)
color.print_error("Checksum verification failed!")
return ""
end if
color.print_success("Checksum verified")
end if
// Verify signature if required or available
let require_signed = config.get_require_signed_packages(cfg)
if require_signed or str.length(remote_pkg.signature) > 0
let sig_path = downloaded_path + ".sig"
// Download signature file if we don't have it
if not file.fileExists(sig_path) and str.length(remote_pkg.signature) > 0
color.print_info("Downloading signature...")
let sig_url = get_sig_url(remote_pkg)
if not download_signature(sig_url, sig_path)
if require_signed
color.print_error("Failed to download package signature")
return ""
else
color.print_warning("Could not download signature, skipping verification")
end if
end if
end if
// Verify signature if we have it
if file.fileExists(sig_path)
color.print_info("Verifying signature...")
let verify_result = signing.verify_package(downloaded_path, sig_path)
if verify_result.success and verify_result.valid
color.print_success("Signature verified (key: " + verify_result.keyid + ")")
else
if require_signed
color.print_error("Signature verification failed: " + verify_result.error)
return ""
else
color.print_warning("Signature verification failed: " + verify_result.error)
end if
end if
elif require_signed
color.print_error("Package signature required but not available")
return ""
end if
end if
return downloaded_path
end if
end if
return ""
end resolve_package_path
// Create a temporary extraction directory
fn create_extract_dir(cfg: config.Config): string
let work_dir = config.get_work_dir(cfg)
let pid = process.getpid()
let extract_dir = path.join_path(work_dir, "install_" + int_to_str(pid))
if dir.dir_exists(extract_dir)
// Clean existing
let cmd = "rm -rf \"" + extract_dir + "\""
let rm_pid = process.process_spawn_shell(cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
end if
if not res.is_ok(dir.create_dir_all(extract_dir))
return ""
end if
return extract_dir
end create_extract_dir
// Cleanup extraction directory
fn cleanup_extract_dir(dir_path: string): bool
if str.length(dir_path) == 0
return true
end if
let cmd = "rm -rf \"" + dir_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
process.process_wait(pid)
return true
end cleanup_extract_dir
// Get installation root from config (can be overridden with --root)
fn get_root(cfg: config.Config): string
let root = config.get_root(cfg)
if str.length(root) == 0
return "/"
end if
return root
end get_root
// Check for file conflicts with other installed packages
// TODO: Implement efficient conflict detection using a file database
fn check_conflicts(files: [string], file_count: int, pkg_name: string): bool
// Skip conflict checking for performance - file overwrites are handled
// by the manifest-driven installer and dependencies are managed separately
return true
end check_conflicts
// Helper to create InstalledPackage
fn new_installed_pkg(info: types.PackageInfo, files: [string], file_count: int): types.InstalledPackage
mut pkg = types.new_installed_package()
pkg.info = info
pkg.install_date = get_date_string()
pkg.install_reason = "explicit"
pkg.files = files
pkg.files_count = file_count
return pkg
end new_installed_pkg
// Get current date as string (simplified)
fn get_date_string(): string
// Use date command for simplicity
// TODO: Use proper time functions when available
return "2025-01-24"
end get_date_string
// Get installed package info (root-aware)
fn get_old_installed(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_old_installed
// Get old file list for a package (root-aware)
fn get_old_files(name: string, files: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.get_files_rooted(name, files, max_count, root_path)
end if
return database.get_files(name, files, max_count)
end get_old_files
// Load old manifest from database for upgrade config protection
fn load_old_manifest(name: string, root_path: string, entries: [mtree.ManifestEntry], max_count: int): int
let manifest_path = database.get_manifest_path(name)
if not file.fileExists(manifest_path)
return 0
end if
let content = res.unwrap_or(file.readFile(manifest_path), "")
if str.length(content) == 0
return 0
end if
return mtree.parse_manifest(content, entries, max_count)
end load_old_manifest
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
// Build signature URL from remote package info
fn get_sig_url(pkg: repository.RemotePackage): string
mut base_url = pkg.repo_url
if not str.ends_with(base_url, "/")
base_url = base_url + "/"
end if
// If signature field contains a full URL, use it
if str.starts_with(pkg.signature, "http")
return pkg.signature
end if
// Otherwise construct from filename
return base_url + "packages/" + pkg.filename + ".sig"
end get_sig_url
// Download a signature file
fn download_signature(url: string, dest: string): bool
return uhttp.download(url, dest)
end download_signature
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: key.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Key command - manage signing keys
******************************************************************************/
module commands.key
import sys.args
import sys.process
import io.file
import io.dir
import core.str
import core.signing
import util.color
import exitcodes as ec
import core.result as res
export
fn execute(): int
end export
fn execute(): int
let argc = args.count()
if argc < 3
print_usage()
return ec.EXIT_USAGE()
end if
let subcommand = args.get(2)
if subcommand == "list"
list_keys()
return ec.EXIT_SUCCESS()
elif subcommand == "generate"
if argc < 4
color.print_error("Missing key name")
println("Usage: coral key generate <name>")
return ec.EXIT_USAGE()
end if
generate_key(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "import"
if argc < 4
color.print_error("Missing key file")
println("Usage: coral key import <file> [name]")
return ec.EXIT_USAGE()
end if
let key_file = args.get(3)
mut name = ""
if argc >= 5
name = args.get(4)
end if
import_key(key_file, name)
return ec.EXIT_SUCCESS()
elif subcommand == "export"
if argc < 4
color.print_error("Missing key name")
println("Usage: coral key export <name>")
return ec.EXIT_USAGE()
end if
export_key(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "delete"
if argc < 4
color.print_error("Missing key name")
println("Usage: coral key delete <name>")
return ec.EXIT_USAGE()
end if
delete_key(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "init"
init_keyring()
return ec.EXIT_SUCCESS()
elif subcommand == "trust"
if argc < 4
color.print_error("Missing key name")
println("Usage: coral key trust <name>")
return ec.EXIT_USAGE()
end if
trust_key(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "revoke"
if argc < 4
color.print_error("Missing key name")
println("Usage: coral key revoke <name>")
return ec.EXIT_USAGE()
end if
revoke_key(args.get(3))
return ec.EXIT_SUCCESS()
else
color.print_error("Unknown subcommand: " + subcommand)
print_usage()
return ec.EXIT_USAGE()
end if
end execute
proc list_keys()
color.print_action("Signing keys:")
println("")
mut keys: [signing.KeyPair] = new [signing.KeyPair](64)
let count = signing.list_keys(keys, 64)
if count == 0
color.print_info("No keys found")
println("")
color.print_info("Generate a key with: coral key generate <name>")
return
end if
mut i = 0
while i < count
let key = keys[i]
print(" ")
print(key.name)
if str.length(key.private_key) > 0
print(" [private+public]")
else
print(" [public only]")
end if
if key.trusted
print(" [trusted]")
end if
println("")
i = i + 1
end while
println("")
color.print_info("Total: " + int_to_str(count) + " key(s)")
end list_keys
proc generate_key(name: string)
color.print_action("Generating Ed25519 keypair: " + name)
let result = signing.generate_keypair(name)
if result.success
color.print_success("Keypair generated successfully")
println("")
color.print_info("Private key: " + signing.get_keyring_dir() + "/" + name + ".key")
color.print_info("Public key: " + signing.get_keyring_dir() + "/" + name + ".pub")
else
color.print_error(result.error)
end if
end generate_key
proc import_key(key_file: string, name: string)
if not file.fileExists(key_file)
color.print_error("Key file not found: " + key_file)
return
end if
// Determine name from filename if not provided
mut key_name = name
if str.length(key_name) == 0
key_name = extract_name(key_file)
end if
if str.length(key_name) == 0
color.print_error("Could not determine key name. Please specify one.")
return
end if
color.print_action("Importing key: " + key_name)
let key_data = res.unwrap_or(file.readFile(key_file), "")
let result = signing.import_key(key_data, key_name)
if result.success
color.print_success("Key imported successfully")
else
color.print_error(result.error)
end if
end import_key
proc export_key(name: string)
let keyring = signing.get_keyring_dir()
let pub_path = keyring + "/" + name + ".pub"
if not file.fileExists(pub_path)
color.print_error("Key not found: " + name)
return
end if
color.print_action("Public key for " + name + ":")
println("")
let key_data = res.unwrap_or(file.readFile(pub_path), "")
println(key_data)
end export_key
proc delete_key(name: string)
let keyring = signing.get_keyring_dir()
// Check if key exists
let pub_path = keyring + "/" + name + ".pub"
let priv_path = keyring + "/" + name + ".key"
if not file.fileExists(pub_path) and not file.fileExists(priv_path)
color.print_error("Key not found: " + name)
return
end if
// Ask for confirmation if private key exists
if file.fileExists(priv_path)
color.print_warning("This will delete the private key! Are you sure?")
color.print_info("Use --force to confirm deletion")
if not args.has_flag("force")
return
end if
end if
// Delete files
if file.fileExists(pub_path)
let cmd1 = "rm -f \"" + pub_path + "\""
let pid1 = process.process_spawn_shell(cmd1)
if pid1 > 0
process.process_wait(pid1)
end if
end if
if file.fileExists(priv_path)
let cmd2 = "rm -f \"" + priv_path + "\""
let pid2 = process.process_spawn_shell(cmd2)
if pid2 > 0
process.process_wait(pid2)
end if
end if
color.print_success("Deleted key: " + name)
end delete_key
fn extract_name(path: string): string
// Extract filename without extension
let len = str.length(path)
if len == 0
return ""
end if
// Find last slash
mut start = 0
mut i = 0
while i < len
if path[i] == '/'
start = i + 1
end if
i = i + 1
end while
// Find last dot
mut end_pos = len
i = len - 1
while i >= start
if path[i] == '.'
end_pos = i
end if
i = i - 1
end while
if end_pos <= start
return str.substring(path, start, len - start)
end if
return str.substring(path, start, end_pos - start)
end extract_name
// Initialize the keyring directory structure
proc init_keyring()
color.print_action("Initializing keyring...")
let keyring = signing.get_keyring_dir()
let trusted_keys_dir = "/var/lib/coral/trusted-keys"
// Create keyring directory
if not dir.dir_exists(keyring)
if not res.is_ok(dir.create_dir_all(keyring))
color.print_error("Failed to create keyring directory: " + keyring)
return
end if
color.print_info("Created: " + keyring)
else
color.print_info("Keyring already exists: " + keyring)
end if
// Create trusted-keys directory
if not dir.dir_exists(trusted_keys_dir)
if not res.is_ok(dir.create_dir_all(trusted_keys_dir))
color.print_error("Failed to create trusted-keys directory")
return
end if
color.print_info("Created: " + trusted_keys_dir)
else
color.print_info("Trusted keys directory already exists: " + trusted_keys_dir)
end if
// Set permissions (keyring should be root-only for private keys)
let cmd = "chmod 700 \"" + keyring + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
color.print_success("Keyring initialized")
color.print_info("Generate keys with: coral key generate <name>")
end init_keyring
// Add a key to the trusted keys list
proc trust_key(name: string)
let keyring = signing.get_keyring_dir()
let trusted_dir = "/var/lib/coral/trusted-keys"
let pub_path = keyring + "/" + name + ".pub"
// Check if key exists
if not file.fileExists(pub_path)
color.print_error("Key not found: " + name)
color.print_info("Import or generate the key first")
return
end if
// Ensure trusted-keys directory exists
if not dir.dir_exists(trusted_dir)
if not res.is_ok(dir.create_dir_all(trusted_dir))
color.print_error("Failed to create trusted-keys directory")
return
end if
end if
// Check if already trusted
let trusted_path = trusted_dir + "/" + name + ".pub"
if file.fileExists(trusted_path)
color.print_warning("Key already trusted: " + name)
return
end if
// Copy public key to trusted directory
let cmd = "cp \"" + pub_path + "\" \"" + trusted_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to copy key")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Failed to trust key")
return
end if
color.print_success("Trusted key: " + name)
color.print_info("Packages signed with this key will now be accepted")
end trust_key
// Remove a key from the trusted keys list
proc revoke_key(name: string)
let trusted_dir = "/var/lib/coral/trusted-keys"
let trusted_path = trusted_dir + "/" + name + ".pub"
// Check if key is trusted
if not file.fileExists(trusted_path)
color.print_error("Key is not in trusted list: " + name)
return
end if
// Confirm revocation
if not args.has_flag("force") and not args.has_flag("yes")
color.print_warning("This will revoke trust for key: " + name)
color.print_info("Use --force or -y to confirm")
return
end if
// Remove from trusted keys
let cmd = "rm -f \"" + trusted_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to revoke key")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Failed to remove key from trusted list")
return
end if
color.print_success("Revoked trust for key: " + name)
color.print_info("Packages signed with this key will no longer be accepted")
end revoke_key
// List trusted keys
proc list_trusted_keys()
let trusted_dir = "/var/lib/coral/trusted-keys"
if not dir.dir_exists(trusted_dir)
color.print_info("No trusted keys (directory does not exist)")
return
end if
let entries = res.unwrap_or(dir.list_dir(trusted_dir), new [string](0))
let count = entries.length()
if count == 0
color.print_info("No trusted keys")
return
end if
println("")
color.print_action("Trusted keys:")
mut i = 0
while i < count
let entry = entries[i]
if str.ends_with(entry, ".pub")
let name = str.substring(entry, 0, str.length(entry) - 4)
println(" " + name)
end if
i = i + 1
end while
end list_trusted_keys
proc print_usage()
println("Usage: coral key <command> [options]")
println("")
println("Manage signing keys for package verification.")
println("")
println("Commands:")
println(" list List all keys in keyring")
println(" generate <name> Generate a new Ed25519 keypair")
println(" import <file> [name] Import a public key")
println(" export <name> Export a public key")
println(" delete <name> Delete a key (use --force for private keys)")
println("")
println("Trust management:")
println(" init Initialize keyring directories")
println(" trust <name> Add key to trusted list")
println(" revoke <name> Remove key from trusted list")
println("")
println("Examples:")
println(" coral key init")
println(" coral key generate maintainer")
println(" coral key import repo.pub community")
println(" coral key trust community")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: list.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: List installed or available packages
******************************************************************************/
module commands.list
import sys.args
import core.str
import core.config
import core.database
import core.port
import core.portindex
import types
import util.color
import exitcodes as ec
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
// Check for --available flag
if args.has_flag("available") or args.has_flag("a")
list_available()
return ec.EXIT_SUCCESS()
end if
// Default: list installed packages
list_installed(root_path)
return ec.EXIT_SUCCESS()
end execute
proc list_installed(root_path: string)
mut packages: [string] = new [string](512)
let pkg_count = list_installed_pkgs(packages, 512, root_path)
if pkg_count == 0
color.print_info("No packages installed")
return
end if
color.print_action("Installed packages:")
println("")
mut i = 0
while i < pkg_count
let pkg_name = packages[i]
let pkg = get_installed_pkg(pkg_name, root_path)
// Format: name version
print(" ")
print(pkg.info.name)
print(" ")
print(pkg.info.version)
print("-")
println(int_to_str(pkg.info.release))
i = i + 1
end while
println("")
color.print_info("Total: " + int_to_str(pkg_count) + " packages")
end list_installed
// Helper functions for rooted operations
fn list_installed_pkgs(names: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.list_installed_rooted(names, max_count, root_path)
end if
return database.list_installed(names, max_count)
end list_installed_pkgs
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_installed_pkg
proc list_available()
color.print_action("Available ports:")
println("")
mut total = 0
// Try ports index first (fast path)
if portindex.port_index_exists()
mut entries: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](4096)
let entry_count = portindex.list_all_ports(entries, 4096)
// Group by category for display
mut current_cat = ""
mut i = 0
while i < entry_count
let entry = entries[i]
if not str.equals(entry.category, current_cat)
if str.length(current_cat) > 0
println("")
end if
current_cat = entry.category
color.print_info(current_cat + "/")
end if
print(" ")
print(entry.name)
print(" ")
print(entry.version)
print(" - ")
println(entry.description)
total = total + 1
i = i + 1
end while
else
// Fall back to filesystem scan
mut cats: [string] = new [string](32)
let cat_count = port.get_categories(cats, 32)
mut i = 0
while i < cat_count
let category = cats[i]
mut ports: [string] = new [string](256)
let port_count = port.list_category(category, ports, 256)
if port_count > 0
color.print_info(category + "/")
mut j = 0
while j < port_count
let port_name = ports[j]
let result = port.find(port_name)
if result.success
let p = result.port
print(" ")
print(p.info.name)
print(" ")
print(p.info.version)
print(" - ")
println(p.info.description)
end if
j = j + 1
total = total + 1
end while
println("")
end if
i = i + 1
end while
end if
println("")
color.print_info("Total: " + int_to_str(total) + " ports")
end list_available
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: outdated.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Outdated command - show packages with available updates
******************************************************************************/
module commands.outdated
import sys.args
import core.str
import core.database
import core.port
import types
import util.color
import exitcodes as ec
export
fn execute(): int
end export
fn execute(): int
color.print_action("Checking for available updates...")
println("")
// Get list of installed packages
mut installed: [string] = new [string](512)
let installed_count = database.list_installed(installed, 512)
if installed_count == 0
color.print_info("No packages installed")
return ec.EXIT_SUCCESS()
end if
// Check each package for updates
mut outdated_count = 0
mut i = 0
while i < installed_count
let pkg_name = installed[i]
let installed_pkg = database.get_installed(pkg_name)
// Find port
let port_result = port.find(pkg_name)
if port_result.success
let p = port_result.port
// Compare versions
let cmp = compare_versions(installed_pkg.info.version, p.info.version)
if cmp < 0
// Outdated
if outdated_count == 0
color.print_info("Outdated packages:")
println("")
end if
print(" ")
print(pkg_name)
print(" ")
print(installed_pkg.info.version)
print("-")
print(int_to_str(installed_pkg.info.release))
print(" -> ")
print(p.info.version)
print("-")
println(int_to_str(p.info.release))
outdated_count = outdated_count + 1
end if
end if
i = i + 1
end while
if outdated_count == 0
color.print_success("All packages are up to date")
// Return special code for scripting - no updates available
if args.has_flag("check")
return ec.EXIT_NO_UPDATES()
end if
return ec.EXIT_SUCCESS()
else
println("")
color.print_info(int_to_str(outdated_count) + " package(s) can be upgraded")
println("")
color.print_info("Run 'coral upgrade' to upgrade all packages")
color.print_info("Run 'coral upgrade <package>' to upgrade specific packages")
// Return special code for scripting - updates available
if args.has_flag("check")
return ec.EXIT_UPDATE_AVAILABLE()
end if
return ec.EXIT_SUCCESS()
end if
end execute
// Compare two version strings
// Returns: -1 if v1 < v2, 0 if equal, 1 if v1 > v2
fn compare_versions(v1: string, v2: string): int
// Split versions into parts
mut parts1: [string] = new [string](10)
mut parts2: [string] = new [string](10)
let count1 = str.split(v1, '.', parts1, 10)
let count2 = str.split(v2, '.', parts2, 10)
// Compare each part
mut i = 0
let max_parts = max_int(count1, count2)
while i < max_parts
mut n1 = 0
mut n2 = 0
if i < count1
n1 = parse_int(parts1[i])
end if
if i < count2
n2 = parse_int(parts2[i])
end if
if n1 < n2
return 0 - 1
elif n1 > n2
return 1
end if
i = i + 1
end while
return 0
end compare_versions
fn max_int(a: int, b: int): int
if a > b
return a
end if
return b
end max_int
// Parse integer from string
fn parse_int(s: string): int
let len = str.length(s)
if len == 0
return 0
end if
mut result = 0
mut i = 0
while i < len
let c = s[i]
if c >= '0' and c <= '9'
result = result * 10 + (c - '0')
else
// Stop at non-digit
return result
end if
i = i + 1
end while
return result
end parse_int
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: owner.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Owner command - find which package owns a file
******************************************************************************/
module commands.owner
import sys.args
import core.str
import core.config
import core.database
import core.pkgdb
import types
import util.color
import exitcodes as ec
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// File path should be at cmd_index + 1
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
let file_path = args.get(opts.cmd_index + 1)
// Find owner (use rooted version if root is set)
let owner = find_owner(file_path, root_path)
if str.length(owner) == 0
color.print_error("No package owns: " + file_path)
return ec.EXIT_PKG_NOT_FOUND()
end if
// Get package info (use rooted version if root is set)
let pkg = get_installed_pkg(owner, root_path)
color.print_action("File: " + file_path)
println("")
println("Owned by: " + owner + " " + pkg.info.version)
return ec.EXIT_SUCCESS()
end execute
// Helper functions for rooted operations
// Uses pkgdb for fast indexed lookup with fallback to database scan
fn find_owner(file_path: string, root_path: string): string
return pkgdb.find_file_owner_rooted(file_path, root_path)
end find_owner
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_installed_pkg
proc print_usage()
println("Usage: coral owner <file>")
println("")
println("Find which package owns a given file.")
println("")
println("Arguments:")
println(" <file> Path to the file to look up")
println("")
println("Examples:")
println(" coral owner /usr/bin/vim")
println(" coral owner /usr/bin/hello")
end print_usage
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: ports.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Ports command - port scaffolding and cache management
******************************************************************************/
module commands.ports
import sys.args
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.portindex
import types
import util.color
import exitcodes as ec
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
let subcommand = args.get(opts.cmd_index + 1)
if subcommand == "new"
return ports_new(opts)
elif subcommand == "cache"
return ports_cache(opts)
else
color.print_error("Unknown subcommand: " + subcommand)
print_usage()
return ec.EXIT_USAGE()
end if
end execute
// ============================================================================
// coral ports new <category/name>
// ============================================================================
fn ports_new(opts: types.GlobalOptions): int
let argc = args.count()
if argc <= opts.cmd_index + 2
color.print_error("Missing argument: category/name")
println("Usage: coral ports new <category/name>")
return ec.EXIT_USAGE()
end if
let arg = args.get(opts.cmd_index + 2)
// Require slash format
let slash_idx = str.index_of(arg, "/")
if slash_idx <= 0
color.print_error("Invalid format: '" + arg + "'")
println("Use category/name format, e.g.: coral ports new hammerhead/my-port")
return ec.EXIT_USAGE()
end if
let category = str.substring(arg, 0, slash_idx)
let name = str.substring(arg, slash_idx + 1, str.length(arg) - slash_idx - 1)
if str.length(name) == 0
color.print_error("Port name cannot be empty")
return ec.EXIT_USAGE()
end if
// Get ports directory
let cfg = config.load()
let ports_dir = config.get_ports_dir(cfg)
// Create port directory
let port_dir = path.join_path(ports_dir, path.join_path(category, name))
if dir.dir_exists(port_dir)
color.print_error("Port directory already exists: " + port_dir)
return ec.EXIT_PKG_ALREADY_INSTALLED()
end if
if not res.is_ok(dir.create_dir_all(port_dir))
color.print_error("Failed to create directory: " + port_dir)
return ec.EXIT_PERMISSION_DENIED()
end if
// Generate package.toml
let toml_path = path.join_path(port_dir, "package.toml")
let toml_content = "[package]\nname = \"" + name + "\"\nversion = \"0.1.0\"\nrelease = 1\ndescription = \"\"\nurl = \"\"\nlicense = \"\"\nmaintainer = \"\"\narch = \"x86_64\"\n\n[dependencies]\nruntime = []\nbuild = []\n\n[[source]]\nfile = \"\"\nurls = []\nchecksum = \"SKIP\"\n\n[build]\nparallel = true\njobs = 0\n"
if not res.is_ok(file.writeFile(toml_path, toml_content))
color.print_error("Failed to write package.toml")
return ec.EXIT_PERMISSION_DENIED()
end if
// Generate build.sh
let build_path = path.join_path(port_dir, "build.sh")
let dollar = "$"
let build_content = "#!/bin/sh\n# Build script for " + name + "\nset -e\n\n# cd " + name + "-" + dollar + "{VERSION}\n\nMAKE=gmake\nif [ \"" + dollar + "(uname -s)\" != \"SunOS\" ]; then\n MAKE=make\nfi\n\n# ./configure --prefix=/usr\n# " + dollar + "MAKE " + dollar + "{MAKEFLAGS}\n# " + dollar + "MAKE DESTDIR=\"" + dollar + "{DESTDIR}\" install\n"
if not res.is_ok(file.writeFile(build_path, build_content))
color.print_error("Failed to write build.sh")
return ec.EXIT_PERMISSION_DENIED()
end if
color.print_success("Port created: " + category + "/" + name)
println("")
println(" Directory: " + port_dir)
println(" package.toml: " + toml_path)
println(" build.sh: " + build_path)
println("")
color.print_info("Next steps:")
println(" 1. Edit package.toml with package details")
println(" 2. Add source URLs and checksums")
println(" 3. Write the build.sh script")
println(" 4. Test with: coral build " + category + "/" + name)
return ec.EXIT_SUCCESS()
end ports_new
// ============================================================================
// coral ports cache [status|rebuild]
// ============================================================================
fn ports_cache(opts: types.GlobalOptions): int
let argc = args.count()
if argc <= opts.cmd_index + 2
// Default to status
return cache_status()
end if
let subcmd = args.get(opts.cmd_index + 2)
if subcmd == "status"
return cache_status()
elif subcmd == "rebuild"
return cache_rebuild()
else
color.print_error("Unknown cache subcommand: " + subcmd)
println("Usage: coral ports cache [status|rebuild]")
return ec.EXIT_USAGE()
end if
end ports_cache
fn cache_status(): int
color.print_action("Ports index status:")
println("")
if portindex.port_index_exists()
let count = portindex.get_port_count()
println(" Status: built")
println(" Ports indexed: " + int_to_str(count))
else
println(" Status: not built")
color.print_info("Run 'coral ports cache rebuild' to build the index")
end if
return ec.EXIT_SUCCESS()
end cache_status
fn cache_rebuild(): int
color.print_action("Rebuilding ports index...")
println("")
if portindex.rebuild_port_index()
let count = portindex.get_port_count()
color.print_success("Ports index rebuilt successfully")
println(" Ports indexed: " + int_to_str(count))
return ec.EXIT_SUCCESS()
else
color.print_error("Failed to rebuild ports index")
return ec.EXIT_DB_ERROR()
end if
end cache_rebuild
// ============================================================================
// Usage
// ============================================================================
proc print_usage()
println("Usage: coral ports <command> [args]")
println("")
println("Port development and cache management.")
println("")
println("Commands:")
println(" new <category/name> Scaffold a new port")
println(" cache [status] Show ports index status")
println(" cache rebuild Rebuild ports index")
println("")
println("Examples:")
println(" coral ports new hammerhead/my-port")
println(" coral ports cache status")
println(" coral ports cache rebuild")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: remove.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Remove command - uninstall packages
******************************************************************************/
module commands.remove
import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.pkgdb
import core.package
import core.port
import util.prompt
import util.mtree
import util.checksum
import types
import util.color
import fs.stat
import fs.ops
import util.priv
import exitcodes as ec
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Package arguments should be after the command
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
// Collect packages to remove
mut packages: [string] = new [string](256)
mut pkg_count = 0
mut i = opts.cmd_index + 1
while i < argc and pkg_count < 256
let pkg_name = args.get(i)
// Skip flags and their values
if pkg_name == "--root" or pkg_name == "--prefix"
i = i + 2 // Skip flag and its value
continue
elif pkg_name == "--no-chroot-scripts"
i = i + 1 // valueless flag: skip only itself
continue
end if
if str.starts_with(pkg_name, "-")
i = i + 1
continue
end if
// Check if installed (use rooted version if root is set)
let installed = check_installed(pkg_name, root_path)
if installed
packages[pkg_count] = pkg_name
pkg_count = pkg_count + 1
else
color.print_warning(pkg_name + " is not installed")
end if
i = i + 1
end while
if pkg_count == 0
color.print_info("No packages to remove")
return ec.EXIT_SUCCESS()
end if
// Check for reverse dependencies (packages that depend on these)
mut dependents: [string] = new [string](256)
mut dependent_count = 0
i = 0
while i < pkg_count
let pkg_name = packages[i]
let count = get_reverse_dependencies(pkg_name, dependents, dependent_count, 256)
dependent_count = count
i = i + 1
end while
// Warn if there are dependents
if dependent_count > 0
color.print_warning("The following installed packages depend on packages being removed:")
i = 0
while i < dependent_count
println(" - " + dependents[i])
i = i + 1
end while
// Require --force to proceed
if not opts.force
color.print_error("Use --force to remove packages with dependents")
return ec.EXIT_DEPS_CONFLICT()
end if
color.print_warning("Proceeding with removal (--force specified)")
end if
// Ask for confirmation (unless -y flag)
if not prompt.confirm_remove(packages, pkg_count, dependents, dependent_count, opts)
color.print_info("Removal cancelled")
return ec.EXIT_CANCELLED()
end if
// Dry-run: show what would be done and exit
if opts.dry_run
color.print_info("Dry run — no changes made")
return ec.EXIT_SUCCESS()
end if
// Remove packages
mut all_success = true
i = 0
while i < pkg_count
if not remove_package(packages[i], root_path, cfg)
color.print_error("Failed to remove: " + packages[i])
all_success = false
end if
i = i + 1
end while
if all_success
return ec.EXIT_SUCCESS()
else
return ec.EXIT_REMOVE_FAILED()
end if
end execute
// Check if package is installed, using rooted check if root is set
fn check_installed(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end check_installed
proc print_usage()
println("Usage: coral remove <package...>")
println("")
println("Remove one or more installed packages.")
println("")
println("Arguments:")
println(" <package> Name of installed package to remove")
println("")
println("Options:")
println(" -y, --yes Don't ask for confirmation")
println(" -f, --force Remove even if other packages depend on it")
println("")
println("Examples:")
println(" coral remove vim")
println(" coral remove vim nano htop")
println(" coral remove --force libfoo")
end print_usage
fn remove_package(pkg_name: string, root_path: string, cfg: config.Config): bool
// Check if package is installed (use rooted version if root is set)
if not check_installed(pkg_name, root_path)
color.print_error(pkg_name + " is not installed")
return false
end if
color.print_action("Removing " + pkg_name + "...")
let install_root = get_actual_root(root_path)
// Resolve script execution context; abort early if confinement is required but impossible.
// Defense-in-depth: main.reef already bars non-root for all non-query commands, so this abort
// is currently unreachable via the CLI. Kept so confinement fails safely if that global gate is
// ever relaxed.
if package.script_wants_chroot(install_root, config.get_chroot_scripts(cfg)) and not priv.is_root()
color.print_error("--root " + install_root + " runs maintainer scripts confined to the target via chroot, which requires root privileges.")
color.print_error("Re-run as root, or pass --no-chroot-scripts to run them on the host (unconfined).")
return false
end if
let script_ctx = package.resolve_script_ctx(install_root, config.get_chroot_scripts(cfg), priv.is_root())
// Get package info (use rooted version if root is set)
let pkg = get_installed_pkg(pkg_name, root_path)
color.print_info("Package: " + pkg.info.name + " " + pkg.info.version)
// Get file list from database (use rooted version if root is set)
mut files: [string] = new [string](4096)
let file_count = get_files_list(pkg_name, files, 4096, root_path)
if file_count == 0
color.print_warning("No files recorded for package")
else
color.print_info("Removing " + int_to_str(file_count) + " files...")
end if
// Run pre-remove script if present (abort on failure)
let scripts_dir = database.get_scripts_dir(pkg_name)
if database.has_stored_scripts(pkg_name)
color.print_info("Running pre-remove script...")
if not package.run_stored_pre_remove(script_ctx, scripts_dir, pkg.info.version)
color.print_error("Pre-remove script failed, aborting removal of " + pkg_name)
return false
end if
end if
// Load config file list and manifest checksums for config protection
mut config_files: [string] = new [string](256)
let config_count = database.get_config_files(pkg_name, config_files, 256)
mut manifest_entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
mut manifest_count = 0
let manifest_path = database.get_manifest_path(pkg_name)
if file.fileExists(manifest_path)
let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
if str.length(manifest_content) > 0
manifest_count = mtree.parse_manifest(manifest_content, manifest_entries, 8192)
end if
end if
// Remove files (with proper root path, respecting config protection)
let actual_root = get_actual_root(root_path)
if not remove_files(files, file_count, actual_root, config_files, config_count, manifest_entries, manifest_count)
color.print_warning("Some files could not be removed")
// Continue anyway - unregister from database
end if
// Run post-remove script if present (warn on failure, don't abort)
if database.has_stored_scripts(pkg_name)
color.print_info("Running post-remove script...")
if not package.run_stored_post_remove(script_ctx, scripts_dir, pkg.info.version)
color.print_warning("Post-remove script failed")
end if
end if
// Unregister from database (use rooted version if root is set)
color.print_info("Unregistering package...")
if not unregister_pkg(pkg_name, root_path)
color.print_error("Failed to unregister package from database")
return false
end if
// Update package database indexes
if not pkgdb.rebuild_indexes_rooted(root_path)
color.print_warning("Failed to update package indexes")
end if
color.print_success("Removed " + pkg_name)
return true
end remove_package
// Get installed package info, using rooted check if root is set
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_installed_pkg
// Get files list, using rooted check if root is set
fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.get_files_rooted(name, files, max_count, root_path)
end if
return database.get_files(name, files, max_count)
end get_files_list
// Unregister package, using rooted version if root is set
fn unregister_pkg(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.unregister_package_rooted(name, root_path)
end if
return database.unregister_package(name)
end unregister_pkg
// Get actual root path (returns "/" if empty)
fn get_actual_root(root_path: string): string
if str.length(root_path) == 0
return "/"
end if
return root_path
end get_actual_root
// Remove files from system, respecting config file protection
fn remove_files(files: [string], file_count: int, root_path: string, config_files: [string], config_count: int, manifest_entries: [mtree.ManifestEntry], manifest_count: int): bool
mut all_success = true
// Remove files in reverse order
mut i = file_count - 1
while i >= 0
let rel_path = files[i]
let full_path = path.join_path(root_path, rel_path)
if stat.is_symlink(full_path) or stat.exists(full_path)
// Check if this is a config file that the user has modified
if config_count > 0 and package.is_config_file(rel_path, config_files, config_count)
// Look up the package's sha256 from the manifest
let pkg_sha = find_manifest_sha256(rel_path, manifest_entries, manifest_count)
if str.length(pkg_sha) > 0
let installed_sha = checksum.sha256_file(full_path)
if not str.equals(installed_sha, pkg_sha)
// User has modified this config — preserve it
color.print_info("Preserving modified config: " + rel_path)
i = i - 1
continue
end if
end if
end if
if not res.is_ok(ops.remove_file(full_path))
color.print_warning("Failed to remove: " + full_path)
all_success = false
end if
end if
i = i - 1
end while
// Try to remove empty parent directories
i = file_count - 1
while i >= 0
let rel_path = files[i]
let full_path = path.join_path(root_path, rel_path)
let parent = path.dirname(full_path)
if str.length(parent) > str.length(root_path) and dir.dir_exists(parent)
dir.remove_dir(parent)
end if
i = i - 1
end while
return all_success
end remove_files
// Look up the sha256 for a given relative path in the manifest entries
fn find_manifest_sha256(rel_path: string, entries: [mtree.ManifestEntry], count: int): string
mut i = 0
while i < count
let epath = mtree.entry_path(entries[i])
// Compare with and without ./ prefix
mut entry_rel = epath
if str.starts_with(epath, "./")
entry_rel = str.substring(epath, 2, str.length(epath) - 2)
end if
if str.equals(entry_rel, rel_path)
return mtree.entry_sha256(entries[i])
end if
i = i + 1
end while
return ""
end find_manifest_sha256
// Get packages that depend on the given package
// Returns new total count (existing + new dependents)
fn get_reverse_dependencies(pkg_name: string, dependents: [string], current_count: int, max_count: int): int
mut count = current_count
// List all installed packages
mut installed: [string] = new [string](512)
let installed_count = database.list_installed(installed, 512)
mut i = 0
while i < installed_count and count < max_count
let other_pkg = installed[i]
// Skip the package being removed and already listed dependents
if str.equals(other_pkg, pkg_name)
i = i + 1
continue
end if
// Check if already in dependents list
if array_contains(dependents, count, other_pkg)
i = i + 1
continue
end if
// Try to find this package's port to get its dependencies
let port_result = port.find(other_pkg)
if port_result.success
let p = port_result.port
// Check runtime dependencies
if depends_on(p.deps.runtime, p.deps.runtime_count, pkg_name)
dependents[count] = other_pkg
count = count + 1
end if
end if
i = i + 1
end while
return count
end get_reverse_dependencies
// Check if a dependency list contains the given package
fn depends_on(deps: [string], dep_count: int, pkg_name: string): bool
mut i = 0
while i < dep_count
let dep = deps[i]
// Handle alternative dependencies (format: base:opt1,opt2)
let colon_pos = str.index_of_char(dep, ':')
mut base_dep = dep
if colon_pos > 0
base_dep = str.substring(dep, 0, colon_pos)
end if
if str.equals(base_dep, pkg_name)
return true
end if
i = i + 1
end while
return false
end depends_on
// Helper to check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
mut i = 0
while i < count
if str.equals(arr[i], s)
return true
end if
i = i + 1
end while
return false
end array_contains
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: repo.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Repo command - manage package repositories
******************************************************************************/
module commands.repo
import sys.args
import sys.process
import io.file
import io.dir
import core.str
import core.repository
import util.color
import exitcodes as ec
import core.result as res
export
fn execute(): int
end export
fn execute(): int
let argc = args.count()
if argc < 3
print_usage()
return ec.EXIT_USAGE()
end if
let subcommand = args.get(2)
if subcommand == "list"
list_repos()
return ec.EXIT_SUCCESS()
elif subcommand == "add"
if argc < 4
color.print_error("Missing repository URL")
println("Usage: coral repo add <url> [name]")
return ec.EXIT_USAGE()
end if
let url = args.get(3)
mut name = ""
if argc >= 5
name = args.get(4)
end if
add_repo(url, name)
return ec.EXIT_SUCCESS()
elif subcommand == "remove"
if argc < 4
color.print_error("Missing repository name")
println("Usage: coral repo remove <name>")
return ec.EXIT_USAGE()
end if
remove_repo(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "enable"
if argc < 4
color.print_error("Missing repository name")
return ec.EXIT_USAGE()
end if
enable_repo(args.get(3), true)
return ec.EXIT_SUCCESS()
elif subcommand == "disable"
if argc < 4
color.print_error("Missing repository name")
return ec.EXIT_USAGE()
end if
enable_repo(args.get(3), false)
return ec.EXIT_SUCCESS()
elif subcommand == "init"
if argc < 4
color.print_error("Missing repository path")
println("Usage: coral repo init <path>")
return ec.EXIT_USAGE()
end if
init_repo(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "rebuild"
if argc < 4
color.print_error("Missing repository path")
println("Usage: coral repo rebuild <path>")
return ec.EXIT_USAGE()
end if
rebuild_repo(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "sign"
if argc < 4
color.print_error("Missing repository path")
println("Usage: coral repo sign <path> [keyname]")
return ec.EXIT_USAGE()
end if
let repo_path = args.get(3)
mut key_name = "default"
if argc >= 5
key_name = args.get(4)
end if
sign_repo(repo_path, key_name)
return ec.EXIT_SUCCESS()
elif subcommand == "verify"
if argc < 4
color.print_error("Missing repository path")
println("Usage: coral repo verify <path>")
return ec.EXIT_USAGE()
end if
verify_repo(args.get(3))
return ec.EXIT_SUCCESS()
elif subcommand == "mirror"
if argc < 5
color.print_error("Missing source or destination")
println("Usage: coral repo mirror <source> <dest>")
return ec.EXIT_USAGE()
end if
mirror_repo(args.get(3), args.get(4))
return ec.EXIT_SUCCESS()
elif subcommand == "export"
if argc < 5
color.print_error("Missing repository path or output")
println("Usage: coral repo export <path> <output>")
return ec.EXIT_USAGE()
end if
export_repo(args.get(3), args.get(4))
return ec.EXIT_SUCCESS()
else
color.print_error("Unknown subcommand: " + subcommand)
print_usage()
return ec.EXIT_USAGE()
end if
end execute
proc list_repos()
color.print_action("Configured repositories:")
println("")
mut repos: [repository.Repository] = new [repository.Repository](32)
let count = repository.list_repos(repos, 32)
if count == 0
color.print_info("No repositories configured")
println("")
color.print_info("Add a repository with: coral repo add <url>")
return
end if
mut i = 0
while i < count
let repo = repos[i]
print(" ")
print(repo.name)
print(" - ")
print(repo.url)
if not repo.enabled
print(" [disabled]")
end if
if repo.is_signed
print(" [signed]")
end if
println("")
i = i + 1
end while
println("")
color.print_info("Total: " + int_to_str(count) + " repository(ies)")
end list_repos
proc add_repo(url: string, name: string)
color.print_action("Adding repository...")
// Generate name from URL if not provided
mut repo_name = name
if str.length(repo_name) == 0
repo_name = extract_repo_name(url)
end if
if str.length(repo_name) == 0
color.print_error("Could not determine repository name. Please specify one.")
return
end if
// Create repo file
let repos_dir = "/etc/coral/repos.d"
let repo_path = repos_dir + "/" + repo_name + ".repo"
// Check if it exists
if file.fileExists(repo_path)
color.print_error("Repository already exists: " + repo_name)
return
end if
// Ensure directory exists
if not dir.dir_exists(repos_dir)
if not res.is_ok(dir.create_dir_all(repos_dir))
color.print_error("Failed to create repos directory")
return
end if
end if
// Create repo file content
mut content = "[repository]\n"
content = content + "name = \"" + repo_name + "\"\n"
content = content + "url = \"" + url + "\"\n"
content = content + "priority = 100\n"
content = content + "enabled = true\n"
content = content + "signed = false\n"
if not res.is_ok(file.writeFile(repo_path, content))
color.print_error("Failed to write repository file")
return
end if
color.print_success("Added repository: " + repo_name)
end add_repo
proc remove_repo(name: string)
let repos_dir = "/etc/coral/repos.d"
let repo_path = repos_dir + "/" + name + ".repo"
if not file.fileExists(repo_path)
color.print_error("Repository not found: " + name)
return
end if
// Remove the file
let cmd = "rm -f \"" + repo_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
color.print_success("Removed repository: " + name)
end remove_repo
proc enable_repo(name: string, enable: bool)
let repos_dir = "/etc/coral/repos.d"
let repo_path = repos_dir + "/" + name + ".repo"
if not file.fileExists(repo_path)
color.print_error("Repository not found: " + name)
return
end if
// Read current content
let content = res.unwrap_or(file.readFile(repo_path), "")
// Replace enabled line
mut new_content = ""
if enable
new_content = str.replace(content, "enabled = false", "enabled = true")
else
new_content = str.replace(content, "enabled = true", "enabled = false")
end if
if not res.is_ok(file.writeFile(repo_path, new_content))
color.print_error("Failed to update repository file")
return
end if
if enable
color.print_success("Enabled repository: " + name)
else
color.print_success("Disabled repository: " + name)
end if
end enable_repo
fn extract_repo_name(url: string): string
// Extract name from URL (e.g., https://repo.example.com/zygaena -> zygaena)
let len = str.length(url)
if len == 0
return ""
end if
// Find last slash
mut last_slash = 0 - 1
mut i = 0
while i < len
if url[i] == '/'
last_slash = i
end if
i = i + 1
end while
if last_slash < 0 or last_slash >= len - 1
return "repo"
end if
return str.substring(url, last_slash + 1, len - last_slash - 1)
end extract_repo_name
// Initialize a new repository at the given path
proc init_repo(repo_path: string)
color.print_action("Initializing repository at " + repo_path)
// Create the repository directory
if not dir.dir_exists(repo_path)
if not res.is_ok(dir.create_dir_all(repo_path))
color.print_error("Failed to create repository directory")
return
end if
end if
// Create packages subdirectory
let packages_dir = repo_path + "/packages"
if not dir.dir_exists(packages_dir)
if not res.is_ok(dir.create_dir_all(packages_dir))
color.print_error("Failed to create packages directory")
return
end if
end if
// Create repo.toml manifest
let manifest_path = repo_path + "/repo.toml"
if file.fileExists(manifest_path)
color.print_warning("repo.toml already exists, skipping")
else
mut content = "# Coral Repository Manifest\n"
content = content + "# Generated by coral repo init\n\n"
content = content + "[repository]\n"
content = content + "name = \"unnamed\"\n"
content = content + "description = \"A Coral package repository\"\n"
content = content + "url = \"\"\n"
content = content + "arch = \"x86_64\"\n"
content = content + "created = \"2025-01-24\"\n"
content = content + "signed = false\n\n"
content = content + "# Packages will be listed below by coral repo rebuild\n"
content = content + "[packages]\n"
if not res.is_ok(file.writeFile(manifest_path, content))
color.print_error("Failed to write repo.toml")
return
end if
end if
color.print_success("Repository initialized at " + repo_path)
color.print_info("Place packages in: " + packages_dir)
color.print_info("Run 'coral repo rebuild " + repo_path + "' to update manifest")
end init_repo
// Rebuild repository manifest by scanning packages
proc rebuild_repo(repo_path: string)
color.print_action("Rebuilding repository manifest...")
let packages_dir = repo_path + "/packages"
if not dir.dir_exists(packages_dir)
color.print_error("Packages directory not found: " + packages_dir)
return
end if
// Scan for package files
let entries = res.unwrap_or(dir.list_dir(packages_dir), new [string](0))
let entry_count = entries.length()
mut pkg_count = 0
mut packages_content = ""
mut i = 0
while i < entry_count
let entry = entries[i]
// Look for .pkg.tar.xz files
if str.ends_with(entry, ".pkg.tar.xz")
// Parse package name and version from filename
// Format: name-version-release.arch.pkg.tar.xz
let info = parse_package_filename(entry)
if str.length(info) > 0
packages_content = packages_content + info + "\n"
pkg_count = pkg_count + 1
end if
end if
i = i + 1
end while
// Generate new repo.toml
let manifest_path = repo_path + "/repo.toml"
mut content = "# Coral Repository Manifest\n"
content = content + "# Rebuilt by coral repo rebuild\n\n"
content = content + "[repository]\n"
content = content + "name = \"unnamed\"\n"
content = content + "description = \"A Coral package repository\"\n"
content = content + "url = \"\"\n"
content = content + "arch = \"x86_64\"\n"
content = content + "created = \"2025-01-24\"\n"
content = content + "signed = false\n\n"
content = content + "[packages]\n"
content = content + packages_content
if not res.is_ok(file.writeFile(manifest_path, content))
color.print_error("Failed to write repo.toml")
return
end if
color.print_success("Repository rebuilt: " + int_to_str(pkg_count) + " package(s) found")
end rebuild_repo
// Parse package filename into TOML entry
fn parse_package_filename(filename: string): string
// Extract name-version-release from filename
// Example: vim-9.0-1.x86_64.pkg.tar.xz -> vim = { version = "9.0", release = 1 }
// Remove .pkg.tar.xz suffix
let base = str.substring(filename, 0, str.length(filename) - 11)
// Find arch (e.g., .x86_64)
let arch_pos = str.last_index_of_char(base, '.')
if arch_pos < 0
return ""
end if
let name_ver_rel = str.substring(base, 0, arch_pos)
// Find release number (last hyphen)
let rel_pos = str.last_index_of_char(name_ver_rel, '-')
if rel_pos < 0
return ""
end if
let release = str.substring(name_ver_rel, rel_pos + 1, str.length(name_ver_rel) - rel_pos - 1)
// Find version (second to last hyphen)
let name_ver = str.substring(name_ver_rel, 0, rel_pos)
let ver_pos = str.last_index_of_char(name_ver, '-')
if ver_pos < 0
return ""
end if
let name = str.substring(name_ver, 0, ver_pos)
let version = str.substring(name_ver, ver_pos + 1, str.length(name_ver) - ver_pos - 1)
return name + " = { version = \"" + version + "\", release = " + release + ", file = \"" + filename + "\" }"
end parse_package_filename
// Sign the repository manifest
proc sign_repo(repo_path: string, key_name: string)
color.print_action("Signing repository manifest...")
let manifest_path = repo_path + "/repo.toml"
if not file.fileExists(manifest_path)
color.print_error("repo.toml not found in: " + repo_path)
return
end if
// Find the key
let keyring = "/etc/coral/keys"
let key_path = keyring + "/" + key_name + ".key"
if not file.fileExists(key_path)
color.print_error("Key not found: " + key_name)
color.print_info("Generate a key with: coral key generate " + key_name)
return
end if
// Sign the manifest using openssl
let sig_path = repo_path + "/repo.toml.sig"
let cmd = "openssl pkeyutl -sign -inkey \"" + key_path + "\" -in \"" + manifest_path + "\" -out \"" + sig_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to start signing process")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Signing failed")
return
end if
// Update repo.toml to indicate it's signed
let content = res.unwrap_or(file.readFile(manifest_path), "")
let new_content = str.replace(content, "signed = false", "signed = true")
file.writeFile(manifest_path, new_content)
color.print_success("Repository signed with key: " + key_name)
color.print_info("Signature: " + sig_path)
end sign_repo
// Verify repository signature
proc verify_repo(repo_path: string)
color.print_action("Verifying repository signature...")
let manifest_path = repo_path + "/repo.toml"
let sig_path = repo_path + "/repo.toml.sig"
if not file.fileExists(manifest_path)
color.print_error("repo.toml not found")
return
end if
if not file.fileExists(sig_path)
color.print_error("No signature found (repo.toml.sig)")
return
end if
// Try to find a matching public key
let keyring = "/etc/coral/keys"
if not dir.dir_exists(keyring)
color.print_error("No keys in keyring")
return
end if
// List all public keys and try each
let entries = res.unwrap_or(dir.list_dir(keyring), new [string](0))
let count = entries.length()
mut i = 0
mut verified = false
while i < count and not verified
let entry = entries[i]
if str.ends_with(entry, ".pub")
let key_path = keyring + "/" + entry
let cmd = "openssl pkeyutl -verify -pubin -inkey \"" + key_path + "\" -in \"" + manifest_path + "\" -sigfile \"" + sig_path + "\" 2>/dev/null"
let pid = process.process_spawn_shell(cmd)
if pid > 0
let exit_code = process.process_wait(pid)
if exit_code == 0
let key_name = str.substring(entry, 0, str.length(entry) - 4)
color.print_success("Signature verified with key: " + key_name)
verified = true
end if
end if
end if
i = i + 1
end while
if not verified
color.print_error("Signature verification failed - no matching key found")
end if
end verify_repo
// Mirror repository to remote destination
proc mirror_repo(source: string, dest: string)
color.print_action("Mirroring repository...")
color.print_info("Source: " + source)
color.print_info("Destination: " + dest)
// Use rsync for mirroring
let cmd = "rsync -av --delete \"" + source + "/\" \"" + dest + "/\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to start rsync")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Mirror sync failed")
return
end if
color.print_success("Repository mirrored to: " + dest)
end mirror_repo
// Export repository for offline distribution (ISO/USB)
proc export_repo(repo_path: string, output_path: string)
color.print_action("Exporting repository for offline distribution...")
if not dir.dir_exists(repo_path)
color.print_error("Repository not found: " + repo_path)
return
end if
// Determine output format based on extension
if str.ends_with(output_path, ".tar.xz")
// Create compressed tarball
let cmd = "gtar -C \"" + repo_path + "\" -cJf \"" + output_path + "\" ."
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to create archive")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Archive creation failed")
return
end if
elif str.ends_with(output_path, ".tar.gz")
let cmd = "gtar -C \"" + repo_path + "\" -czf \"" + output_path + "\" ."
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to create archive")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Archive creation failed")
return
end if
else
// Copy directory
let cmd = "cp -r \"" + repo_path + "\" \"" + output_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to copy repository")
return
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Copy failed")
return
end if
end if
color.print_success("Repository exported to: " + output_path)
end export_repo
proc print_usage()
println("Usage: coral repo <command> [options]")
println("")
println("Manage package repositories.")
println("")
println("Commands:")
println(" list List configured repositories")
println(" add <url> [name] Add a new repository")
println(" remove <name> Remove a repository")
println(" enable <name> Enable a repository")
println(" disable <name> Disable a repository")
println("")
println("Repository maintenance:")
println(" init <path> Create a new repository structure")
println(" rebuild <path> Scan packages and rebuild manifest")
println(" sign <path> [key] Sign repository with Ed25519 key")
println(" verify <path> Verify repository signature")
println(" mirror <src> <dst> Sync repository to mirror (rsync)")
println(" export <path> <out> Export for offline distribution")
println("")
println("Examples:")
println(" coral repo list")
println(" coral repo add https://repo.zygaena.org/packages")
println(" coral repo init /var/www/repo/myrepo")
println(" coral repo rebuild /var/www/repo/myrepo")
println(" coral repo sign /var/www/repo/myrepo maintainer")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: search.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Search command - search for packages by name or description
******************************************************************************/
module commands.search
import sys.args
import core.str
import core.port
import core.portindex
import core.database
import types
import util.color
import exitcodes as ec
export
fn execute(): int
end export
fn execute(): int
let argc = args.count()
if argc < 3
print_usage()
return ec.EXIT_USAGE()
end if
let search_term = args.get(2)
color.print_action("Searching for: " + search_term)
println("")
mut total = 0
// Try ports index first (fast path)
if portindex.port_index_exists()
mut results: [portindex.PortIndexEntry] = new [portindex.PortIndexEntry](512)
let result_count = portindex.search_ports(search_term, results, 512)
mut i = 0
while i < result_count
let entry = results[i]
print_index_match(entry)
total = total + 1
i = i + 1
end while
else
// Fall back to filesystem scan
mut cats: [string] = new [string](32)
let cat_count = port.get_categories(cats, 32)
mut i = 0
while i < cat_count
let category = cats[i]
mut ports: [string] = new [string](256)
let port_count = port.list_category(category, ports, 256)
mut j = 0
while j < port_count
let port_name = ports[j]
let result = port.find(port_name)
if result.success
let p = result.port
// Check if search term matches name or description
if matches_search(p, search_term)
print_match(p, category)
total = total + 1
end if
end if
j = j + 1
end while
i = i + 1
end while
end if
if total == 0
color.print_info("No packages found matching: " + search_term)
else
println("")
color.print_info("Found " + int_to_str(total) + " package(s)")
end if
return ec.EXIT_SUCCESS()
end execute
fn matches_search(p: types.Port, term: string): bool
let lower_term = str.to_lower(term)
let lower_name = str.to_lower(p.info.name)
let lower_desc = str.to_lower(p.info.description)
// Check name
if str.contains(lower_name, lower_term)
return true
end if
// Check description
if str.contains(lower_desc, lower_term)
return true
end if
return false
end matches_search
proc print_index_match(entry: portindex.PortIndexEntry)
let is_installed = database.is_installed(entry.name)
print(entry.category)
print("/")
print(entry.name)
print(" ")
print(entry.version)
if is_installed
print(" [installed]")
end if
println("")
print(" ")
println(entry.description)
end print_index_match
proc print_match(p: types.Port, category: string)
// Check if installed
let is_installed = database.is_installed(p.info.name)
print(category)
print("/")
print(p.info.name)
print(" ")
print(p.info.version)
if is_installed
print(" [installed]")
end if
println("")
print(" ")
println(p.info.description)
end print_match
proc print_usage()
println("Usage: coral search <term>")
println("")
println("Search for packages by name or description.")
println("")
println("Arguments:")
println(" <term> Search term to look for")
println("")
println("Examples:")
println(" coral search vim")
println(" coral search editor")
println(" coral search hello")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: sync.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Sync command - update ports collection from repository
******************************************************************************/
module commands.sync
import sys.args
import sys.process
import io.dir
import io.path
import io.file
import core.str
import core.config
import core.port
import core.portindex
import util.color
import exitcodes as ec
import core.result as res
export
fn execute(): int
end export
fn execute(): int
// Load configuration
let cfg = config.load()
let ports_dir = config.get_ports_dir(cfg)
color.print_action("Syncing ports collection...")
println("")
// Check if ports directory exists
if not dir.dir_exists(ports_dir)
color.print_error("Ports directory does not exist: " + ports_dir)
color.print_info("You may need to clone the ports repository first:")
println(" git clone <ports-repo-url> " + ports_dir)
return ec.EXIT_CONFIG_ERROR()
end if
// Check if it's a git repository
let git_dir = path.join_path(ports_dir, ".git")
if not dir.dir_exists(git_dir)
color.print_warning("Ports directory is not a git repository")
color.print_info("Cannot sync - no version control detected")
return ec.EXIT_CONFIG_ERROR()
end if
// Run git pull
color.print_info("Updating from remote repository...")
let cmd = "cd \"" + ports_dir + "\" && git pull"
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to start git pull")
return ec.EXIT_REPO_UNREACHABLE()
end if
let exit_code = process.process_wait(pid)
if exit_code == 0
color.print_success("Ports collection updated successfully")
// Rebuild ports index after successful sync
portindex.rebuild_port_index()
// Show summary of changes
show_update_summary(ports_dir)
return ec.EXIT_SUCCESS()
else
color.print_error("Git pull failed with exit code " + int_to_str(exit_code))
color.print_info("Check your network connection and repository access")
return ec.EXIT_REPO_UNREACHABLE()
end if
end execute
proc show_update_summary(ports_dir: string)
// Count ports in each category (dynamically discovered)
mut cats: [string] = new [string](32)
let cat_count = port.get_categories(cats, 32)
mut total = 0
mut i = 0
while i < cat_count
let cat = cats[i]
let cat_path = path.join_path(ports_dir, cat)
if dir.dir_exists(cat_path)
let entries = res.unwrap_or(dir.list_dir(cat_path), new [string](0))
let count = entries.length()
// Count valid ports (directories with package.toml)
mut port_count = 0
mut j = 0
while j < count
let entry = entries[j]
if str.length(entry) > 0 and entry[0] != '.'
let toml_path = path.join_path(path.join_path(cat_path, entry), "package.toml")
if file.fileExists(toml_path)
port_count = port_count + 1
end if
end if
j = j + 1
end while
if port_count > 0
println(" " + cat + ": " + int_to_str(port_count) + " ports")
total = total + port_count
end if
end if
i = i + 1
end while
println("")
color.print_info("Total: " + int_to_str(total) + " ports available")
end show_update_summary
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: upgrade.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Upgrade command - upgrade installed packages
******************************************************************************/
module commands.upgrade
import sys.args
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import core.port
import core.portindex
import core.package
import types
import util.color
import util.version as ver
import exitcodes as ec
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
// Auto-refresh port index if configured
if config.get_auto_refresh(cfg)
portindex.rebuild_port_index()
end if
// Show root if set (verbose mode)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
// Count non-flag arguments (package names)
// Skip flag values (--root, --prefix take a value)
mut pkg_count = 0
mut i = opts.cmd_index + 1
while i < argc
let arg = args.get(i)
if arg == "--root" or arg == "--prefix"
i = i + 2 // Skip flag and its value
continue
elif arg == "--no-chroot-scripts"
i = i + 1 // valueless flag: skip only itself
continue
end if
if not str.starts_with(arg, "-")
pkg_count = pkg_count + 1
end if
i = i + 1
end while
if pkg_count == 0
// No packages specified - upgrade all
return upgrade_all(cfg)
else
// Upgrade specified packages
mut all_success = true
i = opts.cmd_index + 1
while i < argc
let pkg_name = args.get(i)
// Skip flags and their values
if pkg_name == "--root" or pkg_name == "--prefix"
i = i + 2 // Skip flag and its value
continue
elif pkg_name == "--no-chroot-scripts"
i = i + 1 // valueless flag: skip only itself
continue
end if
if str.starts_with(pkg_name, "-")
i = i + 1
continue
end if
// Upgrade this package
if not upgrade_package(pkg_name, cfg)
color.print_error("Failed to upgrade: " + pkg_name)
all_success = false
end if
i = i + 1
end while
if all_success
return ec.EXIT_SUCCESS()
else
return ec.EXIT_UPGRADE_FAILED()
end if
end if
end execute
fn upgrade_all(cfg: config.Config): int
color.print_action("Checking for upgrades...")
// Get root path for rooted operations
let root_path = config.get_root(cfg)
// List all installed packages (use rooted version if root is set)
mut installed: [string] = new [string](512)
let installed_count = list_installed_pkgs(installed, 512, root_path)
if installed_count == 0
color.print_info("No packages installed")
return ec.EXIT_SUCCESS()
end if
// Check each package for updates
mut upgradable: [string] = new [string](512)
mut upgradable_count = 0
mut i = 0
while i < installed_count
let pkg_name = installed[i]
if has_upgrade(pkg_name, root_path)
upgradable[upgradable_count] = pkg_name
upgradable_count = upgradable_count + 1
end if
i = i + 1
end while
if upgradable_count == 0
color.print_success("All packages are up to date")
return ec.EXIT_SUCCESS()
end if
color.print_info("Packages to upgrade: " + int_to_str(upgradable_count))
// List packages to upgrade
i = 0
while i < upgradable_count
let pkg_name = upgradable[i]
let installed_pkg = get_installed_pkg(pkg_name, root_path)
let port_result = port.find(pkg_name)
if port_result.success
let p = port_result.port
println(" " + pkg_name + " " + installed_pkg.info.version + " -> " + p.info.version)
end if
i = i + 1
end while
// Ask for confirmation unless -y flag
if not args.has_flag("y") and not args.has_flag("yes")
color.print_info("Use -y flag to skip confirmation and proceed with upgrade")
return ec.EXIT_CANCELLED()
end if
// Dry-run: show what would be done and exit
if args.has_flag("n") or args.has_flag("dry-run")
color.print_info("Dry run — no changes made")
return ec.EXIT_SUCCESS()
end if
// Perform upgrades
mut all_success = true
i = 0
while i < upgradable_count
if not upgrade_package(upgradable[i], cfg)
color.print_error("Failed to upgrade: " + upgradable[i])
all_success = false
end if
i = i + 1
end while
if all_success
return ec.EXIT_SUCCESS()
else
return ec.EXIT_UPGRADE_FAILED()
end if
end upgrade_all
fn has_upgrade(pkg_name: string, root_path: string): bool
// Get installed version (use rooted version if root is set)
let installed_pkg = get_installed_pkg(pkg_name, root_path)
if str.length(installed_pkg.info.name) == 0
return false
end if
// Find port
let port_result = port.find(pkg_name)
if not port_result.success
return false
end if
let p = port_result.port
// Compare versions using semantic versioning
return ver.compare_versions(installed_pkg.info.version, p.info.version) < 0
end has_upgrade
// Helper functions for rooted operations
fn list_installed_pkgs(names: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.list_installed_rooted(names, max_count, root_path)
end if
return database.list_installed(names, max_count)
end list_installed_pkgs
fn get_installed_pkg(name: string, root_path: string): types.InstalledPackage
if str.length(root_path) > 0
return database.get_installed_rooted(name, root_path)
end if
return database.get_installed(name)
end get_installed_pkg
fn is_installed_pkg(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end is_installed_pkg
fn get_files_list(name: string, files: [string], max_count: int, root_path: string): int
if str.length(root_path) > 0
return database.get_files_rooted(name, files, max_count, root_path)
end if
return database.get_files(name, files, max_count)
end get_files_list
fn unregister_pkg(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.unregister_package_rooted(name, root_path)
end if
return database.unregister_package(name)
end unregister_pkg
fn register_pkg(pkg: types.InstalledPackage, root_path: string): bool
if str.length(root_path) > 0
return database.register_from_extract_dir_rooted(pkg, "", root_path)
end if
return database.register_package(pkg)
end register_pkg
fn get_actual_root(root_path: string): string
if str.length(root_path) == 0
return "/"
end if
return root_path
end get_actual_root
fn upgrade_package(pkg_name: string, cfg: config.Config): bool
// Get root path for rooted operations
let root_path = config.get_root(cfg)
// Check if installed (use rooted version if root is set)
if not is_installed_pkg(pkg_name, root_path)
color.print_error(pkg_name + " is not installed")
return false
end if
// Get installed info (use rooted version if root is set)
let installed_pkg = get_installed_pkg(pkg_name, root_path)
// Find port
let port_result = port.find(pkg_name)
if not port_result.success
color.print_error("Port not found: " + pkg_name)
return false
end if
let p = port_result.port
// Check if upgrade is available using semantic versioning
let cmp = ver.compare_versions(installed_pkg.info.version, p.info.version)
if cmp >= 0
color.print_info(pkg_name + " is already at version " + installed_pkg.info.version)
return true
end if
color.print_action("Upgrading " + pkg_name + " from " + installed_pkg.info.version + " to " + p.info.version + "...")
// Look for pre-built package
let pkg_path = find_package(pkg_name, p.info.version, p.info.release, cfg)
if str.length(pkg_path) == 0
color.print_error("Package not found. Build it first with: coral build")
return false
end if
// Remove old version (keep database entry for now)
mut files: [string] = new [string](4096)
let file_count = get_files_list(pkg_name, files, 4096, root_path)
color.print_info("Removing old files...")
let actual_root = get_actual_root(root_path)
remove_files(files, file_count, actual_root)
// Install new version
color.print_info("Installing new version...")
// Create extraction directory
let extract_dir = create_extract_dir(cfg)
if str.length(extract_dir) == 0
color.print_error("Failed to create extraction directory")
return false
end if
// Extract package
let result = package.extract_package(pkg_path, extract_dir)
if not result.success
color.print_error(result.error)
cleanup_extract_dir(extract_dir)
return false
end if
// Read new file list
mut new_files: [string] = new [string](4096)
let new_file_count = package.read_footprint(extract_dir, new_files, 4096)
// Install files to proper root
if not package.install_files(extract_dir, actual_root)
color.print_error("Failed to install files")
cleanup_extract_dir(extract_dir)
return false
end if
// Update database (remove and re-add) using rooted versions if needed
unregister_pkg(pkg_name, root_path)
let new_info = package.read_pkginfo(extract_dir)
mut new_pkg = types.new_installed_package()
new_pkg.info = new_info
new_pkg.install_date = "2025-01-24"
new_pkg.install_reason = "explicit"
new_pkg.files = new_files
new_pkg.files_count = new_file_count
// Register using rooted version if root is set
if str.length(root_path) > 0
if not database.register_from_extract_dir_rooted(new_pkg, extract_dir, root_path)
color.print_warning("Failed to update database")
end if
else
if not database.register_from_extract_dir(new_pkg, extract_dir)
color.print_warning("Failed to update database")
end if
end if
// Cleanup
cleanup_extract_dir(extract_dir)
color.print_success("Upgraded " + pkg_name + " to " + p.info.version)
return true
end upgrade_package
// Find a package file by name and version
fn find_package(name: string, version: string, release: int, cfg: config.Config): string
let packages_dir = config.get_packages_dir(cfg)
let pkg_name = name + "-" + version + "-" + int_to_str(release) + ".pkg.tar.xz"
let pkg_path = path.join_path(packages_dir, pkg_name)
if file.fileExists(pkg_path)
return pkg_path
end if
return ""
end find_package
// Remove files from system
fn remove_files(files: [string], file_count: int, root_path: string): bool
mut i = file_count - 1
while i >= 0
let rel_path = files[i]
let full_path = path.join_path(root_path, rel_path)
if file.fileExists(full_path)
let cmd = "rm -f \"" + full_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
end if
i = i - 1
end while
return true
end remove_files
// Create extraction directory
fn create_extract_dir(cfg: config.Config): string
let work_dir = config.get_work_dir(cfg)
let pid = process.getpid()
let extract_dir = path.join_path(work_dir, "upgrade_" + int_to_str(pid))
if dir.dir_exists(extract_dir)
let cmd = "rm -rf \"" + extract_dir + "\""
let rm_pid = process.process_spawn_shell(cmd)
if rm_pid > 0
process.process_wait(rm_pid)
end if
end if
if not res.is_ok(dir.create_dir_all(extract_dir))
return ""
end if
return extract_dir
end create_extract_dir
// Cleanup extraction directory
fn cleanup_extract_dir(dir_path: string): bool
if str.length(dir_path) == 0
return true
end if
let cmd = "rm -rf \"" + dir_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
process.process_wait(pid)
return true
end cleanup_extract_dir
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: verify.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Verify command - check installed package integrity
******************************************************************************/
module commands.verify
import sys.args
import io.file
import io.dir
import io.path
import core.str
import core.config
import core.database
import util.mtree
import util.checksum
import types
import util.color
import exitcodes as ec
import fs.stat
import fs.link
import core.result as res
export
fn execute(opts: types.GlobalOptions): int
end export
fn execute(opts: types.GlobalOptions): int
let argc = args.count()
if argc <= opts.cmd_index + 1
print_usage()
return ec.EXIT_USAGE()
end if
// Load configuration and apply command-line overrides
let base_cfg = config.load()
let cfg = config.apply_overrides(base_cfg, opts.root, opts.prefix, opts.no_chroot)
let root_path = config.get_root(cfg)
if opts.verbose and str.length(root_path) > 0
color.print_info("Using root: " + root_path)
end if
let pkg_name = args.get(opts.cmd_index + 1)
// Check if installed
if not check_installed(pkg_name, root_path)
color.print_error(pkg_name + " is not installed")
return ec.EXIT_PKG_NOT_FOUND()
end if
color.print_action("Verifying " + pkg_name + "...")
// Load manifest from database
let manifest_path = database.get_manifest_path(pkg_name)
if not file.fileExists(manifest_path)
color.print_error("No manifest found for " + pkg_name + " (legacy package without .MANIFEST)")
return ec.EXIT_PKG_INVALID()
end if
let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
if str.length(manifest_content) == 0
color.print_error("Empty manifest for " + pkg_name)
return ec.EXIT_PKG_INVALID()
end if
mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
let entry_count = mtree.parse_manifest(manifest_content, entries, 8192)
if entry_count == 0
color.print_error("Failed to parse manifest for " + pkg_name)
return ec.EXIT_PKG_INVALID()
end if
// Determine actual root
let actual_root = get_actual_root(root_path)
// Verify each entry
mut missing_count = 0
mut checksum_fail_count = 0
mut mode_fail_count = 0
mut link_fail_count = 0
mut ok_count = 0
mut i = 0
while i < entry_count
let entry = entries[i]
let etype = mtree.entry_type(entry)
let epath = mtree.entry_path(entry)
mut rel_path = epath
if str.starts_with(epath, "./")
rel_path = str.substring(epath, 2, str.length(epath) - 2)
end if
let full_path = path.join_path(actual_root, rel_path)
if str.equals(etype, "dir")
if not dir.dir_exists(full_path)
color.print_warning("MISSING dir: " + rel_path)
missing_count = missing_count + 1
else
// Check mode
let expected_mode = mtree.entry_mode(entry)
let actual_mode = res.unwrap_or(stat.file_mode(full_path), 0)
// Compare lower 12 bits (permissions + setuid/setgid/sticky)
if (actual_mode % 4096) != (expected_mode % 4096)
if opts.verbose
color.print_warning("MODE " + rel_path + " (expected " + int_to_octal(expected_mode) + ", got " + int_to_octal(actual_mode) + ")")
else
color.print_warning("MODE " + rel_path)
end if
mode_fail_count = mode_fail_count + 1
else
ok_count = ok_count + 1
end if
end if
elif str.equals(etype, "file")
if not stat.exists(full_path)
color.print_warning("MISSING file: " + rel_path)
missing_count = missing_count + 1
else
mut file_ok = true
// Check sha256
let expected_sha = mtree.entry_sha256(entry)
if str.length(expected_sha) > 0
let actual_sha = checksum.sha256_file(full_path)
if not str.equals(actual_sha, expected_sha)
color.print_warning("CHECKSUM " + rel_path)
checksum_fail_count = checksum_fail_count + 1
file_ok = false
end if
end if
// Check mode
let expected_mode = mtree.entry_mode(entry)
let actual_mode = res.unwrap_or(stat.file_mode(full_path), 0)
if (actual_mode % 4096) != (expected_mode % 4096)
if opts.verbose
color.print_warning("MODE " + rel_path + " (expected " + int_to_octal(expected_mode) + ", got " + int_to_octal(actual_mode) + ")")
else
color.print_warning("MODE " + rel_path)
end if
mode_fail_count = mode_fail_count + 1
file_ok = false
end if
// Check ownership
let expected_uid = mtree.name_to_uid(mtree.entry_uname(entry))
let expected_gid = mtree.name_to_gid(mtree.entry_gname(entry))
let actual_uid = res.unwrap_or(stat.file_uid(full_path), 0)
let actual_gid = res.unwrap_or(stat.file_gid(full_path), 0)
if actual_uid != expected_uid or actual_gid != expected_gid
if opts.verbose
color.print_warning("OWNER " + rel_path + " (expected " + mtree.entry_uname(entry) + ":" + mtree.entry_gname(entry) + ")")
else
color.print_warning("OWNER " + rel_path)
end if
mode_fail_count = mode_fail_count + 1
file_ok = false
end if
if file_ok
ok_count = ok_count + 1
end if
end if
elif str.equals(etype, "link")
if not stat.is_symlink(full_path)
if not stat.exists(full_path)
color.print_warning("MISSING link: " + rel_path)
missing_count = missing_count + 1
else
color.print_warning("NOT A LINK " + rel_path)
link_fail_count = link_fail_count + 1
end if
else
let expected_target = mtree.entry_link(entry)
let actual_target = res.unwrap_or(link.readlink(full_path), "")
if not str.equals(actual_target, expected_target)
if opts.verbose
color.print_warning("LINK " + rel_path + " -> " + actual_target + " (expected " + expected_target + ")")
else
color.print_warning("LINK TARGET " + rel_path)
end if
link_fail_count = link_fail_count + 1
else
ok_count = ok_count + 1
end if
end if
end if
i = i + 1
end while
// Summary
println("")
let total_issues = missing_count + checksum_fail_count + mode_fail_count + link_fail_count
if total_issues == 0
color.print_success(pkg_name + ": " + int_to_str(ok_count) + " entries verified, all OK")
return ec.EXIT_SUCCESS()
else
color.print_error(pkg_name + ": " + int_to_str(total_issues) + " issue(s) found")
if missing_count > 0
println(" Missing: " + int_to_str(missing_count))
end if
if checksum_fail_count > 0
println(" Checksum: " + int_to_str(checksum_fail_count))
end if
if mode_fail_count > 0
println(" Mode/Owner: " + int_to_str(mode_fail_count))
end if
if link_fail_count > 0
println(" Symlinks: " + int_to_str(link_fail_count))
end if
println(" OK: " + int_to_str(ok_count))
return ec.EXIT_PKG_CHECKSUM_MISMATCH()
end if
end execute
fn check_installed(name: string, root_path: string): bool
if str.length(root_path) > 0
return database.is_installed_rooted(name, root_path)
end if
return database.is_installed(name)
end check_installed
fn get_actual_root(root_path: string): string
if str.length(root_path) == 0
return "/"
end if
return root_path
end get_actual_root
proc print_usage()
println("Usage: coral verify <package>")
println("")
println("Verify integrity of an installed package against its manifest.")
println("")
println("Checks:")
println(" - Missing files, directories, and symlinks")
println(" - File checksum (sha256) mismatches")
println(" - Permission and ownership changes")
println(" - Broken or incorrect symlink targets")
println("")
println("Arguments:")
println(" <package> Name of installed package to verify")
println("")
println("Options:")
println(" -v, --verbose Show expected vs actual values for failures")
println("")
println("Examples:")
println(" coral verify vim")
println(" coral verify -v openssl")
end print_usage
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
// Helper: convert int to octal string (for mode display)
fn int_to_octal(n: int): string
if n == 0
return "0"
end if
mut value = n % 4096
mut result = ""
while value > 0
let digit = value % 8
result = str.concat(str.substring("01234567", digit, 1), result)
value = value / 8
end while
return result
end int_to_octal
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: config.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Configuration file loading and access
******************************************************************************/
module core.config
import types
import io.file
import core.str
import encoding.toml
import core.result as res
export
// Configuration structure
type Config
// Load configuration from file (with defaults if not found)
fn load(): Config
// Access functions for common settings
fn get_arch(cfg: Config): string
fn get_jobs(cfg: Config): int
fn get_confirm(cfg: Config): bool
fn get_color(cfg: Config): bool
// Path accessors
fn get_ports_dir(cfg: Config): string
fn get_packages_dir(cfg: Config): string
fn get_sources_dir(cfg: Config): string
fn get_database_dir(cfg: Config): string
fn get_build_dir(cfg: Config): string
fn get_index_dir(cfg: Config): string
// Legacy (for compatibility)
fn get_work_dir(cfg: Config): string
fn get_pkg_dir(cfg: Config): string
// Root and prefix accessors
fn get_root(cfg: Config): string
fn get_prefix(cfg: Config): string
fn get_sysconfdir(cfg: Config): string
// Root-aware path accessors (prepend root to path)
fn get_database_dir_rooted(cfg: Config): string
fn get_install_prefix(cfg: Config): string
// Apply command-line overrides to config
fn apply_overrides(cfg: Config, root: string, prefix: string, no_chroot: bool): Config
// Build settings
fn get_cflags(cfg: Config): string
fn get_cxxflags(cfg: Config): string
fn get_makeflags(cfg: Config): string
fn get_strip(cfg: Config): bool
fn get_fallback_to_source(cfg: Config): bool
fn get_compress_man(cfg: Config): bool
fn get_clean_work(cfg: Config): bool
fn get_clean_pkg(cfg: Config): bool
fn get_logging(cfg: Config): bool
fn get_quiet(cfg: Config): bool
// Network settings
fn get_timeout(cfg: Config): int
fn get_retries(cfg: Config): int
fn get_use_proxy(cfg: Config): bool
// Sync settings
fn get_auto_refresh(cfg: Config): bool
// Cache settings
fn get_keep_packages(cfg: Config): bool
fn get_keep_sources(cfg: Config): bool
// Security settings
fn get_require_signed_repos(cfg: Config): bool
fn get_require_signed_packages(cfg: Config): bool
// Install settings
fn get_chroot_scripts(cfg: Config): bool
end export
// Configuration structure
type Config = struct
// [general]
arch: string
jobs: int
confirm: bool
color: bool
// [paths]
root: string
prefix: string
sysconfdir: string
ports_dir: string
packages_dir: string
sources_dir: string
database_dir: string
build_dir: string
index_dir: string
// Legacy (kept for compatibility)
work_dir: string
pkg_dir: string
// [build]
cflags: string
cxxflags: string
makeflags: string
strip: bool
compress_man: bool
fallback_to_source: bool
clean_work: bool
clean_pkg: bool
logging: bool
quiet: bool
// [network]
timeout: int
retries: int
use_proxy: bool
// [sync]
auto_refresh: bool
// [cache]
keep_packages: bool
keep_sources: bool
// [security]
require_signed_repos: bool
require_signed_packages: bool
// [install]
chroot_scripts: bool
end Config
// Create a default configuration
fn default_config(): Config
return Config{
// General
arch: "amd64",
jobs: 0, // 0 = auto-detect
confirm: true,
color: true,
// Paths (defaults from types)
root: "",
prefix: "/usr/local",
sysconfdir: "/etc",
ports_dir: types.get_ports_dir(),
packages_dir: types.get_packages_dir(),
sources_dir: types.get_sources_dir(),
database_dir: types.get_db_dir(),
build_dir: types.get_build_dir(),
index_dir: types.get_index_dir(),
// Legacy (for compatibility)
work_dir: types.get_build_dir(),
pkg_dir: types.get_build_dir(),
// Build
cflags: "-O2 -pipe",
cxxflags: "-O2 -pipe",
makeflags: "",
strip: true,
compress_man: true,
fallback_to_source: true,
clean_work: true,
clean_pkg: true,
logging: true,
quiet: false,
// Network
timeout: 30,
retries: 3,
use_proxy: false,
// Sync
auto_refresh: false,
// Cache
keep_packages: true,
keep_sources: true,
// Security
require_signed_repos: false,
require_signed_packages: false,
// Install
chroot_scripts: true
}
end default_config
// Load configuration from file
fn load(): Config
mut cfg = default_config()
// Check if config file exists
if not file.fileExists(types.get_config_file())
return cfg
end if
// Read config file
let content = res.unwrap_or(file.readFile(types.get_config_file()), "")
if str.length(content) == 0
return cfg
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return cfg
end if
// [general] section
if toml.toml_has_key(keys, vals, entry_count, "general.arch")
cfg.arch = toml.toml_get(keys, vals, entry_count, "general.arch")
end if
if toml.toml_has_key(keys, vals, entry_count, "general.jobs")
cfg.jobs = toml.toml_get_int(keys, vals, entry_count, "general.jobs")
end if
if toml.toml_has_key(keys, vals, entry_count, "general.confirm")
cfg.confirm = toml.toml_get_bool(keys, vals, entry_count, "general.confirm")
end if
if toml.toml_has_key(keys, vals, entry_count, "general.color")
cfg.color = toml.toml_get_bool(keys, vals, entry_count, "general.color")
end if
// [paths] section
if toml.toml_has_key(keys, vals, entry_count, "paths.root")
cfg.root = toml.toml_get(keys, vals, entry_count, "paths.root")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.prefix")
cfg.prefix = toml.toml_get(keys, vals, entry_count, "paths.prefix")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.sysconfdir")
cfg.sysconfdir = toml.toml_get(keys, vals, entry_count, "paths.sysconfdir")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.ports")
cfg.ports_dir = toml.toml_get(keys, vals, entry_count, "paths.ports")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.packages")
cfg.packages_dir = toml.toml_get(keys, vals, entry_count, "paths.packages")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.sources")
cfg.sources_dir = toml.toml_get(keys, vals, entry_count, "paths.sources")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.database")
cfg.database_dir = toml.toml_get(keys, vals, entry_count, "paths.database")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.build")
cfg.build_dir = toml.toml_get(keys, vals, entry_count, "paths.build")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.index")
cfg.index_dir = toml.toml_get(keys, vals, entry_count, "paths.index")
end if
// Legacy path support (maps to build_dir)
if toml.toml_has_key(keys, vals, entry_count, "paths.work")
cfg.work_dir = toml.toml_get(keys, vals, entry_count, "paths.work")
cfg.build_dir = cfg.work_dir // Also set new field
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.pkg")
cfg.pkg_dir = toml.toml_get(keys, vals, entry_count, "paths.pkg")
end if
// [build] section
if toml.toml_has_key(keys, vals, entry_count, "build.cflags")
cfg.cflags = toml.toml_get(keys, vals, entry_count, "build.cflags")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.cxxflags")
cfg.cxxflags = toml.toml_get(keys, vals, entry_count, "build.cxxflags")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.makeflags")
cfg.makeflags = toml.toml_get(keys, vals, entry_count, "build.makeflags")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.strip")
cfg.strip = toml.toml_get_bool(keys, vals, entry_count, "build.strip")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.compress_man")
cfg.compress_man = toml.toml_get_bool(keys, vals, entry_count, "build.compress_man")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.fallback_to_source")
cfg.fallback_to_source = toml.toml_get_bool(keys, vals, entry_count, "build.fallback_to_source")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.clean_work")
cfg.clean_work = toml.toml_get_bool(keys, vals, entry_count, "build.clean_work")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.clean_pkg")
cfg.clean_pkg = toml.toml_get_bool(keys, vals, entry_count, "build.clean_pkg")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.logging")
cfg.logging = toml.toml_get_bool(keys, vals, entry_count, "build.logging")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.quiet")
cfg.quiet = toml.toml_get_bool(keys, vals, entry_count, "build.quiet")
end if
// [network] section
if toml.toml_has_key(keys, vals, entry_count, "network.timeout")
cfg.timeout = toml.toml_get_int(keys, vals, entry_count, "network.timeout")
end if
if toml.toml_has_key(keys, vals, entry_count, "network.retries")
cfg.retries = toml.toml_get_int(keys, vals, entry_count, "network.retries")
end if
if toml.toml_has_key(keys, vals, entry_count, "network.use_proxy")
cfg.use_proxy = toml.toml_get_bool(keys, vals, entry_count, "network.use_proxy")
end if
// [sync] section
if toml.toml_has_key(keys, vals, entry_count, "sync.auto_refresh")
cfg.auto_refresh = toml.toml_get_bool(keys, vals, entry_count, "sync.auto_refresh")
end if
// [cache] section
if toml.toml_has_key(keys, vals, entry_count, "cache.keep_packages")
cfg.keep_packages = toml.toml_get_bool(keys, vals, entry_count, "cache.keep_packages")
end if
if toml.toml_has_key(keys, vals, entry_count, "cache.keep_sources")
cfg.keep_sources = toml.toml_get_bool(keys, vals, entry_count, "cache.keep_sources")
end if
// [security] section
if toml.toml_has_key(keys, vals, entry_count, "security.require_signed_repos")
cfg.require_signed_repos = toml.toml_get_bool(keys, vals, entry_count, "security.require_signed_repos")
end if
if toml.toml_has_key(keys, vals, entry_count, "security.require_signed_packages")
cfg.require_signed_packages = toml.toml_get_bool(keys, vals, entry_count, "security.require_signed_packages")
end if
// [install] section
if toml.toml_has_key(keys, vals, entry_count, "install.chroot_scripts")
cfg.chroot_scripts = toml.toml_get_bool(keys, vals, entry_count, "install.chroot_scripts")
end if
return cfg
end load
// Accessor functions
fn get_arch(cfg: Config): string
return cfg.arch
end get_arch
fn get_jobs(cfg: Config): int
return cfg.jobs
end get_jobs
fn get_confirm(cfg: Config): bool
return cfg.confirm
end get_confirm
fn get_color(cfg: Config): bool
return cfg.color
end get_color
fn get_ports_dir(cfg: Config): string
return cfg.ports_dir
end get_ports_dir
fn get_packages_dir(cfg: Config): string
return cfg.packages_dir
end get_packages_dir
fn get_sources_dir(cfg: Config): string
return cfg.sources_dir
end get_sources_dir
fn get_database_dir(cfg: Config): string
return cfg.database_dir
end get_database_dir
fn get_build_dir(cfg: Config): string
return cfg.build_dir
end get_build_dir
fn get_index_dir(cfg: Config): string
return cfg.index_dir
end get_index_dir
// Legacy accessors (for compatibility)
fn get_work_dir(cfg: Config): string
return cfg.build_dir
end get_work_dir
fn get_pkg_dir(cfg: Config): string
return cfg.build_dir
end get_pkg_dir
fn get_cflags(cfg: Config): string
return cfg.cflags
end get_cflags
fn get_cxxflags(cfg: Config): string
return cfg.cxxflags
end get_cxxflags
fn get_makeflags(cfg: Config): string
return cfg.makeflags
end get_makeflags
fn get_strip(cfg: Config): bool
return cfg.strip
end get_strip
fn get_fallback_to_source(cfg: Config): bool
return cfg.fallback_to_source
end get_fallback_to_source
fn get_compress_man(cfg: Config): bool
return cfg.compress_man
end get_compress_man
fn get_clean_work(cfg: Config): bool
return cfg.clean_work
end get_clean_work
fn get_clean_pkg(cfg: Config): bool
return cfg.clean_pkg
end get_clean_pkg
fn get_logging(cfg: Config): bool
return cfg.logging
end get_logging
fn get_quiet(cfg: Config): bool
return cfg.quiet
end get_quiet
fn get_timeout(cfg: Config): int
return cfg.timeout
end get_timeout
fn get_retries(cfg: Config): int
return cfg.retries
end get_retries
fn get_use_proxy(cfg: Config): bool
return cfg.use_proxy
end get_use_proxy
fn get_auto_refresh(cfg: Config): bool
return cfg.auto_refresh
end get_auto_refresh
fn get_keep_packages(cfg: Config): bool
return cfg.keep_packages
end get_keep_packages
fn get_keep_sources(cfg: Config): bool
return cfg.keep_sources
end get_keep_sources
fn get_require_signed_repos(cfg: Config): bool
return cfg.require_signed_repos
end get_require_signed_repos
fn get_require_signed_packages(cfg: Config): bool
return cfg.require_signed_packages
end get_require_signed_packages
fn get_chroot_scripts(cfg: Config): bool
return cfg.chroot_scripts
end get_chroot_scripts
// Get the alternate root path (empty string means /)
fn get_root(cfg: Config): string
return cfg.root
end get_root
// Get the installation prefix (default /usr/local)
fn get_prefix(cfg: Config): string
return cfg.prefix
end get_prefix
// Get the system configuration directory (default /etc)
fn get_sysconfdir(cfg: Config): string
return cfg.sysconfdir
end get_sysconfdir
// Get database directory with root prepended
fn get_database_dir_rooted(cfg: Config): string
if str.length(cfg.root) == 0
return cfg.database_dir
end if
return cfg.root + cfg.database_dir
end get_database_dir_rooted
// Get the full install prefix (root + prefix)
// This is where package files should be installed
fn get_install_prefix(cfg: Config): string
if str.length(cfg.root) == 0
return cfg.prefix
end if
return cfg.root + cfg.prefix
end get_install_prefix
// Apply command-line overrides to config
// Call this after loading config to override with --root and --prefix flags
fn apply_overrides(cfg: Config, root: string, prefix: string, no_chroot: bool): Config
mut result = cfg
if str.length(root) > 0
result.root = root
end if
if str.length(prefix) > 0
result.prefix = prefix
end if
if no_chroot
result.chroot_scripts = false
end if
return result
end apply_overrides
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: database.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Installed package database management
******************************************************************************/
module core.database
import types
import io.file
import io.dir
import io.path
import core.str
import encoding.toml
import util.mtree
import sys.process
import core.result as res
export
// Check if a package is installed
fn is_installed(name: string): bool
// List all installed packages (returns count, fills names array)
fn list_installed(names: [string], max_count: int): int
// Get installed package details
fn get_installed(name: string): types.InstalledPackage
// Register a new installed package
fn register_package(pkg: types.InstalledPackage): bool
// Register package with file list copied from extract dir (more efficient)
fn register_from_extract_dir(pkg: types.InstalledPackage, extract_dir: string): bool
// Unregister (remove) a package from database
fn unregister_package(name: string): bool
// Get list of files owned by a package (returns count, fills files array)
fn get_files(name: string, files: [string], max_count: int): int
// Find which package owns a given file path
fn find_owner(file_path: string): string
// Find which package provides an alternative
fn find_provider(alternative: string): string
// Ensure database directories exist
fn init_db(): bool
// Scripts support
fn get_scripts_dir(name: string): string
fn store_scripts(name: string, extract_dir: string): bool
fn has_stored_scripts(name: string): bool
// Config files support
fn store_config_files(name: string, extract_dir: string): bool
fn get_config_files(name: string, config_files: [string], max_count: int): int
// Manifest support
fn get_manifest_path(name: string): string
// Root-aware versions for alternate root installation
fn init_db_rooted(root: string): bool
fn register_from_extract_dir_rooted(pkg: types.InstalledPackage, extract_dir: string, root: string): bool
fn store_scripts_rooted(name: string, extract_dir: string, root: string): bool
fn store_config_files_rooted(name: string, extract_dir: string, root: string): bool
fn is_installed_rooted(name: string, root: string): bool
fn list_installed_rooted(names: [string], max_count: int, root: string): int
fn get_installed_rooted(name: string, root: string): types.InstalledPackage
fn get_files_rooted(name: string, files: [string], max_count: int, root: string): int
fn find_owner_rooted(file_path: string, root: string): string
fn unregister_package_rooted(name: string, root: string): bool
end export
// Get the package database directory for a specific package
fn pkg_db_dir(name: string): string
return path.join_path(types.get_db_dir(), name)
end pkg_db_dir
// Get the pkg.toml path for a package
fn pkg_toml_path(name: string): string
return path.join_path(pkg_db_dir(name), "pkg.toml")
end pkg_toml_path
// Get the files.txt path for a package
fn pkg_files_path(name: string): string
return path.join_path(pkg_db_dir(name), "files.txt")
end pkg_files_path
// Get the manifest.mtree path for a package
fn get_manifest_path(name: string): string
return path.join_path(pkg_db_dir(name), "manifest.mtree")
end get_manifest_path
// Initialize the database directory structure
fn init_db(): bool
if not dir.dir_exists(types.get_db_dir())
return res.is_ok(dir.create_dir_all(types.get_db_dir()))
end if
return true
end init_db
// Check if a package is installed by looking for its database entry
fn is_installed(name: string): bool
let pkg_dir = pkg_db_dir(name)
if not dir.dir_exists(pkg_dir)
return false
end if
// Also verify pkg.toml exists
return file.fileExists(pkg_toml_path(name))
end is_installed
// List all installed packages by scanning the database directory
fn list_installed(names: [string], max_count: int): int
if not dir.dir_exists(types.get_db_dir())
return 0
end if
let entries = res.unwrap_or(dir.list_dir(types.get_db_dir()), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Skip hidden files
if str.length(entry) > 0 and entry[0] != '.'
// Verify it's a valid package (has pkg.toml)
let toml_path = pkg_toml_path(entry)
if file.fileExists(toml_path)
names[count] = entry
count = count + 1
end if
end if
i = i + 1
end while
return count
end list_installed
// Create an empty InstalledPackage
fn new_installed_package(): types.InstalledPackage
return types.new_installed_package()
end new_installed_package
// Get details of an installed package
fn get_installed(name: string): types.InstalledPackage
if not is_installed(name)
return new_installed_package()
end if
// Read pkg.toml
let toml_path = pkg_toml_path(name)
let content = res.unwrap_or(file.readFile(toml_path), "")
if str.length(content) == 0
return new_installed_package()
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return new_installed_package()
end if
// Build package info
mut pkg = new_installed_package()
pkg.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
pkg.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
pkg.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
pkg.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
pkg.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
pkg.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
pkg.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
pkg.info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")
// Install metadata
pkg.install_date = toml.toml_get(keys, vals, entry_count, "install.date")
pkg.install_reason = toml.toml_get(keys, vals, entry_count, "install.reason")
// Read files list
let files_path = pkg_files_path(name)
if file.fileExists(files_path)
let files_content = res.unwrap_or(file.readFile(files_path), "")
if str.length(files_content) > 0
let alloc_size = count_newlines(files_content) + 16
mut files_arr: [string] = new [string](alloc_size)
let files_count = str.split(files_content, '\n', files_arr, alloc_size)
// Filter out empty lines
mut valid_count = 0
mut j = 0
while j < files_count
if str.length(files_arr[j]) > 0
valid_count = valid_count + 1
end if
j = j + 1
end while
pkg.files = files_arr
pkg.files_count = valid_count
end if
end if
return pkg
end get_installed
// Generate TOML content for a package
fn generate_pkg_toml(pkg: types.InstalledPackage): string
mut content = "[package]\n"
content = content + "name = \"" + pkg.info.name + "\"\n"
content = content + "version = \"" + pkg.info.version + "\"\n"
content = content + "release = " + int_to_str(pkg.info.release) + "\n"
content = content + "description = \"" + pkg.info.description + "\"\n"
content = content + "url = \"" + pkg.info.url + "\"\n"
content = content + "license = \"" + pkg.info.license + "\"\n"
content = content + "maintainer = \"" + pkg.info.maintainer + "\"\n"
content = content + "arch = \"" + pkg.info.arch + "\"\n"
content = content + "\n"
content = content + "[install]\n"
content = content + "date = \"" + pkg.install_date + "\"\n"
content = content + "reason = \"" + pkg.install_reason + "\"\n"
return content
end generate_pkg_toml
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
// Register a newly installed package
fn register_package(pkg: types.InstalledPackage): bool
// Ensure database directory exists
if not init_db()
return false
end if
// Create package directory
let pkg_dir = pkg_db_dir(pkg.info.name)
if not dir.dir_exists(pkg_dir)
if not res.is_ok(dir.create_dir_all(pkg_dir))
return false
end if
end if
// Write pkg.toml
let toml_content = generate_pkg_toml(pkg)
let toml_path = pkg_toml_path(pkg.info.name)
if not res.is_ok(file.writeFile(toml_path, toml_content))
return false
end if
// Note: files.txt is written by register_from_extract_dir for performance
return true
end register_package
// Count newline characters in a string to estimate line count
fn count_newlines(s: string): int
let slen = str.length(s)
mut count = 0
mut i = 0
while i < slen
if s[i] == '\n'
count = count + 1
end if
i = i + 1
end while
return count
end count_newlines
// Process a .FOOTPRINT file content: filter and normalize paths
// Uses str.join() for O(n) single-allocation string building
fn process_footprint(content: string): string
let newline_count = count_newlines(content)
let alloc_size = newline_count + 16
mut lines: [string] = new [string](alloc_size)
let line_count = str.split(content, '\n', lines, alloc_size)
mut result_lines: [string] = new [string](alloc_size)
mut result_count = 0
mut i = 0
while i < line_count
mut line = str.trim_ws(lines[i])
if str.length(line) == 0
i = i + 1
continue
end if
// Strip leading ./
if str.starts_with(line, "./")
line = str.substring(line, 2, str.length(line) - 2)
end if
// Skip metadata files
if str.equals(line, ".PKGINFO") or str.equals(line, ".FOOTPRINT")
i = i + 1
continue
end if
if str.starts_with(line, ".SCRIPTS")
i = i + 1
continue
end if
if str.equals(line, ".CONFIG")
i = i + 1
continue
end if
// Skip directories (end with /)
let len = str.length(line)
if len > 0 and line[len - 1] == '/'
i = i + 1
continue
end if
result_lines[result_count] = line
result_count = result_count + 1
i = i + 1
end while
return str.join(result_lines, result_count, "\n")
end process_footprint
// Extract file paths from mtree manifest content for files.txt
// Parses manifest entries and returns a newline-joined list of relative paths
// (files and symlinks only, no directories, no metadata)
fn extract_paths_from_manifest(content: string): string
mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
let count = mtree.parse_manifest(content, entries, 8192)
mut result_lines: [string] = new [string](8192)
mut result_count = 0
mut i = 0
while i < count
let etype = mtree.entry_type(entries[i])
let epath = mtree.entry_path(entries[i])
// Only include files and symlinks (matches legacy files.txt behavior)
if str.equals(etype, "file") or str.equals(etype, "link")
// Strip leading ./
if str.starts_with(epath, "./")
result_lines[result_count] = str.substring(epath, 2, str.length(epath) - 2)
else
result_lines[result_count] = epath
end if
result_count = result_count + 1
end if
i = i + 1
end while
return str.join(result_lines, result_count, "\n")
end extract_paths_from_manifest
// Register package and copy files list from extracted package directory
fn register_from_extract_dir(pkg: types.InstalledPackage, extract_dir: string): bool
// Register the package metadata
if not register_package(pkg)
return false
end if
let files_path = pkg_files_path(pkg.info.name)
// Try .MANIFEST first (v2 format), fall back to .FOOTPRINT (legacy)
let manifest_path = path.join_path(extract_dir, ".MANIFEST")
if file.fileExists(manifest_path)
// Store the full manifest for future use (verify, manifest-based remove)
let manifest_store = path.join_path(pkg_db_dir(pkg.info.name), "manifest.mtree")
let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
file.writeFile(manifest_store, manifest_content)
// Also generate files.txt for backward compatibility
let result = extract_paths_from_manifest(manifest_content)
return res.is_ok(file.writeFile(files_path, result))
end if
// Legacy: .FOOTPRINT
let footprint_path = path.join_path(extract_dir, ".FOOTPRINT")
if not file.fileExists(footprint_path)
file.writeFile(files_path, "")
return true
end if
let content = res.unwrap_or(file.readFile(footprint_path), "")
if str.length(content) == 0
file.writeFile(files_path, "")
return true
end if
let result = process_footprint(content)
return res.is_ok(file.writeFile(files_path, result))
end register_from_extract_dir
// Helper to remove a file
fn remove_file(file_path: string): bool
let cmd = "rm -f \"" + file_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
return exit_code == 0
end remove_file
// Unregister a package from the database
fn unregister_package(name: string): bool
if not is_installed(name)
return true // Already not installed
end if
let pkg_dir = pkg_db_dir(name)
// Remove pkg.toml
let toml_path = pkg_toml_path(name)
if file.fileExists(toml_path)
if not remove_file(toml_path)
return false
end if
end if
// Remove files.txt
let files_path = pkg_files_path(name)
if file.fileExists(files_path)
if not remove_file(files_path)
return false
end if
end if
// Remove manifest.mtree
let manifest_path = get_manifest_path(name)
if file.fileExists(manifest_path)
remove_file(manifest_path)
end if
// Remove scripts directory if exists
let scripts_dir = get_scripts_dir(name)
if dir.dir_exists(scripts_dir)
let cmd = "rm -rf \"" + scripts_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
end if
// Remove config.txt if exists
let config_path = pkg_config_path(name)
if file.fileExists(config_path)
remove_file(config_path)
end if
// Remove the package directory
return res.is_ok(dir.remove_dir(pkg_dir))
end unregister_package
// Get list of files owned by a package
fn get_files(name: string, files: [string], max_count: int): int
if not is_installed(name)
return 0
end if
let files_path = pkg_files_path(name)
if not file.fileExists(files_path)
return 0
end if
let content = res.unwrap_or(file.readFile(files_path), "")
if str.length(content) == 0
return 0
end if
// Split by newlines — size dynamically
let alloc_size = count_newlines(content) + 16
mut all_lines: [string] = new [string](alloc_size)
let line_count = str.split(content, '\n', all_lines, alloc_size)
// Copy non-empty lines to output
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(all_lines[i])
if str.length(line) > 0
files[count] = line
count = count + 1
end if
i = i + 1
end while
return count
end get_files
// Find which package owns a given file
fn find_owner(file_path: string): string
// Normalize the path - strip leading "/" if present
mut search_path = file_path
if str.length(search_path) > 0 and search_path[0] == '/'
search_path = str.substring(search_path, 1, str.length(search_path) - 1)
end if
// Get list of all installed packages
mut packages: [string] = new [string](256)
let pkg_count = list_installed(packages, 256)
mut i = 0
while i < pkg_count
let pkg_name = packages[i]
// Get files for this package
mut files: [string] = new [string](4096)
let file_count = get_files(pkg_name, files, 4096)
// Search for matching file
mut j = 0
while j < file_count
if files[j] == search_path
return pkg_name
end if
j = j + 1
end while
i = i + 1
end while
return "" // No owner found
end find_owner
// Find which package provides an alternative
fn find_provider(alternative: string): string
// Get list of all installed packages
mut packages: [string] = new [string](256)
let pkg_count = list_installed(packages, 256)
mut i = 0
while i < pkg_count
let pkg_name = packages[i]
let pkg = get_installed(pkg_name)
// Check alternatives array
// Note: We'd need to parse the alternatives array from pkg.toml
// For now, check if this package provides the alternative
let toml_path = pkg_toml_path(pkg_name)
let content = res.unwrap_or(file.readFile(toml_path), "")
if str.length(content) > 0
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if toml.toml_has_key(keys, vals, entry_count, "package.alternatives")
let alts_val = toml.toml_get(keys, vals, entry_count, "package.alternatives")
// Check if the alternative is in the array
if str.contains(alts_val, alternative)
return pkg_name
end if
end if
end if
i = i + 1
end while
return "" // No provider found
end find_provider
// Get the scripts directory path for a package in the database
fn get_scripts_dir(name: string): string
return path.join_path(pkg_db_dir(name), "scripts")
end get_scripts_dir
// Check if a package has stored scripts in the database
fn has_stored_scripts(name: string): bool
let scripts_path = get_scripts_dir(name)
return dir.dir_exists(scripts_path)
end has_stored_scripts
// Store scripts from an extracted package to the database
fn store_scripts(name: string, extract_dir: string): bool
let src_scripts = path.join_path(extract_dir, ".SCRIPTS")
// Check if source has scripts
if not dir.dir_exists(src_scripts)
return true // No scripts is not an error
end if
let dest_scripts = get_scripts_dir(name)
// Create scripts directory in database
if not dir.dir_exists(dest_scripts)
if not res.is_ok(dir.create_dir_all(dest_scripts))
return false
end if
end if
// Copy all script files
let cmd = "cp -r \"" + src_scripts + "/\"* \"" + dest_scripts + "/\" 2>/dev/null"
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
// Don't fail if cp fails (might be empty directory)
return true
end store_scripts
// Get the config.txt path for a package
fn pkg_config_path(name: string): string
return path.join_path(pkg_db_dir(name), "config.txt")
end pkg_config_path
// Store config files list from an extracted package to the database
fn store_config_files(name: string, extract_dir: string): bool
let src_config = path.join_path(extract_dir, ".CONFIG")
// Check if source has config files list
if not file.fileExists(src_config)
return true // No config files is not an error
end if
let dest_config = pkg_config_path(name)
// Copy the config files list
let content = res.unwrap_or(file.readFile(src_config), "")
if str.length(content) > 0
return res.is_ok(file.writeFile(dest_config, content))
end if
return true
end store_config_files
// Get list of config files for a package
fn get_config_files(name: string, config_files: [string], max_count: int): int
let config_path = pkg_config_path(name)
if not file.fileExists(config_path)
return 0
end if
let content = res.unwrap_or(file.readFile(config_path), "")
if str.length(content) == 0
return 0
end if
// Split by newlines
mut lines: [string] = new [string](max_count)
let line_count = str.split(content, '\n', lines, max_count)
// Filter out empty lines and comments
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(lines[i])
if str.length(line) > 0 and line[0] != '#'
config_files[count] = line
count = count + 1
end if
i = i + 1
end while
return count
end get_config_files
// ============================================================================
// Root-aware functions for alternate root installation
// ============================================================================
// Get the rooted database directory
fn get_db_dir_rooted(root: string): string
if str.length(root) == 0
return types.get_db_dir()
end if
return root + types.get_db_dir()
end get_db_dir_rooted
// Get the rooted package database directory
fn pkg_db_dir_rooted(name: string, root: string): string
return path.join_path(get_db_dir_rooted(root), name)
end pkg_db_dir_rooted
// Get the rooted pkg.toml path
fn pkg_toml_path_rooted(name: string, root: string): string
return path.join_path(pkg_db_dir_rooted(name, root), "pkg.toml")
end pkg_toml_path_rooted
// Get the rooted files.txt path
fn pkg_files_path_rooted(name: string, root: string): string
return path.join_path(pkg_db_dir_rooted(name, root), "files.txt")
end pkg_files_path_rooted
// Initialize database with alternate root
fn init_db_rooted(root: string): bool
let db_dir = get_db_dir_rooted(root)
if not dir.dir_exists(db_dir)
return res.is_ok(dir.create_dir_all(db_dir))
end if
return true
end init_db_rooted
// Check if package is installed in alternate root
fn is_installed_rooted(name: string, root: string): bool
let pkg_dir = pkg_db_dir_rooted(name, root)
if not dir.dir_exists(pkg_dir)
return false
end if
return file.fileExists(pkg_toml_path_rooted(name, root))
end is_installed_rooted
// Register package with alternate root
fn register_package_rooted(pkg: types.InstalledPackage, root: string): bool
// Ensure database directory exists
if not init_db_rooted(root)
return false
end if
// Create package directory
let pkg_dir = pkg_db_dir_rooted(pkg.info.name, root)
if not dir.dir_exists(pkg_dir)
if not res.is_ok(dir.create_dir_all(pkg_dir))
return false
end if
end if
// Write pkg.toml
let toml_content = generate_pkg_toml(pkg)
let toml_path = pkg_toml_path_rooted(pkg.info.name, root)
if not res.is_ok(file.writeFile(toml_path, toml_content))
return false
end if
return true
end register_package_rooted
// Register package from extract dir with alternate root
fn register_from_extract_dir_rooted(pkg: types.InstalledPackage, extract_dir: string, root: string): bool
// Register the package metadata
if not register_package_rooted(pkg, root)
return false
end if
let files_path = pkg_files_path_rooted(pkg.info.name, root)
// Try .MANIFEST first (v2 format), fall back to .FOOTPRINT (legacy)
let manifest_path = path.join_path(extract_dir, ".MANIFEST")
if file.fileExists(manifest_path)
// Store the full manifest
let manifest_store = path.join_path(pkg_db_dir_rooted(pkg.info.name, root), "manifest.mtree")
let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
file.writeFile(manifest_store, manifest_content)
// Also generate files.txt for backward compatibility
let result = extract_paths_from_manifest(manifest_content)
return res.is_ok(file.writeFile(files_path, result))
end if
// Legacy: .FOOTPRINT
let footprint_path = path.join_path(extract_dir, ".FOOTPRINT")
if not file.fileExists(footprint_path)
file.writeFile(files_path, "")
return true
end if
let content = res.unwrap_or(file.readFile(footprint_path), "")
if str.length(content) == 0
file.writeFile(files_path, "")
return true
end if
let result = process_footprint(content)
return res.is_ok(file.writeFile(files_path, result))
end register_from_extract_dir_rooted
// Get scripts directory with alternate root
fn get_scripts_dir_rooted(name: string, root: string): string
return path.join_path(pkg_db_dir_rooted(name, root), "scripts")
end get_scripts_dir_rooted
// Store scripts with alternate root
fn store_scripts_rooted(name: string, extract_dir: string, root: string): bool
let src_scripts = path.join_path(extract_dir, ".SCRIPTS")
if not dir.dir_exists(src_scripts)
return true
end if
let dest_scripts = get_scripts_dir_rooted(name, root)
if not dir.dir_exists(dest_scripts)
if not res.is_ok(dir.create_dir_all(dest_scripts))
return false
end if
end if
let cmd = "cp -r \"" + src_scripts + "/\"* \"" + dest_scripts + "/\" 2>/dev/null"
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
process.process_wait(pid)
return true
end store_scripts_rooted
// Get config path with alternate root
fn pkg_config_path_rooted(name: string, root: string): string
return path.join_path(pkg_db_dir_rooted(name, root), "config.txt")
end pkg_config_path_rooted
// Store config files with alternate root
fn store_config_files_rooted(name: string, extract_dir: string, root: string): bool
let src_config = path.join_path(extract_dir, ".CONFIG")
if not file.fileExists(src_config)
return true
end if
let dest_config = pkg_config_path_rooted(name, root)
let content = res.unwrap_or(file.readFile(src_config), "")
if str.length(content) > 0
return res.is_ok(file.writeFile(dest_config, content))
end if
return true
end store_config_files_rooted
// List all installed packages in alternate root
fn list_installed_rooted(names: [string], max_count: int, root: string): int
let db_dir = get_db_dir_rooted(root)
if not dir.dir_exists(db_dir)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(db_dir), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Skip hidden files
if str.length(entry) > 0 and entry[0] != '.'
// Verify it's a valid package (has pkg.toml)
let toml_path = pkg_toml_path_rooted(entry, root)
if file.fileExists(toml_path)
names[count] = entry
count = count + 1
end if
end if
i = i + 1
end while
return count
end list_installed_rooted
// Get details of an installed package in alternate root
fn get_installed_rooted(name: string, root: string): types.InstalledPackage
if not is_installed_rooted(name, root)
return new_installed_package()
end if
// Read pkg.toml
let toml_path = pkg_toml_path_rooted(name, root)
let content = res.unwrap_or(file.readFile(toml_path), "")
if str.length(content) == 0
return new_installed_package()
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return new_installed_package()
end if
// Build package info
mut pkg = new_installed_package()
pkg.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
pkg.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
pkg.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
pkg.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
pkg.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
pkg.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
pkg.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
pkg.info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")
// Install metadata
pkg.install_date = toml.toml_get(keys, vals, entry_count, "install.date")
pkg.install_reason = toml.toml_get(keys, vals, entry_count, "install.reason")
// Read files list
let files_path = pkg_files_path_rooted(name, root)
if file.fileExists(files_path)
let files_content = res.unwrap_or(file.readFile(files_path), "")
if str.length(files_content) > 0
let alloc_size = count_newlines(files_content) + 16
mut files_arr: [string] = new [string](alloc_size)
let files_count = str.split(files_content, '\n', files_arr, alloc_size)
// Filter out empty lines
mut valid_count = 0
mut j = 0
while j < files_count
if str.length(files_arr[j]) > 0
valid_count = valid_count + 1
end if
j = j + 1
end while
pkg.files = files_arr
pkg.files_count = valid_count
end if
end if
return pkg
end get_installed_rooted
// Get list of files owned by a package in alternate root
fn get_files_rooted(name: string, files: [string], max_count: int, root: string): int
if not is_installed_rooted(name, root)
return 0
end if
let files_path = pkg_files_path_rooted(name, root)
if not file.fileExists(files_path)
return 0
end if
let content = res.unwrap_or(file.readFile(files_path), "")
if str.length(content) == 0
return 0
end if
// Split by newlines — size dynamically
let alloc_size = count_newlines(content) + 16
mut all_lines: [string] = new [string](alloc_size)
let line_count = str.split(content, '\n', all_lines, alloc_size)
// Copy non-empty lines to output
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(all_lines[i])
if str.length(line) > 0
files[count] = line
count = count + 1
end if
i = i + 1
end while
return count
end get_files_rooted
// Find which package owns a given file in alternate root
fn find_owner_rooted(file_path: string, root: string): string
// Normalize the path - strip leading "/" if present
mut search_path = file_path
if str.length(search_path) > 0 and search_path[0] == '/'
search_path = str.substring(search_path, 1, str.length(search_path) - 1)
end if
// Get list of all installed packages in this root
mut packages: [string] = new [string](256)
let pkg_count = list_installed_rooted(packages, 256, root)
mut i = 0
while i < pkg_count
let pkg_name = packages[i]
// Get files for this package
mut files: [string] = new [string](4096)
let file_count = get_files_rooted(pkg_name, files, 4096, root)
// Search for matching file
mut j = 0
while j < file_count
if files[j] == search_path
return pkg_name
end if
j = j + 1
end while
i = i + 1
end while
return "" // No owner found
end find_owner_rooted
// Unregister a package from the database in alternate root
fn unregister_package_rooted(name: string, root: string): bool
if not is_installed_rooted(name, root)
return true // Already not installed
end if
let pkg_dir = pkg_db_dir_rooted(name, root)
// Remove pkg.toml
let toml_path = pkg_toml_path_rooted(name, root)
if file.fileExists(toml_path)
if not remove_file(toml_path)
return false
end if
end if
// Remove files.txt
let files_path = pkg_files_path_rooted(name, root)
if file.fileExists(files_path)
if not remove_file(files_path)
return false
end if
end if
// Remove scripts directory if exists
let scripts_dir = get_scripts_dir_rooted(name, root)
if dir.dir_exists(scripts_dir)
let cmd = "rm -rf \"" + scripts_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid > 0
process.process_wait(pid)
end if
end if
// Remove config.txt if exists
let config_path = pkg_config_path_rooted(name, root)
if file.fileExists(config_path)
remove_file(config_path)
end if
// Remove the package directory
return res.is_ok(dir.remove_dir(pkg_dir))
end unregister_package_rooted
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: groups.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Package groups support for Coral (@groupname)
******************************************************************************/
module core.groups
import core.str
import io.file
import io.dir
import io.path
import encoding.toml
import types
import core.result as res
export
type GroupResult
fn load_group(name: string): GroupResult
fn list_groups(groups: [types.PackageGroup], max_count: int): int
fn expand_group(name: string, packages: [string], max_count: int): int
fn is_group(name: string): bool
end export
// Result for group loading
type GroupResult = struct
success: bool
group: types.PackageGroup
error: string
end GroupResult
// Get the groups directory
fn get_groups_dir(): string
return types.get_groups_dir()
end get_groups_dir
// Create empty group
fn new_group(): types.PackageGroup
return types.new_package_group()
end new_group
// Create success result
fn success_result(g: types.PackageGroup): GroupResult
return GroupResult{ success: true, group: g, error: "" }
end success_result
// Create error result
fn error_result(msg: string): GroupResult
return GroupResult{ success: false, group: new_group(), error: msg }
end error_result
// Check if a package name is a group reference (starts with @)
fn is_group(name: string): bool
if str.length(name) < 2
return false
end if
return name[0] == '@'
end is_group
// Load a group definition from TOML file
fn load_group(name: string): GroupResult
// Remove @ prefix if present
mut group_name = name
if name[0] == '@'
group_name = str.substring(name, 1, str.length(name) - 1)
end if
let groups_dir = get_groups_dir()
let group_file = path.join_path(groups_dir, group_name + ".toml")
if not file.fileExists(group_file)
return error_result("Group not found: " + group_name)
end if
let content = res.unwrap_or(file.readFile(group_file), "")
if str.length(content) == 0
return error_result("Failed to read group file")
end if
// Parse TOML using key/value arrays
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return error_result("Invalid group file format")
end if
mut group = new_group()
group.name = group_name
// Get description
if toml.toml_has_key(keys, vals, entry_count, "group.description")
group.description = toml.toml_get(keys, vals, entry_count, "group.description")
end if
// Get members list (packages array)
if toml.toml_has_key(keys, vals, entry_count, "group.packages")
let members_str = toml.toml_get(keys, vals, entry_count, "group.packages")
group.members_count = parse_toml_array(members_str, group.members, 256)
end if
return success_result(group)
end load_group
// List all available groups
fn list_groups(groups: [types.PackageGroup], max_count: int): int
let groups_dir = get_groups_dir()
if not dir.dir_exists(groups_dir)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(groups_dir), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Look for .toml files
if str.ends_with(entry, ".toml")
let name_len = str.length(entry) - 5
let name = str.substring(entry, 0, name_len)
let result = load_group(name)
if result.success
groups[count] = result.group
count = count + 1
end if
end if
i = i + 1
end while
return count
end list_groups
// Expand a group to its member packages
fn expand_group(name: string, packages: [string], max_count: int): int
let result = load_group(name)
if not result.success
return 0
end if
let group = result.group
mut count = 0
while count < group.members_count and count < max_count
packages[count] = group.members[count]
count = count + 1
end while
return count
end expand_group
// Parse TOML array value into string array
// Format: ["item1", "item2", "item3"]
fn parse_toml_array(value: string, result: [string], max_items: int): int
let len = str.length(value)
if len < 2
return 0
end if
// Check for array brackets
if value[0] != '['
return 0
end if
mut count = 0
mut i = 1
mut in_string = false
mut item_start = 0
while i < len and count < max_items
let c = value[i]
if c == '"' and not in_string
in_string = true
item_start = i + 1
elif c == '"' and in_string
// End of string item
let item_len = i - item_start
if item_len > 0
result[count] = str.substring(value, item_start, item_len)
count = count + 1
end if
in_string = false
elif c == ']' and not in_string
// End of array
return count
end if
i = i + 1
end while
return count
end parse_toml_array
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: package.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Package archive handling - extract, read metadata, install files
******************************************************************************/
module core.package
import types
import io.file
import io.dir
import io.path
import core.str
import encoding.toml
import util.archive
import util.mtree
import util.checksum
import sys.process
import fs.stat
import fs.perm
import fs.link
import fs.ops
import core.result as res
export
// Package extraction result
type ExtractResult
// Extract a package to a temporary directory
fn extract_package(pkg_path: string, dest_dir: string): ExtractResult
// Read package info from an extracted package or archive
fn read_pkginfo(pkg_path: string): types.PackageInfo
// Read file list from an extracted package (legacy .FOOTPRINT or .MANIFEST)
fn read_footprint(pkg_path: string, files: [string], max_count: int): int
// Read manifest entries from an extracted package
fn read_manifest(pkg_dir: string, entries: [mtree.ManifestEntry], max_count: int): int
// Install files from extracted package to root (manifest-driven)
fn install_files(src_dir: string, root: string): bool
// Remove files listed in footprint from root
fn remove_files(files: [string], file_count: int, root: string): bool
// Remove files using manifest entries (with explicit directory tracking)
fn remove_files_manifest(entries: [mtree.ManifestEntry], entry_count: int, root: string): bool
// Verify package integrity (check all files exist in extracted dir)
fn verify_package(pkg_dir: string): bool
// Install files with old manifest for upgrade config protection
fn install_files_upgrade(src_dir: string, root: string, old_entries: [mtree.ManifestEntry], old_entry_count: int): bool
// Script execution context (chroot-confined maintainer scripts)
type ScriptCtx
fn new_script_ctx(root: string, do_chroot: bool): ScriptCtx
fn script_wants_chroot(root: string, chroot_scripts: bool): bool
fn build_script_cmd(ctx: ScriptCtx, script_path: string, script_name: string, args: string, is_sh: bool): string
fn resolve_script_ctx(root: string, chroot_scripts: bool, caller_is_root: bool): ScriptCtx
// Install scripts support (version passed as $VERSION to scripts)
fn has_scripts(pkg_dir: string): bool
fn run_pre_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
fn run_post_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
fn run_pre_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
fn run_post_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
// Upgrade scripts ($OLD_VERSION $NEW_VERSION passed to scripts)
fn run_pre_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
fn run_post_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
// Run scripts from a stored scripts directory (for remove/upgrade operations)
fn run_stored_pre_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
fn run_stored_post_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
fn run_stored_pre_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
fn run_stored_post_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
// Config file protection
fn read_config_files(pkg_dir: string, config_files: [string], max_count: int): int
fn is_config_file(rel_path: string, config_files: [string], config_count: int): bool
fn install_config_file(src_path: string, dest_path: string, manifest_sha256: string, stored_sha256: string): bool
end export
// Extraction result
type ExtractResult = struct
success: bool
extract_dir: string
error: string
end ExtractResult
// Create a failed extraction result
fn extract_error(msg: string): ExtractResult
return ExtractResult{ success: false, extract_dir: "", error: msg }
end extract_error
// Create a successful extraction result
fn extract_success(dir: string): ExtractResult
return ExtractResult{ success: true, extract_dir: dir, error: "" }
end extract_success
// Extract a package archive to destination directory
fn extract_package(pkg_path: string, dest_dir: string): ExtractResult
// Verify package exists
if not file.fileExists(pkg_path)
return extract_error("Package file not found: " + pkg_path)
end if
// Ensure destination directory exists
if not dir.dir_exists(dest_dir)
if not res.is_ok(dir.create_dir_all(dest_dir))
return extract_error("Failed to create extraction directory: " + dest_dir)
end if
end if
// Extract using archive module
if not archive.extract(pkg_path, dest_dir)
return extract_error("Failed to extract package: " + pkg_path)
end if
// Verify .PKGINFO exists
let pkginfo_path = path.join_path(dest_dir, ".PKGINFO")
if not file.fileExists(pkginfo_path)
return extract_error("Invalid package: missing .PKGINFO")
end if
return extract_success(dest_dir)
end extract_package
// Read package info from .PKGINFO in an extracted package directory
fn read_pkginfo(pkg_dir: string): types.PackageInfo
mut info = types.new_package_info()
let pkginfo_path = path.join_path(pkg_dir, ".PKGINFO")
if not file.fileExists(pkginfo_path)
return info
end if
let content = res.unwrap_or(file.readFile(pkginfo_path), "")
if str.length(content) == 0
return info
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return info
end if
// Extract fields
info.name = toml.toml_get(keys, vals, entry_count, "package.name")
info.version = toml.toml_get(keys, vals, entry_count, "package.version")
info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
info.description = toml.toml_get(keys, vals, entry_count, "package.description")
info.url = toml.toml_get(keys, vals, entry_count, "package.url")
info.license = toml.toml_get(keys, vals, entry_count, "package.license")
info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")
// Parse [dependencies] section (optional — legacy packages won't have it)
if toml.toml_has_key(keys, vals, entry_count, "dependencies.runtime")
let rt_val = toml.toml_get(keys, vals, entry_count, "dependencies.runtime")
info.runtime_deps_count = parse_toml_array(rt_val, info.runtime_deps, 64)
end if
if toml.toml_has_key(keys, vals, entry_count, "dependencies.build")
let bd_val = toml.toml_get(keys, vals, entry_count, "dependencies.build")
info.build_deps_count = parse_toml_array(bd_val, info.build_deps, 64)
end if
return info
end read_pkginfo
// Read file list from .MANIFEST (v2) or .FOOTPRINT (legacy)
// Returns a flat list of relative file paths (files and symlinks only)
fn read_footprint(pkg_dir: string, files: [string], max_count: int): int
// Try .MANIFEST first (v2 format)
let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
if file.fileExists(manifest_path)
let content = res.unwrap_or(file.readFile(manifest_path), "")
if str.length(content) > 0
mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](max_count)
let entry_count = mtree.parse_manifest(content, entries, max_count)
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let etype = mtree.entry_type(entries[i])
// Only include files and symlinks (matches legacy behavior)
if str.equals(etype, "file") or str.equals(etype, "link")
let epath = mtree.entry_path(entries[i])
if str.starts_with(epath, "./")
files[count] = str.substring(epath, 2, str.length(epath) - 2)
else
files[count] = epath
end if
count = count + 1
end if
i = i + 1
end while
return count
end if
end if
// Fallback: legacy .FOOTPRINT
let footprint_path = path.join_path(pkg_dir, ".FOOTPRINT")
if not file.fileExists(footprint_path)
return 0
end if
let content = res.unwrap_or(file.readFile(footprint_path), "")
if str.length(content) == 0
return 0
end if
mut lines: [string] = new [string](max_count)
let line_count = str.split(content, '\n', lines, max_count)
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(lines[i])
if str.length(line) == 0
i = i + 1
continue
end if
if str.equals(line, "./.PKGINFO") or str.equals(line, "./.FOOTPRINT")
i = i + 1
continue
end if
if str.equals(line, ".PKGINFO") or str.equals(line, ".FOOTPRINT")
i = i + 1
continue
end if
let len = str.length(line)
if len > 0 and line[len - 1] == '/'
i = i + 1
continue
end if
if str.starts_with(line, "./")
files[count] = str.substring(line, 2, len - 2)
else
files[count] = line
end if
count = count + 1
i = i + 1
end while
return count
end read_footprint
// Read manifest entries from .MANIFEST in an extracted package directory
fn read_manifest(pkg_dir: string, entries: [mtree.ManifestEntry], max_count: int): int
let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
if not file.fileExists(manifest_path)
return 0
end if
let content = res.unwrap_or(file.readFile(manifest_path), "")
if str.length(content) == 0
return 0
end if
return mtree.parse_manifest(content, entries, max_count)
end read_manifest
// Install files from extracted package to root directory using manifest
fn install_files(src_dir: string, root: string): bool
// Read config file list for protection checks
mut config_files: [string] = new [string](256)
let config_count = read_config_files(src_dir, config_files, 256)
// Parse .MANIFEST
mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
let entry_count = read_manifest(src_dir, entries, 8192)
if entry_count == 0
return false
end if
// Walk manifest entries in order (dirs before their contents)
mut i = 0
while i < entry_count
let entry = entries[i]
let etype = mtree.entry_type(entry)
let epath = mtree.entry_path(entry)
// Strip leading ./ from manifest path to get relative path
mut rel_path = epath
if str.starts_with(epath, "./")
rel_path = str.substring(epath, 2, str.length(epath) - 2)
end if
let dest_path = path.join_path(root, rel_path)
let src_path = path.join_path(src_dir, rel_path)
let mode = mtree.entry_mode(entry)
let uid = mtree.name_to_uid(mtree.entry_uname(entry))
let gid = mtree.name_to_gid(mtree.entry_gname(entry))
if str.equals(etype, "dir")
// Create directory if it doesn't exist
if not dir.dir_exists(dest_path)
if not res.is_ok(dir.create_dir_all(dest_path))
return false
end if
end if
perm.chmod(dest_path, mode)
perm.chown(dest_path, uid, gid)
elif str.equals(etype, "file")
// Check if this is a config-protected file
if is_config_file(rel_path, config_files, config_count)
// Config file — use checksum-based protection
let manifest_sha = mtree.entry_sha256(entry)
install_config_file(src_path, dest_path, manifest_sha, "")
else
// Ensure parent directory exists
let parent = path.dirname(dest_path)
if str.length(parent) > 0 and not dir.dir_exists(parent)
dir.create_dir_all(parent)
end if
// Remove any conflicting target (symlink, file, or dir)
if stat.is_symlink(dest_path)
ops.remove_file(dest_path)
elif stat.exists(dest_path)
ops.remove_file(dest_path)
end if
// Copy file preserving permissions from source
if not res.is_ok(ops.copy_file_preserve(src_path, dest_path))
return false
end if
// Set permissions and ownership from manifest
perm.chmod(dest_path, mode)
perm.chown(dest_path, uid, gid)
// Verify sha256 after copy
let manifest_sha = mtree.entry_sha256(entry)
if str.length(manifest_sha) > 0
let installed_sha = checksum.sha256_file(dest_path)
if not str.equals(installed_sha, manifest_sha)
return false
end if
end if
end if
elif str.equals(etype, "link")
let link_target = mtree.entry_link(entry)
// Remove any conflicting target
if stat.is_symlink(dest_path) or stat.exists(dest_path)
ops.remove_file(dest_path)
end if
// Ensure parent directory exists
let parent = path.dirname(dest_path)
if str.length(parent) > 0 and not dir.dir_exists(parent)
dir.create_dir_all(parent)
end if
// Create symlink
if not res.is_ok(link.symlink(link_target, dest_path))
return false
end if
end if
i = i + 1
end while
return true
end install_files
// Remove files from root directory based on flat file list (legacy)
fn remove_files(files: [string], file_count: int, root: string): bool
// Remove files in reverse order
mut i = file_count - 1
while i >= 0
let rel_path = files[i]
let full_path = path.join_path(root, rel_path)
if stat.is_symlink(full_path) or stat.exists(full_path)
ops.remove_file(full_path)
end if
i = i - 1
end while
// Try to remove empty parent directories
i = file_count - 1
while i >= 0
let rel_path = files[i]
let full_path = path.join_path(root, rel_path)
let parent = path.dirname(full_path)
if str.length(parent) > 0 and dir.dir_exists(parent)
dir.remove_dir(parent)
end if
i = i - 1
end while
return true
end remove_files
// Remove files using manifest entries (with explicit directory tracking)
// Processes in reverse order: files/symlinks first, then directories
fn remove_files_manifest(entries: [mtree.ManifestEntry], entry_count: int, root: string): bool
mut all_success = true
// First pass: remove files and symlinks in reverse order
mut i = entry_count - 1
while i >= 0
let entry = entries[i]
let etype = mtree.entry_type(entry)
let epath = mtree.entry_path(entry)
mut rel_path = epath
if str.starts_with(epath, "./")
rel_path = str.substring(epath, 2, str.length(epath) - 2)
end if
let full_path = path.join_path(root, rel_path)
if str.equals(etype, "file") or str.equals(etype, "link")
if stat.is_symlink(full_path) or stat.exists(full_path)
if not res.is_ok(ops.remove_file(full_path))
all_success = false
end if
end if
end if
i = i - 1
end while
// Second pass: remove directories in reverse order (deepest first)
i = entry_count - 1
while i >= 0
let entry = entries[i]
let etype = mtree.entry_type(entry)
let epath = mtree.entry_path(entry)
if str.equals(etype, "dir")
mut rel_path = epath
if str.starts_with(epath, "./")
rel_path = str.substring(epath, 2, str.length(epath) - 2)
end if
let full_path = path.join_path(root, rel_path)
// Only remove empty directories (remove_dir fails on non-empty)
if dir.dir_exists(full_path)
dir.remove_dir(full_path)
end if
end if
i = i - 1
end while
return all_success
end remove_files_manifest
// Verify package has required files
fn verify_package(pkg_dir: string): bool
// Check for .PKGINFO
let pkginfo_path = path.join_path(pkg_dir, ".PKGINFO")
if not file.fileExists(pkginfo_path)
return false
end if
// Check for .MANIFEST (or legacy .FOOTPRINT)
let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
let footprint_path = path.join_path(pkg_dir, ".FOOTPRINT")
if not file.fileExists(manifest_path) and not file.fileExists(footprint_path)
return false
end if
// Verify we can read package info
let info = read_pkginfo(pkg_dir)
if str.length(info.name) == 0
return false
end if
return true
end verify_package
// Check if package has install/remove scripts
fn has_scripts(pkg_dir: string): bool
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
return dir.dir_exists(scripts_dir)
end has_scripts
// Context describing where a package's maintainer scripts run.
// root == "/" -> normal install on the live system
// do_chroot -> confine scripts to root via chroot (root must be != "/")
type ScriptCtx = struct
root: string
do_chroot: bool
end ScriptCtx
// Construct a ScriptCtx.
fn new_script_ctx(root: string, do_chroot: bool): ScriptCtx
return ScriptCtx{ root: root, do_chroot: do_chroot }
end new_script_ctx
// Pure predicate: should scripts be chrooted for this root + config?
fn script_wants_chroot(root: string, chroot_scripts: bool): bool
if str.equals(root, "/")
return false
end if
return chroot_scripts
end script_wants_chroot
// Resolve the script execution context for a command flow.
// want_chroot requires both a non-"/" root with chroot enabled AND a root caller;
// the caller is responsible for aborting first when chroot is wanted but caller_is_root
// is false (see resolve in the command flows).
fn resolve_script_ctx(root: string, chroot_scripts: bool, caller_is_root: bool): ScriptCtx
mut want_chroot = script_wants_chroot(root, chroot_scripts)
if not caller_is_root
want_chroot = false
end if
return new_script_ctx(root, want_chroot)
end resolve_script_ctx
// The single place a maintainer-script shell command is assembled.
// is_sh true -> run under zsh; false -> execute the file directly.
fn build_script_cmd(ctx: ScriptCtx, script_path: string, script_name: string, args: string, is_sh: bool): string
mut cmd = ""
if ctx.do_chroot
// Confined: run inside <root>; from the script's view the target is "/".
let in_root_path = "/.SCRIPTS/" + script_name
mut body = ""
if is_sh
body = "zsh \"" + in_root_path + "\""
else
body = "\"" + in_root_path + "\""
end if
cmd = "chroot \"" + ctx.root + "\" env CORAL_ROOT=\"/\" " + body
else
// Host: normal install or --no-chroot-scripts. Export CORAL_ROOT=ctx.root.
mut body = ""
if is_sh
body = "zsh \"" + script_path + "\""
else
body = "\"" + script_path + "\""
end if
cmd = "CORAL_ROOT=\"" + ctx.root + "\" " + body
end if
if str.length(args) > 0
cmd = cmd + " " + args
end if
return cmd
end build_script_cmd
// Copy a package's .SCRIPTS dir into <root>/.SCRIPTS so it is reachable post-chroot.
fn stage_scripts_in_root(pkg_scripts_dir: string, root: string): bool
let dest = path.join_path(root, ".SCRIPTS")
// Clean any stale staging first.
let rm_cmd = "rm -rf \"" + dest + "\""
let rm_pid = process.process_spawn_shell(rm_cmd)
process.process_wait(rm_pid)
// Copy preserving perms/owner/symlinks.
let cp_cmd = "cp -a \"" + pkg_scripts_dir + "\" \"" + dest + "\""
let pid = process.process_spawn_shell(cp_cmd)
if pid < 0
return false
end if
let code = process.process_wait(pid)
return code == 0
end stage_scripts_in_root
// Remove staged scripts from <root>/.SCRIPTS.
proc unstage_scripts_in_root(root: string)
let dest = path.join_path(root, ".SCRIPTS")
let cmd = "rm -rf \"" + dest + "\""
let pid = process.process_spawn_shell(cmd)
process.process_wait(pid)
end unstage_scripts_in_root
// Run a script from the .SCRIPTS directory
fn run_script(ctx: ScriptCtx, pkg_dir: string, script_name: string, script_args: string): bool
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let script_path = path.join_path(scripts_dir, script_name)
if not file.fileExists(script_path)
return true
end if
if ctx.do_chroot
if not stage_scripts_in_root(scripts_dir, ctx.root)
// Staging may have left a partial <root>/.SCRIPTS; clean it before bailing.
unstage_scripts_in_root(ctx.root)
return false
end if
end if
let is_sh = str.ends_with(script_name, ".sh")
let cmd = build_script_cmd(ctx, script_path, script_name, script_args, is_sh)
let pid = process.process_spawn_shell(cmd)
mut ok = false
if pid >= 0
let exit_code = process.process_wait(pid)
ok = exit_code == 0
end if
if ctx.do_chroot
unstage_scripts_in_root(ctx.root)
end if
return ok
end run_script
// Run pre-install script (passes $VERSION)
fn run_pre_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
// Try .sh first, then bare executable
let sh_path = path.join_path(scripts_dir, "pre-install.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "pre-install.sh", args)
end if
return run_script(ctx, pkg_dir, "pre-install", args)
end run_pre_install
// Run post-install script (passes $VERSION)
fn run_post_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let sh_path = path.join_path(scripts_dir, "post-install.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "post-install.sh", args)
end if
return run_script(ctx, pkg_dir, "post-install", args)
end run_post_install
// Run pre-remove script (passes $VERSION)
fn run_pre_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let sh_path = path.join_path(scripts_dir, "pre-remove.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "pre-remove.sh", args)
end if
return run_script(ctx, pkg_dir, "pre-remove", args)
end run_pre_remove
// Run post-remove script (passes $VERSION)
fn run_post_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let sh_path = path.join_path(scripts_dir, "post-remove.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "post-remove.sh", args)
end if
return run_script(ctx, pkg_dir, "post-remove", args)
end run_post_remove
// Run pre-upgrade script (passes $OLD_VERSION $NEW_VERSION)
fn run_pre_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + old_version + "\" \"" + new_version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let sh_path = path.join_path(scripts_dir, "pre-upgrade.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "pre-upgrade.sh", args)
end if
return run_script(ctx, pkg_dir, "pre-upgrade", args)
end run_pre_upgrade
// Run post-upgrade script (passes $OLD_VERSION $NEW_VERSION)
fn run_post_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
if not has_scripts(pkg_dir)
return true
end if
let args = "\"" + old_version + "\" \"" + new_version + "\""
let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
let sh_path = path.join_path(scripts_dir, "post-upgrade.sh")
if file.fileExists(sh_path)
return run_script(ctx, pkg_dir, "post-upgrade.sh", args)
end if
return run_script(ctx, pkg_dir, "post-upgrade", args)
end run_post_upgrade
// Run a script directly from a stored scripts directory
fn run_stored_script(ctx: ScriptCtx, scripts_dir: string, script_name: string, script_args: string): bool
let script_path = path.join_path(scripts_dir, script_name)
if not file.fileExists(script_path)
return true
end if
if ctx.do_chroot
if not stage_scripts_in_root(scripts_dir, ctx.root)
// Staging may have left a partial <root>/.SCRIPTS; clean it before bailing.
unstage_scripts_in_root(ctx.root)
return false
end if
end if
let is_sh = str.ends_with(script_name, ".sh")
let cmd = build_script_cmd(ctx, script_path, script_name, script_args, is_sh)
let pid = process.process_spawn_shell(cmd)
mut ok = false
if pid >= 0
let exit_code = process.process_wait(pid)
ok = exit_code == 0
end if
if ctx.do_chroot
unstage_scripts_in_root(ctx.root)
end if
return ok
end run_stored_script
// Run pre-remove script from stored scripts directory (passes $VERSION)
fn run_stored_pre_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
if not dir.dir_exists(scripts_dir)
return true
end if
let args = "\"" + version + "\""
let sh_path = path.join_path(scripts_dir, "pre-remove.sh")
if file.fileExists(sh_path)
return run_stored_script(ctx, scripts_dir, "pre-remove.sh", args)
end if
return run_stored_script(ctx, scripts_dir, "pre-remove", args)
end run_stored_pre_remove
// Run post-remove script from stored scripts directory (passes $VERSION)
fn run_stored_post_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
if not dir.dir_exists(scripts_dir)
return true
end if
let args = "\"" + version + "\""
let sh_path = path.join_path(scripts_dir, "post-remove.sh")
if file.fileExists(sh_path)
return run_stored_script(ctx, scripts_dir, "post-remove.sh", args)
end if
return run_stored_script(ctx, scripts_dir, "post-remove", args)
end run_stored_post_remove
// Run pre-upgrade script from stored scripts directory (passes $OLD_VERSION $NEW_VERSION)
fn run_stored_pre_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
if not dir.dir_exists(scripts_dir)
return true
end if
let args = "\"" + old_version + "\" \"" + new_version + "\""
let sh_path = path.join_path(scripts_dir, "pre-upgrade.sh")
if file.fileExists(sh_path)
return run_stored_script(ctx, scripts_dir, "pre-upgrade.sh", args)
end if
return run_stored_script(ctx, scripts_dir, "pre-upgrade", args)
end run_stored_pre_upgrade
// Run post-upgrade script from stored scripts directory (passes $OLD_VERSION $NEW_VERSION)
fn run_stored_post_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
if not dir.dir_exists(scripts_dir)
return true
end if
let args = "\"" + old_version + "\" \"" + new_version + "\""
let sh_path = path.join_path(scripts_dir, "post-upgrade.sh")
if file.fileExists(sh_path)
return run_stored_script(ctx, scripts_dir, "post-upgrade.sh", args)
end if
return run_stored_script(ctx, scripts_dir, "post-upgrade", args)
end run_stored_post_upgrade
// Read list of config files from .CONFIG file in extracted package
fn read_config_files(pkg_dir: string, config_files: [string], max_count: int): int
let config_path = path.join_path(pkg_dir, ".CONFIG")
if not file.fileExists(config_path)
return 0
end if
let content = res.unwrap_or(file.readFile(config_path), "")
if str.length(content) == 0
return 0
end if
// Split by newlines
mut lines: [string] = new [string](max_count)
let line_count = str.split(content, '\n', lines, max_count)
// Filter out empty lines
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(lines[i])
if str.length(line) > 0 and line[0] != '#'
// Normalize path (remove leading ./)
if str.starts_with(line, "./")
config_files[count] = str.substring(line, 2, str.length(line) - 2)
else
config_files[count] = line
end if
count = count + 1
end if
i = i + 1
end while
return count
end read_config_files
// Check if a file path is in the config files list
fn is_config_file(rel_path: string, config_files: [string], config_count: int): bool
mut i = 0
while i < config_count
if str.equals(rel_path, config_files[i])
return true
end if
i = i + 1
end while
return false
end is_config_file
// Install a config file with checksum-based protection.
// manifest_sha256: checksum of the new package's config file
// stored_sha256: checksum from the previously installed package version (empty on fresh install)
fn install_config_file(src_path: string, dest_path: string, manifest_sha256: string, stored_sha256: string): bool
if not stat.exists(dest_path)
// Fresh install — file doesn't exist yet
// Create parent directory if needed
let dest_dir = path.dirname(dest_path)
if str.length(dest_dir) > 0 and not dir.dir_exists(dest_dir)
dir.create_dir_all(dest_dir)
end if
return res.is_ok(ops.copy_file_preserve(src_path, dest_path))
end if
// File exists — check if user has modified it
if str.length(stored_sha256) == 0
// No stored checksum (fresh install over existing file or legacy package)
// Be safe: install as .pkg-new, preserve user's file
let new_path = dest_path + ".pkg-new"
return res.is_ok(ops.copy_file_preserve(src_path, new_path))
end if
let installed_sha = checksum.sha256_file(dest_path)
if str.equals(installed_sha, stored_sha256)
// User has not modified the config — safe to overwrite
return res.is_ok(ops.copy_file_preserve(src_path, dest_path))
else
// User has modified the config — preserve their version
let new_path = dest_path + ".pkg-new"
return res.is_ok(ops.copy_file_preserve(src_path, new_path))
end if
end install_config_file
// Look up sha256 for a path in manifest entries
fn find_manifest_sha256(rel_path: string, entries: [mtree.ManifestEntry], count: int): string
mut i = 0
while i < count
let epath = mtree.entry_path(entries[i])
mut entry_rel = epath
if str.starts_with(epath, "./")
entry_rel = str.substring(epath, 2, str.length(epath) - 2)
end if
if str.equals(entry_rel, rel_path)
return mtree.entry_sha256(entries[i])
end if
i = i + 1
end while
return ""
end find_manifest_sha256
// Install files from extracted package with old manifest for upgrade config protection
fn install_files_upgrade(src_dir: string, root: string, old_entries: [mtree.ManifestEntry], old_entry_count: int): bool
mut config_files: [string] = new [string](256)
let config_count = read_config_files(src_dir, config_files, 256)
mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
let entry_count = read_manifest(src_dir, entries, 8192)
if entry_count == 0
return false
end if
mut i = 0
while i < entry_count
let entry = entries[i]
let etype = mtree.entry_type(entry)
let epath = mtree.entry_path(entry)
mut rel_path = epath
if str.starts_with(epath, "./")
rel_path = str.substring(epath, 2, str.length(epath) - 2)
end if
let dest_path = path.join_path(root, rel_path)
let src_path = path.join_path(src_dir, rel_path)
let mode = mtree.entry_mode(entry)
let uid = mtree.name_to_uid(mtree.entry_uname(entry))
let gid = mtree.name_to_gid(mtree.entry_gname(entry))
if str.equals(etype, "dir")
if not dir.dir_exists(dest_path)
if not res.is_ok(dir.create_dir_all(dest_path))
return false
end if
end if
perm.chmod(dest_path, mode)
perm.chown(dest_path, uid, gid)
elif str.equals(etype, "file")
if is_config_file(rel_path, config_files, config_count)
let manifest_sha = mtree.entry_sha256(entry)
// Look up old sha256 from previous version's manifest
let stored_sha = find_manifest_sha256(rel_path, old_entries, old_entry_count)
install_config_file(src_path, dest_path, manifest_sha, stored_sha)
else
let parent = path.dirname(dest_path)
if str.length(parent) > 0 and not dir.dir_exists(parent)
dir.create_dir_all(parent)
end if
if stat.is_symlink(dest_path)
ops.remove_file(dest_path)
elif stat.exists(dest_path)
ops.remove_file(dest_path)
end if
if not res.is_ok(ops.copy_file_preserve(src_path, dest_path))
return false
end if
perm.chmod(dest_path, mode)
perm.chown(dest_path, uid, gid)
let manifest_sha = mtree.entry_sha256(entry)
if str.length(manifest_sha) > 0
let installed_sha = checksum.sha256_file(dest_path)
if not str.equals(installed_sha, manifest_sha)
return false
end if
end if
end if
elif str.equals(etype, "link")
let link_target = mtree.entry_link(entry)
if stat.is_symlink(dest_path) or stat.exists(dest_path)
ops.remove_file(dest_path)
end if
let parent = path.dirname(dest_path)
if str.length(parent) > 0 and not dir.dir_exists(parent)
dir.create_dir_all(parent)
end if
if not res.is_ok(link.symlink(link_target, dest_path))
return false
end if
end if
i = i + 1
end while
return true
end install_files_upgrade
// Parse a TOML inline array string like ["foo", "bar"] into a string array
fn parse_toml_array(value: string, result: [string], max_items: int): int
let len = str.length(value)
if len < 2
return 0
end if
if value[0] != '['
if len > 0
result[0] = value
return 1
end if
return 0
end if
mut pos = 1
mut count = 0
while pos < len and count < max_items
while pos < len and (value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
pos = pos + 1
end while
if pos >= len or value[pos] == ']'
break
end if
if value[pos] == '"'
pos = pos + 1
mut item_start = pos
while pos < len and value[pos] != '"'
pos = pos + 1
end while
if pos > item_start
result[count] = str.substring(value, item_start, pos - item_start)
count = count + 1
end if
pos = pos + 1
elif value[pos] != ']' and value[pos] != ','
mut item_start = pos
while pos < len and value[pos] != ',' and value[pos] != ']' and value[pos] != ' '
pos = pos + 1
end while
if pos > item_start
result[count] = str.substring(value, item_start, pos - item_start)
count = count + 1
end if
end if
while pos < len and (value[pos] == ',' or value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
pos = pos + 1
end while
end while
return count
end parse_toml_array
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: pkgdb.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: MsgPack-based package database for fast lookups
The package database provides fast indexed access to:
- Installed packages (packages.db)
- File ownership (files.db)
Source of truth remains in /var/lib/coral/installed/<pkg>/pkg.toml
These indexes can be rebuilt with 'coral db rebuild'
Index files are stored as Base64-encoded MsgPack data for compatibility
with Reef's string-based file I/O.
******************************************************************************/
module core.pkgdb
import types
import io.file
import io.dir
import io.path
import core.str
import core.database
import encoding.msgpack
import encoding.base64
import core.result as res
export
// Package index entry (for packages.db)
type PkgIndexEntry
// Initialize/ensure db directory exists
fn init_db(): bool
// Check if indexes exist and are valid
fn indexes_exist(): bool
// Get package count from index (fast)
fn get_package_count(): int
// List all packages from index (fast)
fn list_packages(names: [string], versions: [string], max_count: int): int
// Check if package is in index
fn is_indexed(name: string): bool
// Get package info from index
fn get_indexed_package(name: string): PkgIndexEntry
// Find file owner from index (fast)
fn find_file_owner(file_path: string): string
// Update index when package is installed
fn index_add_package(name: string, version: string, release: int, description: string): bool
// Update index when package is removed
fn index_remove_package(name: string): bool
// Add files to file index
fn index_add_files(pkg_name: string, files: [string], file_count: int): bool
// Remove files from file index
fn index_remove_files(pkg_name: string): bool
// Rebuild all indexes from installed packages (source of truth)
fn rebuild_indexes(): bool
// Get index statistics
fn get_index_stats(): IndexStats
// Root-aware versions for alternate root
fn init_db_rooted(root: string): bool
fn indexes_exist_rooted(root: string): bool
fn rebuild_indexes_rooted(root: string): bool
fn get_index_stats_rooted(root: string): IndexStats
fn find_file_owner_rooted(file_path: string, root: string): string
// Debug: dump files index contents
fn dump_files_index_rooted(root: string, paths: [string], owners: [string], max_count: int): int
type IndexStats
end export
// ============================================================================
// Types
// ============================================================================
type PkgIndexEntry = struct
name: string
version: string
release: int
description: string
installed_date: string
file_count: int
found: bool
end PkgIndexEntry
type IndexStats = struct
package_count: int
file_count: int
packages_db_size: int
files_db_size: int
last_updated: string
end IndexStats
// Loaded packages index (deserialized from packages.db)
type PackagesIndex = struct
version: int
generated: string
package_count: int
entries: [PkgIndexEntry]
loaded: bool
end PackagesIndex
// Loaded files index (deserialized from files.db)
// Uses parallel arrays for binary search capability
type FilesIndex = struct
version: int
generated: string
file_count: int
file_paths: [string] // Sorted alphabetically for binary search
owners: [string] // Package name at same index as file_paths
loaded: bool
end FilesIndex
// ============================================================================
// Constants
// ============================================================================
const INDEX_VERSION: int = 1
const MAX_PACKAGES: int = 2048
const MAX_FILES: int = 131072 // 128K files max
// ============================================================================
// Path Constants
// ============================================================================
fn db_dir(): string
return types.get_index_dir()
end db_dir
fn packages_db_path(): string
return types.get_index_dir() + "/packages.db"
end packages_db_path
fn files_db_path(): string
return types.get_index_dir() + "/files.db"
end files_db_path
// ============================================================================
// Buffer Size Estimation Helpers
// ============================================================================
// Estimate buffer size needed for packages.db
fn estimate_packages_buffer_size(pkg_count: int): int
// Header overhead: ~100 bytes
// Per package: ~200 bytes (name, version, description, dates)
return 100 + (pkg_count * 200)
end estimate_packages_buffer_size
// Estimate buffer size needed for files.db
fn estimate_files_buffer_size(file_count: int): int
// Header overhead: ~100 bytes
// Per file: ~100 bytes (path + package name)
return 100 + (file_count * 100)
end estimate_files_buffer_size
// Get current timestamp as string
fn get_timestamp(): string
// Simple timestamp - just use a placeholder for now
// In production would use sys.time module
return "2026-01-29"
end get_timestamp
// ============================================================================
// Empty/Default Constructors
// ============================================================================
fn empty_packages_index(): PackagesIndex
return PackagesIndex{
version: 0,
generated: "",
package_count: 0,
entries: new [PkgIndexEntry](MAX_PACKAGES),
loaded: false
}
end empty_packages_index
fn empty_files_index(): FilesIndex
return FilesIndex{
version: 0,
generated: "",
file_count: 0,
file_paths: new [string](MAX_FILES),
owners: new [string](MAX_FILES),
loaded: false
}
end empty_files_index
fn empty_pkg_entry(): PkgIndexEntry
return PkgIndexEntry{
name: "",
version: "",
release: 0,
description: "",
installed_date: "",
file_count: 0,
found: false
}
end empty_pkg_entry
// Get just the header size for a map (not the entire map contents)
fn map_header_size(buf: [int], offset: int): int
let b = buf[offset] & 255
// Fixmap (0x80-0x8F): 1 byte header
if (b & 0xF0) == 0x80
return 1
// map16 (0xDE): 3 byte header
elif b == 0xDE
return 3
// map32 (0xDF): 5 byte header
elif b == 0xDF
return 5
end if
return 1 // Default
end map_header_size
// Get just the header size for an array (not the entire array contents)
fn array_header_size(buf: [int], offset: int): int
let b = buf[offset] & 255
// Fixarray (0x90-0x9F): 1 byte header
if (b & 0xF0) == 0x90
return 1
// array16 (0xDC): 3 byte header
elif b == 0xDC
return 3
// array32 (0xDD): 5 byte header
elif b == 0xDD
return 5
end if
return 1 // Default
end array_header_size
// ============================================================================
// MsgPack Deserialization
// ============================================================================
// Load packages index from disk
fn load_packages_index_rooted(root: string): PackagesIndex
mut index = empty_packages_index()
// Check if file exists
let db_path = packages_db_path_rooted(root)
if not file.fileExists(db_path)
return index
end if
// Read base64-encoded content
let encoded = res.unwrap_or(file.readFile(db_path), "")
if str.length(encoded) == 0
return index
end if
// Decode base64 to buffer
let buf_size = str.length(encoded) // Decoded will be smaller
mut buf: [int] = new [int](buf_size)
let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)
if buf_len == 0
return index
end if
// Parse MsgPack structure
mut offset = 0
// Expect map header
if not msgpack.msgpack_is_map(buf, offset)
return index
end if
let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
// Iterate through map entries
mut entry_idx = 0
while entry_idx < map_len and offset < buf_len
// Get key
let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
if str.equals(key, "version")
index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "generated")
index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "package_count")
index.package_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "packages")
// Parse packages array
let arr_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
offset = offset + array_header_size(buf, offset)
mut pkg_idx = 0
while pkg_idx < arr_len and pkg_idx < MAX_PACKAGES and offset < buf_len
// Each package is a map
let pkg_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
mut entry = empty_pkg_entry()
entry.found = true
mut pkg_field = 0
while pkg_field < pkg_map_len and offset < buf_len
let field_key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
if str.equals(field_key, "name")
entry.name = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
elif str.equals(field_key, "version")
entry.version = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
elif str.equals(field_key, "release")
entry.release = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
elif str.equals(field_key, "description")
entry.description = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
elif str.equals(field_key, "installed_date")
entry.installed_date = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
elif str.equals(field_key, "file_count")
entry.file_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
end if
offset = offset + msgpack.msgpack_value_size(buf, offset)
pkg_field = pkg_field + 1
end while
index.entries[pkg_idx] = entry
pkg_idx = pkg_idx + 1
end while
else
// Skip unknown key's value
offset = offset + msgpack.msgpack_value_size(buf, offset)
end if
entry_idx = entry_idx + 1
end while
index.loaded = true
return index
end load_packages_index_rooted
// Load files index from disk
fn load_files_index_rooted(root: string): FilesIndex
mut index = empty_files_index()
// Check if file exists
let db_path = files_db_path_rooted(root)
if not file.fileExists(db_path)
return index
end if
// Read base64-encoded content
let encoded = res.unwrap_or(file.readFile(db_path), "")
let encoded_len = str.length(encoded)
if encoded_len == 0
return index
end if
// Decode base64 to buffer
let buf_size = encoded_len // Decoded will be smaller
mut buf: [int] = new [int](buf_size)
let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)
if buf_len <= 0
return index
end if
// Parse MsgPack structure
mut offset = 0
// Expect map header
if not msgpack.msgpack_is_map(buf, offset)
return index
end if
let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
// Iterate through map entries
mut entry_idx = 0
while entry_idx < map_len and offset < buf_len
// Get key
let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
if str.equals(key, "version")
index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "generated")
index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "file_count")
index.file_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "files")
// Parse files map
let files_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
mut file_idx = 0
while file_idx < files_map_len and file_idx < MAX_FILES and offset < buf_len
// Key is file path, value is owner
let file_path = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
let owner = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
index.file_paths[file_idx] = file_path
index.owners[file_idx] = owner
file_idx = file_idx + 1
end while
index.file_count = file_idx
else
// Skip unknown key's value
offset = offset + msgpack.msgpack_value_size(buf, offset)
end if
entry_idx = entry_idx + 1
end while
index.loaded = true
return index
end load_files_index_rooted
// Binary search for file owner in sorted files index
// Returns package name or empty string if not found
fn binary_search_file_owner(index: FilesIndex, path: string): string
if not index.loaded or index.file_count == 0
return ""
end if
mut low = 0
mut high = index.file_count - 1
while low <= high
let mid = (low + high) / 2
let cmp = str.compare(path, index.file_paths[mid])
if cmp == 0
return index.owners[mid]
elif cmp < 0
high = mid - 1
else
low = mid + 1
end if
end while
return "" // Not found
end binary_search_file_owner
// Normalize file path for lookup (strip leading /)
fn normalize_path(path: string): string
let len = str.length(path)
if len > 0 and path[0] == '/'
return str.substring(path, 1, len - 1)
end if
return path
end normalize_path
// Linear search fallback for file owner (when binary search fails)
fn linear_search_file_owner(index: FilesIndex, path: string): string
if not index.loaded or index.file_count == 0
return ""
end if
mut i = 0
while i < index.file_count
if str.equals(path, index.file_paths[i])
return index.owners[i]
end if
i = i + 1
end while
return ""
end linear_search_file_owner
// ============================================================================
// Initialization
// ============================================================================
fn init_db(): bool
let db = db_dir()
if not dir.dir_exists(db)
return res.is_ok(dir.create_dir_all(db))
end if
return true
end init_db
fn indexes_exist(): bool
return file.fileExists(packages_db_path()) and file.fileExists(files_db_path())
end indexes_exist
// ============================================================================
// Package Index Operations - Uses MsgPack index with fallback
// ============================================================================
fn get_package_count(): int
// Try index first
let index = load_packages_index_rooted("")
if index.loaded
return index.package_count
end if
// Fall back to database scan
mut names: [string] = new [string](1024)
return database.list_installed(names, 1024)
end get_package_count
fn list_packages(names: [string], versions: [string], max_count: int): int
// Try index first
let index = load_packages_index_rooted("")
if index.loaded
mut count = 0
while count < index.package_count and count < max_count
names[count] = index.entries[count].name
versions[count] = index.entries[count].version
count = count + 1
end while
return count
end if
// Fall back to database scan
let count = database.list_installed(names, max_count)
// Fill in versions
mut i = 0
while i < count
let pkg = database.get_installed(names[i])
versions[i] = pkg.info.version
i = i + 1
end while
return count
end list_packages
fn is_indexed(name: string): bool
// Try index first
let index = load_packages_index_rooted("")
if index.loaded
mut i = 0
while i < index.package_count
if str.equals(index.entries[i].name, name)
return true
end if
i = i + 1
end while
return false
end if
// Fall back to database check
return database.is_installed(name)
end is_indexed
fn get_indexed_package(name: string): PkgIndexEntry
// Try index first
let index = load_packages_index_rooted("")
if index.loaded
mut i = 0
while i < index.package_count
if str.equals(index.entries[i].name, name)
return index.entries[i]
end if
i = i + 1
end while
return empty_pkg_entry()
end if
// Fall back to database
mut entry = empty_pkg_entry()
if not database.is_installed(name)
return entry
end if
let pkg = database.get_installed(name)
entry.name = pkg.info.name
entry.version = pkg.info.version
entry.release = pkg.info.release
entry.description = pkg.info.description
entry.installed_date = pkg.install_date
entry.file_count = pkg.files_count
entry.found = true
return entry
end get_indexed_package
// ============================================================================
// File Index Operations - Uses MsgPack index with fallback
// ============================================================================
fn find_file_owner(file_path: string): string
return find_file_owner_rooted(file_path, "")
end find_file_owner
fn find_file_owner_rooted(file_path: string, root: string): string
// Try index first (O(log N) binary search)
let index = load_files_index_rooted(root)
if index.loaded
let normalized = normalize_path(file_path)
let owner = binary_search_file_owner(index, normalized)
if str.length(owner) > 0
return owner
end if
// Binary search failed - try linear search as fallback
// This helps diagnose if the index isn't sorted correctly
let linear_owner = linear_search_file_owner(index, normalized)
if str.length(linear_owner) > 0
return linear_owner
end if
// File not in index - either not owned or index out of date
return ""
end if
// Fall back to database scan (O(N*M))
if str.length(root) > 0
return database.find_owner_rooted(file_path, root)
end if
return database.find_owner(file_path)
end find_file_owner_rooted
// ============================================================================
// Index Modification (stub - no-op for now)
// ============================================================================
fn index_add_package(name: string, version: string, release: int, description: string): bool
// Stub - no indexing yet
return true
end index_add_package
fn index_remove_package(name: string): bool
// Stub - no indexing yet
return true
end index_remove_package
fn index_add_files(pkg_name: string, files: [string], file_count: int): bool
// Stub - no indexing yet
return true
end index_add_files
fn index_remove_files(pkg_name: string): bool
// Stub - triggers full rebuild
return true
end index_remove_files
// ============================================================================
// MsgPack Serialization
// ============================================================================
// Serialize packages index to MsgPack format
// Returns buffer and sets length via out parameter simulation (length stored at buf[0])
fn serialize_packages_db_rooted(root: string, buf: [int], max_size: int): int
// Get list of installed packages
mut names: [string] = new [string](MAX_PACKAGES)
let pkg_count = database.list_installed_rooted(names, MAX_PACKAGES, root)
mut pos = 0
// Pack map header (4 keys: version, generated, package_count, packages)
pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)
// Pack "version" -> INDEX_VERSION
pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
pos = pos + msgpack.msgpack_pack_int(INDEX_VERSION, buf, pos)
// Pack "generated" -> timestamp
pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)
// Pack "package_count" -> count
pos = pos + msgpack.msgpack_pack_string("package_count", buf, pos)
pos = pos + msgpack.msgpack_pack_int(pkg_count, buf, pos)
// Pack "packages" -> array of package entries
pos = pos + msgpack.msgpack_pack_string("packages", buf, pos)
pos = pos + msgpack.msgpack_pack_array_header(pkg_count, buf, pos)
// Pack each package entry
mut i = 0
while i < pkg_count and pos < max_size - 1000
let pkg = database.get_installed_rooted(names[i], root)
// Each package is a map with 6 keys
pos = pos + msgpack.msgpack_pack_map_header(6, buf, pos)
// name
pos = pos + msgpack.msgpack_pack_string("name", buf, pos)
pos = pos + msgpack.msgpack_pack_string(pkg.info.name, buf, pos)
// version
pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
pos = pos + msgpack.msgpack_pack_string(pkg.info.version, buf, pos)
// release
pos = pos + msgpack.msgpack_pack_string("release", buf, pos)
pos = pos + msgpack.msgpack_pack_int(pkg.info.release, buf, pos)
// description
pos = pos + msgpack.msgpack_pack_string("description", buf, pos)
pos = pos + msgpack.msgpack_pack_string(pkg.info.description, buf, pos)
// installed_date
pos = pos + msgpack.msgpack_pack_string("installed_date", buf, pos)
pos = pos + msgpack.msgpack_pack_string(pkg.install_date, buf, pos)
// file_count
pos = pos + msgpack.msgpack_pack_string("file_count", buf, pos)
pos = pos + msgpack.msgpack_pack_int(pkg.files_count, buf, pos)
i = i + 1
end while
return pos
end serialize_packages_db_rooted
// Count total installed files across all packages (cheap — no file content read)
fn count_total_files_rooted(root: string): int
mut pkg_names: [string] = new [string](MAX_PACKAGES)
let pkg_count = database.list_installed_rooted(pkg_names, MAX_PACKAGES, root)
mut total = 0
mut i = 0
while i < pkg_count
mut pkg_files: [string] = new [string](8192)
let file_count = database.get_files_rooted(pkg_names[i], pkg_files, 8192, root)
total = total + file_count
i = i + 1
end while
return total
end count_total_files_rooted
// Serialize files index to MsgPack format
// Creates a map of file_path -> package_name for fast ownership lookup
fn serialize_files_db_rooted(root: string, buf: [int], max_size: int, alloc_size: int): int
// Get all installed packages
mut pkg_names: [string] = new [string](MAX_PACKAGES)
let pkg_count = database.list_installed_rooted(pkg_names, MAX_PACKAGES, root)
// Collect all files with their owners — sized to actual count + margin
mut all_files: [string] = new [string](alloc_size)
mut all_owners: [string] = new [string](alloc_size)
mut total_files = 0
mut i = 0
while i < pkg_count and total_files < alloc_size - 256
mut pkg_files: [string] = new [string](8192)
let file_count = database.get_files_rooted(pkg_names[i], pkg_files, 8192, root)
mut j = 0
while j < file_count and total_files < alloc_size
all_files[total_files] = pkg_files[j]
all_owners[total_files] = pkg_names[i]
total_files = total_files + 1
j = j + 1
end while
i = i + 1
end while
// Sort files alphabetically for binary search (simple bubble sort for now)
sort_file_index(all_files, all_owners, total_files)
mut pos = 0
// Pack map header (4 keys: version, generated, file_count, files)
pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)
// Pack "version" -> INDEX_VERSION
pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
pos = pos + msgpack.msgpack_pack_int(INDEX_VERSION, buf, pos)
// Pack "generated" -> timestamp
pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)
// Pack "file_count" -> count
pos = pos + msgpack.msgpack_pack_string("file_count", buf, pos)
pos = pos + msgpack.msgpack_pack_int(total_files, buf, pos)
// Pack "files" -> map of path -> owner
pos = pos + msgpack.msgpack_pack_string("files", buf, pos)
pos = pos + msgpack.msgpack_pack_map_header(total_files, buf, pos)
// Pack each file -> owner pair
i = 0
while i < total_files and pos < max_size - 500
pos = pos + msgpack.msgpack_pack_string(all_files[i], buf, pos)
pos = pos + msgpack.msgpack_pack_string(all_owners[i], buf, pos)
i = i + 1
end while
return pos
end serialize_files_db_rooted
// Sort parallel arrays of files and owners alphabetically by file path
// Uses merge sort for O(n log n) performance on large file counts
proc sort_file_index(files: [string], owners: [string], count: int)
if count <= 1
return
end if
// Allocate temporary arrays for merge operations
mut tmp_files: [string] = new [string](count)
mut tmp_owners: [string] = new [string](count)
merge_sort(files, owners, tmp_files, tmp_owners, 0, count - 1)
end sort_file_index
proc merge_sort(files: [string], owners: [string], tmp_files: [string], tmp_owners: [string], left: int, right: int)
if left >= right
return
end if
let mid = left + (right - left) / 2
merge_sort(files, owners, tmp_files, tmp_owners, left, mid)
merge_sort(files, owners, tmp_files, tmp_owners, mid + 1, right)
merge(files, owners, tmp_files, tmp_owners, left, mid, right)
end merge_sort
proc merge(files: [string], owners: [string], tmp_files: [string], tmp_owners: [string], left: int, mid: int, right: int)
// Copy both halves into temp arrays
mut i = left
while i <= right
tmp_files[i] = files[i]
tmp_owners[i] = owners[i]
i = i + 1
end while
// Merge back from temp into original
mut l = left
mut r = mid + 1
mut k = left
while l <= mid and r <= right
if str.compare(tmp_files[l], tmp_files[r]) <= 0
files[k] = tmp_files[l]
owners[k] = tmp_owners[l]
l = l + 1
else
files[k] = tmp_files[r]
owners[k] = tmp_owners[r]
r = r + 1
end if
k = k + 1
end while
// Copy remaining left half
while l <= mid
files[k] = tmp_files[l]
owners[k] = tmp_owners[l]
l = l + 1
k = k + 1
end while
// Right half remaining elements are already in place
end merge
// ============================================================================
// Index Rebuild
// ============================================================================
fn rebuild_indexes(): bool
return rebuild_indexes_rooted("")
end rebuild_indexes
// ============================================================================
// Index Statistics
// ============================================================================
fn get_index_stats(): IndexStats
mut stats = IndexStats{
package_count: 0,
file_count: 0,
packages_db_size: 0,
files_db_size: 0,
last_updated: ""
}
// Get package count from source of truth
mut names: [string] = new [string](1024)
stats.package_count = database.list_installed(names, 1024)
// Count files across all packages
mut i = 0
while i < stats.package_count
mut files: [string] = new [string](4096)
let file_count = database.get_files(names[i], files, 4096)
stats.file_count = stats.file_count + file_count
i = i + 1
end while
return stats
end get_index_stats
// ============================================================================
// Root-aware versions for alternate root
// ============================================================================
fn db_dir_rooted(root: string): string
if str.length(root) == 0
return types.get_index_dir()
end if
return root + types.get_index_dir()
end db_dir_rooted
fn packages_db_path_rooted(root: string): string
return db_dir_rooted(root) + "/packages.db"
end packages_db_path_rooted
fn files_db_path_rooted(root: string): string
return db_dir_rooted(root) + "/files.db"
end files_db_path_rooted
fn init_db_rooted(root: string): bool
let db = db_dir_rooted(root)
if not dir.dir_exists(db)
return res.is_ok(dir.create_dir_all(db))
end if
return true
end init_db_rooted
fn indexes_exist_rooted(root: string): bool
return file.fileExists(packages_db_path_rooted(root)) and file.fileExists(files_db_path_rooted(root))
end indexes_exist_rooted
fn rebuild_indexes_rooted(root: string): bool
if not init_db_rooted(root)
return false
end if
// Serialize packages.db
let pkg_buf_size = estimate_packages_buffer_size(MAX_PACKAGES)
mut pkg_buf: [int] = new [int](pkg_buf_size)
let pkg_len = serialize_packages_db_rooted(root, pkg_buf, pkg_buf_size)
if pkg_len > 0
// Encode to base64 and write
let pkg_encoded = base64.base64_encode_bytes(pkg_buf, pkg_len)
if not res.is_ok(file.writeFile(packages_db_path_rooted(root), pkg_encoded))
return false
end if
end if
// Serialize files.db — count actual files first to avoid massive over-allocation
let actual_file_count = count_total_files_rooted(root)
let alloc_size = actual_file_count + 1024
let files_buf_size = estimate_files_buffer_size(alloc_size)
mut files_buf: [int] = new [int](files_buf_size)
let files_len = serialize_files_db_rooted(root, files_buf, files_buf_size, alloc_size)
if files_len > 0
// Encode to base64 and write
let files_encoded = base64.base64_encode_bytes(files_buf, files_len)
if not res.is_ok(file.writeFile(files_db_path_rooted(root), files_encoded))
return false
end if
end if
return true
end rebuild_indexes_rooted
fn get_index_stats_rooted(root: string): IndexStats
mut stats = IndexStats{
package_count: 0,
file_count: 0,
packages_db_size: 0,
files_db_size: 0,
last_updated: ""
}
// Get package count from source of truth in alternate root
mut names: [string] = new [string](1024)
stats.package_count = database.list_installed_rooted(names, 1024, root)
// Count files across all packages
mut i = 0
while i < stats.package_count
mut files: [string] = new [string](4096)
let file_count = database.get_files_rooted(names[i], files, 4096, root)
stats.file_count = stats.file_count + file_count
i = i + 1
end while
return stats
end get_index_stats_rooted
// Debug: dump files index contents to arrays
fn dump_files_index_rooted(root: string, paths: [string], owners: [string], max_count: int): int
let index = load_files_index_rooted(root)
if not index.loaded
return 0
end if
mut count = 0
while count < index.file_count and count < max_count
paths[count] = index.file_paths[count]
owners[count] = index.owners[count]
count = count + 1
end while
return count
end dump_files_index_rooted
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: port.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Port loading and parsing from package.toml
******************************************************************************/
module core.port
import types
import io.file
import io.dir
import io.path
import core.str
import core.config
import encoding.toml
import core.result as res
export
// Load a port from a directory path, returns PortResult
fn load(port_path: string): types.PortResult
// Find a port by name, searches all categories
fn find(name: string): types.PortResult
// List all ports in a category
fn list_category(category: string, names: [string], max_count: int): int
// Get all categories
fn get_categories(cats: [string], max_count: int): int
end export
// Dynamically discover categories by scanning the ports directory
// Excludes hidden dirs, infrastructure dirs (pkgs/, groups/), and config-aware paths
fn get_categories(cats: [string], max_count: int): int
let cfg = config.load()
let ports_dir = config.get_ports_dir(cfg)
if not dir.dir_exists(ports_dir)
return 0
end if
let packages_path = config.get_packages_dir(cfg)
let sources_path = config.get_sources_dir(cfg)
let build_path = config.get_build_dir(cfg)
// Extract first path component relative to ports_dir for each configured path
let skip1 = get_relative_top_dir(ports_dir, packages_path)
let skip2 = get_relative_top_dir(ports_dir, sources_path)
let skip3 = get_relative_top_dir(ports_dir, build_path)
// Also skip the groups directory
let groups_dir = types.get_groups_dir()
let skip_groups = get_relative_top_dir(ports_dir, groups_dir)
let entries = res.unwrap_or(dir.list_dir(ports_dir), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
let elen = str.length(entry)
// Skip hidden directories
if elen == 0 or entry[0] == '.'
i = i + 1
continue
end if
// Skip infrastructure directories
if str.equals(entry, skip1) or str.equals(entry, skip2) or str.equals(entry, skip3) or str.equals(entry, skip_groups)
i = i + 1
continue
end if
// Verify it's actually a directory
let entry_path = path.join_path(ports_dir, entry)
if dir.dir_exists(entry_path)
cats[count] = entry
count = count + 1
end if
i = i + 1
end while
return count
end get_categories
// Extract the first path component of `child` relative to `parent`
// e.g. parent="/usr/zports", child="/usr/zports/pkgs/packages" -> "pkgs"
// Returns empty string if child is not under parent
fn get_relative_top_dir(parent: string, child: string): string
let parent_len = str.length(parent)
let child_len = str.length(child)
if child_len <= parent_len
return ""
end if
// Check that child starts with parent
let prefix = str.substring(child, 0, parent_len)
if not str.equals(prefix, parent)
return ""
end if
// Skip the separator
mut start = parent_len
if child[start] == '/'
start = start + 1
end if
// Find the next slash or end of string
mut end_pos = start
while end_pos < child_len
if child[end_pos] == '/'
break
end if
end_pos = end_pos + 1
end while
if end_pos > start
return str.substring(child, start, end_pos - start)
end if
return ""
end get_relative_top_dir
// Parse a TOML array value like ["item1", "item2"] into a string array
// Returns the number of items parsed
fn parse_toml_array(value: string, result: [string], max_items: int): int
let len = str.length(value)
if len < 2
return 0
end if
// Check for array brackets
if value[0] != '['
// Single value, not an array
if len > 0
result[0] = value
return 1
end if
return 0
end if
// Skip the opening bracket
mut pos = 1
mut count = 0
while pos < len and count < max_items
// Skip whitespace
while pos < len and (value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
pos = pos + 1
end while
if pos >= len or value[pos] == ']'
break
end if
// Check for quoted string
if value[pos] == '"'
pos = pos + 1
mut item_start = pos
// Find closing quote
while pos < len and value[pos] != '"'
pos = pos + 1
end while
if pos > item_start
result[count] = str.substring(value, item_start, pos - item_start)
count = count + 1
end if
pos = pos + 1 // Skip closing quote
elif value[pos] != ']' and value[pos] != ','
// Unquoted value
mut item_start = pos
while pos < len and value[pos] != ',' and value[pos] != ']' and value[pos] != ' '
pos = pos + 1
end while
if pos > item_start
result[count] = str.substring(value, item_start, pos - item_start)
count = count + 1
end if
end if
// Skip comma and whitespace
while pos < len and (value[pos] == ',' or value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
pos = pos + 1
end while
end while
return count
end parse_toml_array
// Create an empty/default Port structure (delegate to types module)
fn new_port(): types.Port
return types.new_port()
end new_port
// Helper to create error result
fn error_result(msg: string): types.PortResult
return types.new_port_result(false, new_port(), msg)
end error_result
// Helper to create success result
fn success_result(p: types.Port): types.PortResult
return types.new_port_result(true, p, "")
end success_result
// Extract filename from URL
fn extract_filename_from_url(url: string): string
let len = str.length(url)
if len == 0
return ""
end if
// Find last slash
mut last_slash = -1
mut i = len - 1
while i >= 0
if url[i] == '/'
last_slash = i
break
end if
i = i - 1
end while
if last_slash < 0
return url
end if
let filename = str.substring(url, last_slash + 1, len - last_slash - 1)
// Remove query string if present
let query_len = str.length(filename)
mut query_pos = -1
i = 0
while i < query_len
if filename[i] == '?'
query_pos = i
break
end if
i = i + 1
end while
if query_pos > 0
return str.substring(filename, 0, query_pos)
end if
return filename
end extract_filename_from_url
// Parse sources from TOML - supports both new [[source]] and legacy [sources] format
fn parse_sources(keys: [string], vals: [string], entry_count: int): types.SourceInfo
mut info = types.new_source_info()
// Try new [[source]] format first (source.0.file, source.1.file, etc.)
mut source_idx = 0
mut found_new_format = false
while source_idx < 16
let prefix = "source." + int_to_str(source_idx)
let file_key = prefix + ".file"
if not toml.toml_has_key(keys, vals, entry_count, file_key)
break
end if
found_new_format = true
mut src = types.new_source()
// Get file name
src.file = toml.toml_get(keys, vals, entry_count, file_key)
// Get URLs array
let urls_key = prefix + ".urls"
if toml.toml_has_key(keys, vals, entry_count, urls_key)
let urls_val = toml.toml_get(keys, vals, entry_count, urls_key)
mut urls_arr: [string] = new [string](16)
let urls_count = parse_toml_array(urls_val, urls_arr, 16)
src.urls = urls_arr
src.url_count = urls_count
end if
// Get checksum (single value)
let checksum_key = prefix + ".checksum"
if toml.toml_has_key(keys, vals, entry_count, checksum_key)
src.checksum = toml.toml_get(keys, vals, entry_count, checksum_key)
end if
// Get extract flag (default: true)
let extract_key = prefix + ".extract"
if toml.toml_has_key(keys, vals, entry_count, extract_key)
src.extract = toml.toml_get_bool(keys, vals, entry_count, extract_key)
end if
info.sources[source_idx] = src
source_idx = source_idx + 1
end while
if found_new_format
info.count = source_idx
return info
end if
// Fall back to legacy [sources] format
if toml.toml_has_key(keys, vals, entry_count, "sources.urls")
let urls_val = toml.toml_get(keys, vals, entry_count, "sources.urls")
mut urls_arr: [string] = new [string](16)
let urls_count = parse_toml_array(urls_val, urls_arr, 16)
// Parse checksums
mut checksums_arr: [string] = new [string](16)
if toml.toml_has_key(keys, vals, entry_count, "sources.checksums")
let cksum_val = toml.toml_get(keys, vals, entry_count, "sources.checksums")
parse_toml_array(cksum_val, checksums_arr, 16)
end if
// Convert legacy format to new Source structs
mut i = 0
while i < urls_count
mut src = types.new_source()
src.file = extract_filename_from_url(urls_arr[i])
src.urls[0] = urls_arr[i]
src.url_count = 1
if str.length(checksums_arr[i]) > 0
src.checksum = checksums_arr[i]
end if
src.extract = true
info.sources[i] = src
i = i + 1
end while
info.count = urls_count
end if
return info
end parse_sources
// Helper: convert int to string (for source index keys)
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut result = ""
mut value = n
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
return result
end int_to_str
// Load a port from a directory containing package.toml
fn load(port_path: string): types.PortResult
// Check if directory exists
if not dir.dir_exists(port_path)
return error_result("Port directory does not exist: " + port_path)
end if
// Check for package.toml
let toml_path = path.join_path(port_path, "package.toml")
if not file.fileExists(toml_path)
return error_result("package.toml not found in: " + port_path)
end if
// Read the TOML file
let content = res.unwrap_or(file.readFile(toml_path), "")
if str.length(content) == 0
return error_result("Failed to read package.toml or file is empty")
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return error_result("Failed to parse package.toml")
end if
// Build the Port structure
mut port = new_port()
port.port_dir = port_path
// Extract category from path (e.g., /usr/zports/base/vim -> base)
let parent_dir = path.dirname(port_path)
port.category = path.basename(parent_dir)
// Parse [package] section
port.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
port.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
port.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
port.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
port.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
port.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
port.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
// Architecture (default to x86_64 if not specified)
let arch_val = toml.toml_get(keys, vals, entry_count, "package.arch")
if str.length(arch_val) > 0
port.info.arch = arch_val
end if
// Parse alternatives array
if toml.toml_has_key(keys, vals, entry_count, "package.alternatives")
let alt_val = toml.toml_get(keys, vals, entry_count, "package.alternatives")
mut alt_arr: [string] = new [string](32)
let alt_count = parse_toml_array(alt_val, alt_arr, 32)
port.info.alternatives = alt_arr
port.info.alternatives_count = alt_count
end if
// Parse conflicts array
if toml.toml_has_key(keys, vals, entry_count, "package.conflicts")
let conf_val = toml.toml_get(keys, vals, entry_count, "package.conflicts")
mut conf_arr: [string] = new [string](32)
let conf_count = parse_toml_array(conf_val, conf_arr, 32)
port.info.conflicts = conf_arr
port.info.conflicts_count = conf_count
end if
// Parse [dependencies] section
if toml.toml_has_key(keys, vals, entry_count, "dependencies.runtime")
let rt_val = toml.toml_get(keys, vals, entry_count, "dependencies.runtime")
mut rt_arr: [string] = new [string](64)
let rt_count = parse_toml_array(rt_val, rt_arr, 64)
port.deps.runtime = rt_arr
port.deps.runtime_count = rt_count
end if
if toml.toml_has_key(keys, vals, entry_count, "dependencies.build")
let bd_val = toml.toml_get(keys, vals, entry_count, "dependencies.build")
mut bd_arr: [string] = new [string](64)
let bd_count = parse_toml_array(bd_val, bd_arr, 64)
port.deps.build = bd_arr
port.deps.build_count = bd_count
end if
// Parse sources - try new [[source]] format first, fall back to legacy [sources]
port.sources = parse_sources(keys, vals, entry_count)
// Parse [patches] section
if toml.toml_has_key(keys, vals, entry_count, "patches.files")
let patch_val = toml.toml_get(keys, vals, entry_count, "patches.files")
mut patch_arr: [string] = new [string](32)
let patch_count = parse_toml_array(patch_val, patch_arr, 32)
port.patches.files = patch_arr
port.patches.count = patch_count
end if
if toml.toml_has_key(keys, vals, entry_count, "patches.strip")
port.patches.strip = toml.toml_get_int(keys, vals, entry_count, "patches.strip")
end if
// Parse [config] section
if toml.toml_has_key(keys, vals, entry_count, "config.files")
let cfg_val = toml.toml_get(keys, vals, entry_count, "config.files")
mut cfg_arr: [string] = new [string](32)
let cfg_count = parse_toml_array(cfg_val, cfg_arr, 32)
port.config.files = cfg_arr
port.config.count = cfg_count
end if
// Parse [scripts] section
if toml.toml_has_key(keys, vals, entry_count, "scripts.pre_install")
port.scripts.pre_install = toml.toml_get(keys, vals, entry_count, "scripts.pre_install")
end if
if toml.toml_has_key(keys, vals, entry_count, "scripts.post_install")
port.scripts.post_install = toml.toml_get(keys, vals, entry_count, "scripts.post_install")
end if
if toml.toml_has_key(keys, vals, entry_count, "scripts.pre_remove")
port.scripts.pre_remove = toml.toml_get(keys, vals, entry_count, "scripts.pre_remove")
end if
if toml.toml_has_key(keys, vals, entry_count, "scripts.post_remove")
port.scripts.post_remove = toml.toml_get(keys, vals, entry_count, "scripts.post_remove")
end if
// Parse [paths] section (per-package overrides)
if toml.toml_has_key(keys, vals, entry_count, "paths.prefix")
port.prefix = toml.toml_get(keys, vals, entry_count, "paths.prefix")
end if
if toml.toml_has_key(keys, vals, entry_count, "paths.sysconfdir")
port.sysconfdir = toml.toml_get(keys, vals, entry_count, "paths.sysconfdir")
end if
// Parse [build] section
if toml.toml_has_key(keys, vals, entry_count, "build.parallel")
port.build_cfg.parallel = toml.toml_get_bool(keys, vals, entry_count, "build.parallel")
end if
if toml.toml_has_key(keys, vals, entry_count, "build.jobs")
port.build_cfg.jobs = toml.toml_get_int(keys, vals, entry_count, "build.jobs")
end if
// Validate required fields
if str.length(port.info.name) == 0
return types.new_port_result(false, port, "package.name is required")
end if
if str.length(port.info.version) == 0
return types.new_port_result(false, port, "package.version is required")
end if
return success_result(port)
end load
// Find a port by name, searching all categories
// Accepts both "kernel" (searches all categories) and "hammerhead/kernel" (direct category/name)
fn find(name: string): types.PortResult
let cfg = config.load()
let ports_dir = config.get_ports_dir(cfg)
// Check if ports directory exists
if not dir.dir_exists(ports_dir)
return error_result("Ports directory not found: " + ports_dir + " (check /etc/coral/coral.conf)")
end if
// Check if name contains a slash (category/name format)
let slash_idx = str.index_of(name, "/")
if slash_idx >= 0
let port_path = path.join_path(ports_dir, name)
if dir.dir_exists(port_path)
return load(port_path)
end if
return error_result("Port not found: " + name + " (searched " + ports_dir + "/" + name + ")")
end if
// Search all categories for the name
mut cats: [string] = new [string](32)
let cat_count = get_categories(cats, 32)
mut i = 0
while i < cat_count
let port_path = path.join_path(ports_dir, path.join_path(cats[i], name))
if dir.dir_exists(port_path)
return load(port_path)
end if
i = i + 1
end while
return error_result("Port not found: " + name + " (searched " + ports_dir + ")")
end find
// List all ports in a given category
fn list_category(category: string, names: [string], max_count: int): int
let cfg = config.load()
let cat_path = path.join_path(config.get_ports_dir(cfg), category)
if not dir.dir_exists(cat_path)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(cat_path), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Skip hidden files and non-directories
if str.length(entry) > 0 and entry[0] != '.'
let entry_path = path.join_path(cat_path, entry)
// Check if it's a valid port (has package.toml)
let toml_path = path.join_path(entry_path, "package.toml")
if file.fileExists(toml_path)
names[count] = entry
count = count + 1
end if
end if
i = i + 1
end while
return count
end list_category
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: portindex.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Ports index for fast port lookups
The ports index provides fast indexed access to port metadata
without parsing individual package.toml files from disk.
Index file: /var/lib/coral/db/ports.db
Format: Base64-encoded MsgPack (same as packages.db, files.db)
Rebuild triggers: coral sync, coral db rebuild, coral db init
Manual: coral ports cache rebuild
******************************************************************************/
module core.portindex
import types
import io.file
import io.dir
import io.path
import core.str
import core.port
import core.config
import encoding.msgpack
import encoding.base64
import core.result as res
export
type PortIndexEntry
type PortsIndex
// Rebuild the ports index from the ports tree
fn rebuild_port_index(): bool
// Check if ports.db exists
fn port_index_exists(): bool
// Load the ports index from disk
fn load_port_index(): PortsIndex
// Find a single port by name or category/name
fn find_port(name: string): PortIndexEntry
// Search ports by substring match on name + description
fn search_ports(term: string, results: [PortIndexEntry], max_count: int): int
// List all indexed ports
fn list_all_ports(entries: [PortIndexEntry], max_count: int): int
// Get count of indexed ports
fn get_port_count(): int
// Find ports that depend on a given package name
fn find_reverse_deps(name: string, results: [PortIndexEntry], max_count: int): int
end export
// ============================================================================
// Types
// ============================================================================
type PortIndexEntry = struct
name: string
category: string
version: string
release: int
description: string
port_dir: string
runtime_deps: [string]
runtime_dep_count: int
found: bool
end PortIndexEntry
type PortsIndex = struct
version: int
generated: string
port_count: int
entries: [PortIndexEntry]
loaded: bool
end PortsIndex
// ============================================================================
// Constants
// ============================================================================
const PORT_INDEX_VERSION: int = 1
const MAX_PORTS: int = 4096
// ============================================================================
// Path helpers
// ============================================================================
fn ports_db_path(): string
return types.get_index_dir() + "/ports.db"
end ports_db_path
// Get current timestamp as string
fn get_timestamp(): string
return "2026-02-19"
end get_timestamp
// ============================================================================
// Empty constructors
// ============================================================================
fn empty_port_index(): PortsIndex
return PortsIndex{
version: 0,
generated: "",
port_count: 0,
entries: new [PortIndexEntry](MAX_PORTS),
loaded: false
}
end empty_port_index
fn empty_port_entry(): PortIndexEntry
return PortIndexEntry{
name: "",
category: "",
version: "",
release: 0,
description: "",
port_dir: "",
runtime_deps: new [string](64),
runtime_dep_count: 0,
found: false
}
end empty_port_entry
// ============================================================================
// Buffer size estimation
// ============================================================================
fn estimate_buffer_size(port_count: int): int
// Header: ~100 bytes
// Per port: ~300 bytes (name, category, version, description, port_dir, deps)
return 100 + (port_count * 300)
end estimate_buffer_size
// ============================================================================
// MsgPack header size helpers (same as pkgdb.reef)
// ============================================================================
fn map_header_size(buf: [int], offset: int): int
let b = buf[offset] & 255
if (b & 0xF0) == 0x80
return 1
elif b == 0xDE
return 3
elif b == 0xDF
return 5
end if
return 1
end map_header_size
fn array_header_size(buf: [int], offset: int): int
let b = buf[offset] & 255
if (b & 0xF0) == 0x90
return 1
elif b == 0xDC
return 3
elif b == 0xDD
return 5
end if
return 1
end array_header_size
// ============================================================================
// Index existence check
// ============================================================================
fn port_index_exists(): bool
return file.fileExists(ports_db_path())
end port_index_exists
// ============================================================================
// Rebuild: scan all ports, serialize to ports.db
// ============================================================================
fn rebuild_port_index(): bool
// Ensure db directory exists
let db_dir = types.get_index_dir()
if not dir.dir_exists(db_dir)
dir.create_dir_all(db_dir)
end if
// Get all categories dynamically
mut cats: [string] = new [string](32)
let cat_count = port.get_categories(cats, 32)
// Collect all port entries
mut entries: [PortIndexEntry] = new [PortIndexEntry](MAX_PORTS)
mut total = 0
mut i = 0
while i < cat_count and total < MAX_PORTS
let category = cats[i]
mut port_names: [string] = new [string](256)
let port_count = port.list_category(category, port_names, 256)
mut j = 0
while j < port_count and total < MAX_PORTS
let result = port.load(get_port_path(category, port_names[j]))
if result.success
let p = result.port
mut entry = empty_port_entry()
entry.name = p.info.name
entry.category = p.category
entry.version = p.info.version
entry.release = p.info.release
entry.description = p.info.description
entry.port_dir = p.port_dir
entry.found = true
// Copy runtime deps
mut k = 0
while k < p.deps.runtime_count and k < 64
entry.runtime_deps[k] = p.deps.runtime[k]
k = k + 1
end while
entry.runtime_dep_count = p.deps.runtime_count
entries[total] = entry
total = total + 1
end if
j = j + 1
end while
i = i + 1
end while
// Serialize to MsgPack
let buf_size = estimate_buffer_size(total)
mut buf: [int] = new [int](buf_size)
let buf_len = serialize_port_index(entries, total, buf, buf_size)
if buf_len == 0
return false
end if
// Encode to base64 and write
let encoded = base64.base64_encode_bytes(buf, buf_len)
return res.is_ok(file.writeFile(ports_db_path(), encoded))
end rebuild_port_index
// Build a port path from category and name
fn get_port_path(category: string, name: string): string
let cfg = config.load()
let ports_dir = config.get_ports_dir(cfg)
return path.join_path(ports_dir, path.join_path(category, name))
end get_port_path
// ============================================================================
// Serialization
// ============================================================================
fn serialize_port_index(entries: [PortIndexEntry], count: int, buf: [int], max_size: int): int
mut pos = 0
// Pack map header (4 keys: version, generated, port_count, ports)
pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)
// version
pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
pos = pos + msgpack.msgpack_pack_int(PORT_INDEX_VERSION, buf, pos)
// generated
pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)
// port_count
pos = pos + msgpack.msgpack_pack_string("port_count", buf, pos)
pos = pos + msgpack.msgpack_pack_int(count, buf, pos)
// ports array
pos = pos + msgpack.msgpack_pack_string("ports", buf, pos)
pos = pos + msgpack.msgpack_pack_array_header(count, buf, pos)
mut i = 0
while i < count and pos < max_size - 2000
let entry = entries[i]
// Each port is a map with 7 keys
pos = pos + msgpack.msgpack_pack_map_header(7, buf, pos)
// name
pos = pos + msgpack.msgpack_pack_string("name", buf, pos)
pos = pos + msgpack.msgpack_pack_string(entry.name, buf, pos)
// category
pos = pos + msgpack.msgpack_pack_string("category", buf, pos)
pos = pos + msgpack.msgpack_pack_string(entry.category, buf, pos)
// version
pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
pos = pos + msgpack.msgpack_pack_string(entry.version, buf, pos)
// release
pos = pos + msgpack.msgpack_pack_string("release", buf, pos)
pos = pos + msgpack.msgpack_pack_int(entry.release, buf, pos)
// description
pos = pos + msgpack.msgpack_pack_string("description", buf, pos)
pos = pos + msgpack.msgpack_pack_string(entry.description, buf, pos)
// port_dir
pos = pos + msgpack.msgpack_pack_string("port_dir", buf, pos)
pos = pos + msgpack.msgpack_pack_string(entry.port_dir, buf, pos)
// runtime_deps (array of strings)
pos = pos + msgpack.msgpack_pack_string("runtime_deps", buf, pos)
pos = pos + msgpack.msgpack_pack_array_header(entry.runtime_dep_count, buf, pos)
mut d = 0
while d < entry.runtime_dep_count
pos = pos + msgpack.msgpack_pack_string(entry.runtime_deps[d], buf, pos)
d = d + 1
end while
i = i + 1
end while
return pos
end serialize_port_index
// ============================================================================
// Deserialization
// ============================================================================
fn load_port_index(): PortsIndex
mut index = empty_port_index()
let db_path = ports_db_path()
if not file.fileExists(db_path)
return index
end if
let encoded = res.unwrap_or(file.readFile(db_path), "")
if str.length(encoded) == 0
return index
end if
let buf_size = str.length(encoded)
mut buf: [int] = new [int](buf_size)
let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)
if buf_len == 0
return index
end if
mut offset = 0
// Expect map header
if not msgpack.msgpack_is_map(buf, offset)
return index
end if
let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
mut entry_idx = 0
while entry_idx < map_len and offset < buf_len
let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
if str.equals(key, "version")
index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "generated")
index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "port_count")
index.port_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(key, "ports")
// Parse ports array
let arr_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
offset = offset + array_header_size(buf, offset)
mut port_idx = 0
while port_idx < arr_len and port_idx < MAX_PORTS and offset < buf_len
let port_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
offset = offset + map_header_size(buf, offset)
mut entry = empty_port_entry()
entry.found = true
mut port_field = 0
while port_field < port_map_len and offset < buf_len
let field_key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
if str.equals(field_key, "name")
entry.name = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "category")
entry.category = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "version")
entry.version = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "release")
entry.release = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "description")
entry.description = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "port_dir")
entry.port_dir = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
elif str.equals(field_key, "runtime_deps")
// Parse deps array
let deps_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
offset = offset + array_header_size(buf, offset)
mut dep_idx = 0
while dep_idx < deps_len and dep_idx < 64 and offset < buf_len
entry.runtime_deps[dep_idx] = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
offset = offset + msgpack.msgpack_value_size(buf, offset)
dep_idx = dep_idx + 1
end while
entry.runtime_dep_count = dep_idx
else
offset = offset + msgpack.msgpack_value_size(buf, offset)
end if
port_field = port_field + 1
end while
index.entries[port_idx] = entry
port_idx = port_idx + 1
end while
else
offset = offset + msgpack.msgpack_value_size(buf, offset)
end if
entry_idx = entry_idx + 1
end while
index.loaded = true
return index
end load_port_index
// ============================================================================
// Query functions
// ============================================================================
// Find a single port by name or category/name
fn find_port(name: string): PortIndexEntry
let index = load_port_index()
if not index.loaded
return empty_port_entry()
end if
// Check if name contains a slash (category/name format)
let slash_idx = str.index_of(name, "/")
mut i = 0
while i < index.port_count
let entry = index.entries[i]
if slash_idx >= 0
// Match category/name format
let full_name = entry.category + "/" + entry.name
// Also check directory-based name (category/dirname)
let dir_name = path.basename(entry.port_dir)
let full_dir_name = entry.category + "/" + dir_name
if str.equals(full_name, name) or str.equals(full_dir_name, name)
return entry
end if
else
// Match just the name
if str.equals(entry.name, name)
return entry
end if
end if
i = i + 1
end while
return empty_port_entry()
end find_port
// Search ports by substring match on name + description
fn search_ports(term: string, results: [PortIndexEntry], max_count: int): int
let index = load_port_index()
if not index.loaded
return 0
end if
let lower_term = str.to_lower(term)
mut count = 0
mut i = 0
while i < index.port_count and count < max_count
let entry = index.entries[i]
let lower_name = str.to_lower(entry.name)
let lower_desc = str.to_lower(entry.description)
if str.contains(lower_name, lower_term) or str.contains(lower_desc, lower_term)
results[count] = entry
count = count + 1
end if
i = i + 1
end while
return count
end search_ports
// List all indexed ports
fn list_all_ports(entries: [PortIndexEntry], max_count: int): int
let index = load_port_index()
if not index.loaded
return 0
end if
mut count = 0
while count < index.port_count and count < max_count
entries[count] = index.entries[count]
count = count + 1
end while
return count
end list_all_ports
// Get count of indexed ports
fn get_port_count(): int
let index = load_port_index()
if index.loaded
return index.port_count
end if
return 0
end get_port_count
// Find ports that have `name` in their runtime dependencies
fn find_reverse_deps(name: string, results: [PortIndexEntry], max_count: int): int
let index = load_port_index()
if not index.loaded
return 0
end if
mut count = 0
mut i = 0
while i < index.port_count and count < max_count
let entry = index.entries[i]
mut j = 0
while j < entry.runtime_dep_count
if str.equals(entry.runtime_deps[j], name)
results[count] = entry
count = count + 1
break
end if
j = j + 1
end while
i = i + 1
end while
return count
end find_reverse_deps
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: repository.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Repository manifest handling for binary package distribution
******************************************************************************/
module core.repository
import core.str
import io.file
import io.dir
import io.path
import encoding.toml
import util.http as uhttp
import util.color
import types
import core.result as res
export
type Repository
type RepoResult
type RemotePackage
type RemotePackageResult
fn load_repo(repo_path: string): RepoResult
fn list_repos(repos: [Repository], max_count: int): int
// Remote package operations
fn refresh_repo(repo: Repository): bool
fn find_remote_package(name: string): RemotePackageResult
fn download_package(pkg: RemotePackage): string
fn get_cached_manifest(repo: Repository): string
end export
// Repository definition
type Repository = struct
name: string
url: string
priority: int
enabled: bool
is_signed: bool
keyid: string
end Repository
// Result type for repository operations
type RepoResult = struct
success: bool
repo: Repository
error: string
end RepoResult
// Remote package from repository manifest
type RemotePackage = struct
name: string
version: string
release: int
description: string
license: string
category: string
depends: [string]
depends_count: int
size: int
compressed: int
filename: string
sha256: string
signature: string
repo_name: string
repo_url: string
end RemotePackage
// Result type for remote package search
type RemotePackageResult = struct
success: bool
pkg: RemotePackage
error: string
end RemotePackageResult
// Create empty repository
fn new_repository(): Repository
return Repository{ name: "", url: "", priority: 100, enabled: true, is_signed: false, keyid: "" }
end new_repository
// Create empty remote package
fn new_remote_package(): RemotePackage
return RemotePackage{
name: "",
version: "",
release: 0,
description: "",
license: "",
category: "",
depends: new [string](64),
depends_count: 0,
size: 0,
compressed: 0,
filename: "",
sha256: "",
signature: "",
repo_name: "",
repo_url: ""
}
end new_remote_package
// Create error result
fn error_result(msg: string): RepoResult
return RepoResult{ success: false, repo: new_repository(), error: msg }
end error_result
// Create package error result
fn pkg_error_result(msg: string): RemotePackageResult
return RemotePackageResult{ success: false, pkg: new_remote_package(), error: msg }
end pkg_error_result
// Create package success result
fn pkg_success_result(pkg: RemotePackage): RemotePackageResult
return RemotePackageResult{ success: true, pkg: pkg, error: "" }
end pkg_success_result
// Load a repository from a .repo file
fn load_repo(repo_path: string): RepoResult
if not file.fileExists(repo_path)
return error_result("Repository file not found: " + repo_path)
end if
let content = res.unwrap_or(file.readFile(repo_path), "")
if str.length(content) == 0
return error_result("Empty repository file: " + repo_path)
end if
// Parse TOML
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return error_result("Failed to parse repository file: " + repo_path)
end if
mut repo = new_repository()
// Read repository metadata
repo.name = toml.toml_get(keys, vals, entry_count, "repository.name")
repo.url = toml.toml_get(keys, vals, entry_count, "repository.url")
if toml.toml_has_key(keys, vals, entry_count, "repository.priority")
repo.priority = toml.toml_get_int(keys, vals, entry_count, "repository.priority")
end if
if toml.toml_has_key(keys, vals, entry_count, "repository.enabled")
repo.enabled = toml.toml_get_bool(keys, vals, entry_count, "repository.enabled")
end if
if toml.toml_has_key(keys, vals, entry_count, "repository.signed")
repo.is_signed = toml.toml_get_bool(keys, vals, entry_count, "repository.signed")
end if
if toml.toml_has_key(keys, vals, entry_count, "repository.keyid")
repo.keyid = toml.toml_get(keys, vals, entry_count, "repository.keyid")
end if
return RepoResult{ success: true, repo: repo, error: "" }
end load_repo
// List all configured repositories
fn list_repos(repos: [Repository], max_count: int): int
let repos_dir = "/etc/coral/repos.d"
if not dir.dir_exists(repos_dir)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(repos_dir), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Check for .repo extension
if str.ends_with(entry, ".repo")
let repo_path = path.join_path(repos_dir, entry)
let result = load_repo(repo_path)
if result.success
repos[count] = result.repo
count = count + 1
end if
end if
i = i + 1
end while
return count
end list_repos
// Get the path to cached manifest for a repository
fn get_cached_manifest(repo: Repository): string
let cache_dir = "/var/lib/coral/repos"
return path.join_path(cache_dir, repo.name + ".toml")
end get_cached_manifest
// Refresh repository metadata from remote
fn refresh_repo(repo: Repository): bool
if not repo.enabled
return false
end if
if str.length(repo.url) == 0
return false
end if
// Build URL to repo.toml
mut manifest_url = repo.url
if not str.ends_with(manifest_url, "/")
manifest_url = manifest_url + "/"
end if
manifest_url = manifest_url + "repo.toml"
// Ensure cache directory exists
let cache_dir = "/var/lib/coral/repos"
if not dir.dir_exists(cache_dir)
if not res.is_ok(dir.create_dir_all(cache_dir))
return false
end if
end if
// Download manifest
let cache_path = get_cached_manifest(repo)
return uhttp.download(manifest_url, cache_path)
end refresh_repo
// Find a package in all enabled repositories
fn find_remote_package(name: string): RemotePackageResult
// Get list of repositories
mut repos: [Repository] = new [Repository](16)
let repo_count = list_repos(repos, 16)
if repo_count == 0
return pkg_error_result("No repositories configured")
end if
// Search in each repository (by priority)
// TODO: Sort by priority
mut i = 0
while i < repo_count
let repo = repos[i]
if not repo.enabled
i = i + 1
continue
end if
let result = find_package_in_repo(name, repo)
if result.success
return result
end if
i = i + 1
end while
return pkg_error_result("Package not found in any repository: " + name)
end find_remote_package
// Find a package in a specific repository
fn find_package_in_repo(name: string, repo: Repository): RemotePackageResult
let cache_path = get_cached_manifest(repo)
// Check if we have cached manifest
if not file.fileExists(cache_path)
// Try to refresh
if not refresh_repo(repo)
return pkg_error_result("Failed to fetch repository manifest")
end if
end if
// Read cached manifest
let content = res.unwrap_or(file.readFile(cache_path), "")
if str.length(content) == 0
return pkg_error_result("Empty repository manifest")
end if
// Parse TOML to find the package
let keys = toml.toml_alloc_keys()
let vals = toml.toml_alloc_values()
let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)
if entry_count == 0
return pkg_error_result("Failed to parse repository manifest")
end if
// Look for package entry: packages.<name>
let pkg_key = "packages." + name
if not toml.toml_has_key(keys, vals, entry_count, pkg_key + ".version")
return pkg_error_result("Package not found: " + name)
end if
// Build RemotePackage
mut pkg = new_remote_package()
pkg.name = name
pkg.repo_name = repo.name
pkg.repo_url = repo.url
pkg.version = toml.toml_get(keys, vals, entry_count, pkg_key + ".version")
pkg.release = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".release")
pkg.description = toml.toml_get(keys, vals, entry_count, pkg_key + ".description")
pkg.license = toml.toml_get(keys, vals, entry_count, pkg_key + ".license")
pkg.category = toml.toml_get(keys, vals, entry_count, pkg_key + ".category")
pkg.filename = toml.toml_get(keys, vals, entry_count, pkg_key + ".file")
pkg.sha256 = toml.toml_get(keys, vals, entry_count, pkg_key + ".sha256")
pkg.signature = toml.toml_get(keys, vals, entry_count, pkg_key + ".signature")
if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".size")
pkg.size = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".size")
end if
if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".compressed")
pkg.compressed = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".compressed")
end if
// Parse depends array if present
if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".depends")
let deps_str = toml.toml_get(keys, vals, entry_count, pkg_key + ".depends")
pkg.depends_count = parse_toml_array(deps_str, pkg.depends, 64)
end if
// If filename is empty, construct it
if str.length(pkg.filename) == 0
pkg.filename = name + "-" + pkg.version + "-" + int_to_str(pkg.release) + ".x86_64.pkg.tar.xz"
end if
return pkg_success_result(pkg)
end find_package_in_repo
// Download a package to local cache
fn download_package(pkg: RemotePackage): string
if str.length(pkg.filename) == 0
color.print_error("Package has no filename")
return ""
end if
// Build download URL
mut base_url = pkg.repo_url
if not str.ends_with(base_url, "/")
base_url = base_url + "/"
end if
let pkg_url = base_url + "packages/" + pkg.filename
// Ensure packages cache directory exists
let cache_dir = types.get_packages_dir()
if not dir.dir_exists(cache_dir)
if not res.is_ok(dir.create_dir_all(cache_dir))
color.print_error("Failed to create packages cache directory")
return ""
end if
end if
// Download to cache
let dest_path = path.join_path(cache_dir, pkg.filename)
// Check if already cached
if file.fileExists(dest_path)
color.print_info("Using cached: " + pkg.filename)
return dest_path
end if
// Download
color.print_info("Downloading: " + pkg.filename)
if not uhttp.download(pkg_url, dest_path)
return ""
end if
return dest_path
end download_package
// Parse TOML array value into string array
fn parse_toml_array(value: string, result: [string], max_items: int): int
let len = str.length(value)
if len < 2
return 0
end if
if value[0] != '['
return 0
end if
mut count = 0
mut i = 1
mut in_string = false
mut item_start = 0
while i < len and count < max_items
let c = value[i]
if c == '"' and not in_string
in_string = true
item_start = i + 1
elif c == '"' and in_string
let item_len = i - item_start
if item_len > 0
result[count] = str.substring(value, item_start, item_len)
count = count + 1
end if
in_string = false
elif c == ']' and not in_string
return count
end if
i = i + 1
end while
return count
end parse_toml_array
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: resolver.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Dependency resolution for package installation
******************************************************************************/
module core.resolver
import core.str
import io.file
import io.path
import types
import core.port
import core.database
import util.version as ver
export
type ResolveResult
fn resolve(name: string): ResolveResult
fn get_install_order(names: [string], name_count: int, result: [string], max_count: int): int
fn get_dep_tree(name: string, deps: [string], max_count: int): int
// Build dependency resolver (resolves both runtime + build deps recursively from source)
fn resolve_build_deps(name: string): ResolveResult
// Root-aware version for alternate root installation
fn get_install_order_rooted(names: [string], name_count: int, result: [string], max_count: int, root: string): int
end export
// Result for alternative resolution
type AlternativeChoice = struct
satisfied: bool // True if an alternative is already installed
provider: string // The installed provider (if satisfied)
options: [string] // Available options to choose from
option_count: int
base_dep: string // The base dependency name
end AlternativeChoice
// Resolution result
type ResolveResult = struct
success: bool
packages: [string]
count: int
error: string
end ResolveResult
// Create an empty result
fn new_result(): ResolveResult
mut packages: [string] = new [string](256)
return ResolveResult{ success: false, packages: packages, count: 0, error: "" }
end new_result
// Resolve dependencies for a package
// Returns ordered list of packages to install (dependencies first)
fn resolve(name: string): ResolveResult
mut result = new_result()
// Track visited to detect cycles
mut visited: [string] = new [string](256)
mut visited_count = 0
// Track resolution order
mut order: [string] = new [string](256)
mut order_count = 0
// Resolve recursively
let ok = resolve_recursive(name, visited, visited_count, order, order_count)
if not ok.success
result.error = ok.error
return result
end if
result.success = true
result.packages = ok.packages
result.count = ok.count
return result
end resolve
// Internal result for recursive resolution
type RecurseResult = struct
success: bool
packages: [string]
count: int
error: string
end RecurseResult
fn new_recurse_result(): RecurseResult
mut packages: [string] = new [string](256)
return RecurseResult{ success: true, packages: packages, count: 0, error: "" }
end new_recurse_result
fn resolve_recursive(name: string, visited: [string], visited_count: int, order: [string], order_count: int): RecurseResult
mut result = new_recurse_result()
result.packages = order
result.count = order_count
// Check for cycle
if array_contains(visited, visited_count, name)
// Already visited - skip
result.success = true
return result
end if
// Mark as visited
visited[visited_count] = name
let new_visited_count = visited_count + 1
// Find the port
let port_result = port.find(name)
if not port_result.success
// Check if already installed
if database.is_installed(name)
result.success = true
return result
end if
// Check if an alternative provider exists
let provider = database.find_provider(name)
if str.length(provider) > 0
// Alternative already installed
result.success = true
return result
end if
result.success = false
result.error = "Port not found: " + name
return result
end if
let p = port_result.port
let pkg_name = p.info.name
// Resolve runtime dependencies first
mut i = 0
while i < p.deps.runtime_count
let dep = p.deps.runtime[i]
// Check if this is an alternative dependency
if is_alternative_dep(dep)
let alt_choice = resolve_alternative(dep)
if alt_choice.satisfied
// An alternative is already installed, skip
i = i + 1
continue
end if
// No alternative installed - pick the first option
// In a full implementation, we'd prompt the user here
if alt_choice.option_count > 0
let chosen = alt_choice.options[0]
if not array_contains(result.packages, result.count, chosen)
let dep_result = resolve_recursive(chosen, visited, new_visited_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
else
// Regular dependency — may include version constraint (e.g., "libfoo>=1.0")
let constraint = ver.parse_dep_constraint(dep)
let dep_name = ver.constraint_name(constraint)
if database.is_installed(dep_name)
// Installed — check version constraint if present
if ver.has_constraint(constraint)
let installed_pkg = database.get_installed(dep_name)
if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
// Installed version doesn't satisfy constraint — needs upgrade
if not array_contains(result.packages, result.count, dep_name)
let dep_result = resolve_recursive(dep_name, visited, new_visited_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
end if
// No constraint or constraint satisfied — skip
else
// Not installed — resolve it
if not array_contains(result.packages, result.count, dep_name)
let dep_result = resolve_recursive(dep_name, visited, new_visited_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
end if
i = i + 1
end while
// Add this package to order (after its dependencies)
// Use canonical name from package.toml, not the raw search argument
if not array_contains(result.packages, result.count, pkg_name)
// Skip if already installed
if not database.is_installed(pkg_name)
result.packages[result.count] = pkg_name
result.count = result.count + 1
end if
end if
result.success = true
return result
end resolve_recursive
// Get install order for multiple packages
fn get_install_order(names: [string], name_count: int, result: [string], max_count: int): int
mut order_count = 0
mut i = 0
while i < name_count
let name = names[i]
let resolve_result = resolve(name)
if resolve_result.success
// Add resolved packages to result
mut j = 0
while j < resolve_result.count and order_count < max_count
let pkg = resolve_result.packages[j]
// Avoid duplicates
if not array_contains(result, order_count, pkg)
result[order_count] = pkg
order_count = order_count + 1
end if
j = j + 1
end while
end if
i = i + 1
end while
return order_count
end get_install_order
// Get dependency tree for display (with indentation info)
fn get_dep_tree(name: string, deps: [string], max_count: int): int
mut count = 0
collect_deps(name, deps, count, 0, max_count)
return count
end get_dep_tree
// Collect dependencies recursively
fn collect_deps(name: string, deps: [string], count: int, depth: int, max_count: int): int
if depth > 20 or count >= max_count
return count
end if
let result = port.find(name)
if not result.success
return count
end if
let p = result.port
mut current_count = count
mut i = 0
while i < p.deps.runtime_count and current_count < max_count
let dep = p.deps.runtime[i]
// Add with depth prefix (number of spaces = depth * 2)
let indent = make_indent(depth)
deps[current_count] = indent + dep
current_count = current_count + 1
// Recurse
current_count = collect_deps(dep, deps, current_count, depth + 1, max_count)
i = i + 1
end while
return current_count
end collect_deps
// Create indentation string
fn make_indent(depth: int): string
if depth == 0
return ""
end if
mut result = ""
mut i = 0
while i < depth
result = result + " "
i = i + 1
end while
return result
end make_indent
// Check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
mut i = 0
while i < count
if arr[i] == s
return true
end if
i = i + 1
end while
return false
end array_contains
// Check if a dependency string represents alternatives (format: dep:opt1,opt2,opt3)
fn is_alternative_dep(dep: string): bool
return str.contains(dep, ":")
end is_alternative_dep
// Parse alternative options from a dependency string
// Format: base_dep:alt1,alt2,alt3
// Returns number of alternatives parsed, fills alternatives array
fn parse_alternatives(dep: string, alternatives: [string], max_count: int): int
let colon_pos = str.index_of_char(dep, ':')
if colon_pos < 0
// Not an alternative, return the single dependency
alternatives[0] = dep
return 1
end if
// Get the alternatives part after the colon
let alts_part = str.substring(dep, colon_pos + 1, str.length(dep) - colon_pos - 1)
// Split by comma
return str.split(alts_part, ',', alternatives, max_count)
end parse_alternatives
// Get the base dependency name from an alternative string
fn get_base_dep(dep: string): string
let colon_pos = str.index_of_char(dep, ':')
if colon_pos < 0
return dep
end if
return str.substring(dep, 0, colon_pos)
end get_base_dep
// Create empty AlternativeChoice
fn new_alternative_choice(): AlternativeChoice
return AlternativeChoice{
satisfied: false,
provider: "",
options: new [string](16),
option_count: 0,
base_dep: ""
}
end new_alternative_choice
// Resolve an alternative dependency
// Returns satisfied=true if any option is already installed
// Otherwise returns the list of available options
fn resolve_alternative(dep: string): AlternativeChoice
mut choice = new_alternative_choice()
if not is_alternative_dep(dep)
// Regular dependency
choice.base_dep = dep
choice.options[0] = dep
choice.option_count = 1
// Check if installed
if database.is_installed(dep)
choice.satisfied = true
choice.provider = dep
end if
return choice
end if
// Parse the alternatives
choice.base_dep = get_base_dep(dep)
choice.option_count = parse_alternatives(dep, choice.options, 16)
// Check if any alternative is already installed
mut i = 0
while i < choice.option_count
let opt = choice.options[i]
if database.is_installed(opt)
choice.satisfied = true
choice.provider = opt
return choice
end if
i = i + 1
end while
// Check if any provides this via alternatives
let provider = database.find_provider(choice.base_dep)
if str.length(provider) > 0
choice.satisfied = true
choice.provider = provider
return choice
end if
return choice
end resolve_alternative
// ============================================================================
// Build dependency resolver (resolves both runtime + build deps from source)
// ============================================================================
// Resolve all dependencies needed to build a package from source.
// Returns topological order: dependencies first, target package last.
// Resolves both runtime and build deps recursively.
// Uses proper cycle detection with separate visited/in_stack arrays.
fn resolve_build_deps(name: string): ResolveResult
mut result = new_result()
// Permanent marks: fully resolved packages
mut visited: [string] = new [string](256)
mut visited_count = 0
// Temporary marks: packages on the current DFS stack (for cycle detection)
mut in_stack: [string] = new [string](256)
mut stack_count = 0
// Topological build order
mut order: [string] = new [string](256)
mut order_count = 0
let ok = resolve_build_recursive(name, visited, visited_count, in_stack, stack_count, order, order_count)
if not ok.success
result.error = ok.error
return result
end if
result.success = true
result.packages = ok.packages
result.count = ok.count
return result
end resolve_build_deps
fn resolve_build_recursive(name: string, visited: [string], visited_count: int,
in_stack: [string], stack_count: int,
order: [string], order_count: int): RecurseResult
mut result = new_recurse_result()
result.packages = order
result.count = order_count
// Permanent mark: already fully resolved, skip
if array_contains(visited, visited_count, name)
result.success = true
return result
end if
// Temporary mark: cycle detected
if array_contains(in_stack, stack_count, name)
result.success = false
result.error = "Circular dependency detected: " + name
return result
end if
// If already installed, mark visited and skip (don't need to build)
if database.is_installed(name)
visited[visited_count] = name
result.success = true
return result
end if
// Find the port (must exist to build from source)
let port_result = port.find(name)
if not port_result.success
// Check if a provider is already installed
let provider = database.find_provider(name)
if str.length(provider) > 0
visited[visited_count] = name
result.success = true
return result
end if
result.success = false
result.error = "Port not found: " + name
return result
end if
let p = port_result.port
let pkg_name = p.info.name
// Push onto DFS stack (temporary mark)
in_stack[stack_count] = name
let new_stack_count = stack_count + 1
// Mark as visited (permanent mark)
visited[visited_count] = name
let new_visited_count = visited_count + 1
// Recurse into RUNTIME deps
mut i = 0
while i < p.deps.runtime_count
let dep = p.deps.runtime[i]
if is_alternative_dep(dep)
let alt_choice = resolve_alternative(dep)
if not alt_choice.satisfied and alt_choice.option_count > 0
let chosen = alt_choice.options[0]
let dep_result = resolve_build_recursive(chosen, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
else
let constraint = ver.parse_dep_constraint(dep)
let dep_name = ver.constraint_name(constraint)
mut needs_build = false
if database.is_installed(dep_name)
// Check version constraint
if ver.has_constraint(constraint)
let installed_pkg = database.get_installed(dep_name)
if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
needs_build = true
end if
end if
else
needs_build = true
end if
if needs_build
let dep_result = resolve_build_recursive(dep_name, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
i = i + 1
end while
// Recurse into BUILD deps
i = 0
while i < p.deps.build_count
let dep = p.deps.build[i]
if is_alternative_dep(dep)
let alt_choice = resolve_alternative(dep)
if not alt_choice.satisfied and alt_choice.option_count > 0
let chosen = alt_choice.options[0]
let dep_result = resolve_build_recursive(chosen, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
else
let constraint = ver.parse_dep_constraint(dep)
let dep_name = ver.constraint_name(constraint)
mut needs_build = false
if database.is_installed(dep_name)
if ver.has_constraint(constraint)
let installed_pkg = database.get_installed(dep_name)
if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
needs_build = true
end if
end if
else
needs_build = true
end if
if needs_build
let dep_result = resolve_build_recursive(dep_name, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
i = i + 1
end while
// Post-order: add this package AFTER all its deps (topological sort)
if not array_contains(result.packages, result.count, pkg_name)
result.packages[result.count] = pkg_name
result.count = result.count + 1
end if
result.success = true
return result
end resolve_build_recursive
// ============================================================================
// Root-aware resolver functions for alternate root installation
// ============================================================================
// Internal result for rooted recursive resolution
type RootedRecurseResult = struct
success: bool
packages: [string]
count: int
error: string
end RootedRecurseResult
fn new_rooted_recurse_result(): RootedRecurseResult
mut packages: [string] = new [string](256)
return RootedRecurseResult{ success: true, packages: packages, count: 0, error: "" }
end new_rooted_recurse_result
// Resolve dependencies checking against a specific root
fn resolve_recursive_rooted(name: string, visited: [string], visited_count: int, order: [string], order_count: int, root: string): RootedRecurseResult
mut result = new_rooted_recurse_result()
result.packages = order
result.count = order_count
// Check for cycle
if array_contains(visited, visited_count, name)
result.success = true
return result
end if
// Mark as visited
visited[visited_count] = name
let new_visited_count = visited_count + 1
// Find the port
let port_result = port.find(name)
if not port_result.success
// Check if already installed in target root
if database.is_installed_rooted(name, root)
result.success = true
return result
end if
// Check if an alternative provider exists in target root
// Note: find_provider doesn't have rooted version yet, skip for now
result.success = false
result.error = "Port not found: " + name
return result
end if
let p = port_result.port
let pkg_name = p.info.name
// Resolve runtime dependencies first
mut i = 0
while i < p.deps.runtime_count
let dep = p.deps.runtime[i]
// Skip alternative deps for now (simplification)
if not is_alternative_dep(dep)
// Parse version constraint if present
let constraint = ver.parse_dep_constraint(dep)
let dep_name = ver.constraint_name(constraint)
if database.is_installed_rooted(dep_name, root)
// Check version constraint if present
if ver.has_constraint(constraint)
let installed_pkg = database.get_installed_rooted(dep_name, root)
if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
// Needs upgrade
let dep_result = resolve_recursive_rooted(dep_name, visited, new_visited_count, result.packages, result.count, root)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
else
let dep_result = resolve_recursive_rooted(dep_name, visited, new_visited_count, result.packages, result.count, root)
if not dep_result.success
return dep_result
end if
result.packages = dep_result.packages
result.count = dep_result.count
end if
end if
i = i + 1
end while
// Add this package to order (after its dependencies)
// Use canonical name from package.toml, not the raw search argument
if not array_contains(result.packages, result.count, pkg_name)
// Skip if already installed in target root
if not database.is_installed_rooted(pkg_name, root)
result.packages[result.count] = pkg_name
result.count = result.count + 1
end if
end if
result.success = true
return result
end resolve_recursive_rooted
// Resolve for a single package with root support
fn resolve_rooted(name: string, root: string): ResolveResult
mut result = new_result()
mut visited: [string] = new [string](256)
mut visited_count = 0
mut order: [string] = new [string](256)
mut order_count = 0
let ok = resolve_recursive_rooted(name, visited, visited_count, order, order_count, root)
if not ok.success
result.error = ok.error
return result
end if
result.success = true
result.packages = ok.packages
result.count = ok.count
return result
end resolve_rooted
// Get install order for multiple packages, checking against target root
fn get_install_order_rooted(names: [string], name_count: int, result: [string], max_count: int, root: string): int
mut order_count = 0
mut i = 0
while i < name_count
let name = names[i]
let resolve_result = resolve_rooted(name, root)
if resolve_result.success
mut j = 0
while j < resolve_result.count and order_count < max_count
let pkg = resolve_result.packages[j]
if not array_contains(result, order_count, pkg)
result[order_count] = pkg
order_count = order_count + 1
end if
j = j + 1
end while
end if
i = i + 1
end while
return order_count
end get_install_order_rooted
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: signing.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Ed25519 signing and verification for packages and repositories
******************************************************************************/
module core.signing
import core.str
import io.file
import io.dir
import io.path
import sys.process
import core.result as res
export
type KeyPair
type SignResult
type VerifyResult
fn generate_keypair(name: string): SignResult
fn sign_file(file_path: string, key_path: string): SignResult
fn verify_file(file_path: string, sig_path: string, key_path: string): VerifyResult
fn import_key(key_data: string, name: string): SignResult
fn list_keys(keys: [KeyPair], max_count: int): int
fn get_keyring_dir(): string
fn get_trusted_keys_dir(): string
// High-level verification functions
fn verify_package(pkg_path: string, sig_path: string): VerifyResult
fn verify_manifest(manifest_path: string): VerifyResult
fn is_key_trusted(keyid: string): bool
end export
// Key pair information
type KeyPair = struct
name: string
keyid: string
public_key: string
private_key: string
created: string
trusted: bool
end KeyPair
// Result for signing operations
type SignResult = struct
success: bool
signature: string
error: string
end SignResult
// Result for verification
type VerifyResult = struct
success: bool
valid: bool
keyid: string
error: string
end VerifyResult
// Get the keyring directory
fn get_keyring_dir(): string
return "/etc/coral/keys"
end get_keyring_dir
// Create empty keypair
fn new_keypair(): KeyPair
return KeyPair{ name: "", keyid: "", public_key: "", private_key: "", created: "", trusted: false }
end new_keypair
// Create error result
fn error_sign_result(msg: string): SignResult
return SignResult{ success: false, signature: "", error: msg }
end error_sign_result
fn error_verify_result(msg: string): VerifyResult
return VerifyResult{ success: false, valid: false, keyid: "", error: msg }
end error_verify_result
// Generate a new Ed25519 keypair
// Note: This requires an external tool (openssl or signify)
fn generate_keypair(name: string): SignResult
let keyring = get_keyring_dir()
// Ensure keyring directory exists
if not dir.dir_exists(keyring)
if not res.is_ok(dir.create_dir_all(keyring))
return error_sign_result("Failed to create keyring directory")
end if
end if
let private_path = path.join_path(keyring, name + ".key")
let public_path = path.join_path(keyring, name + ".pub")
// Check if key already exists
if file.fileExists(private_path)
return error_sign_result("Key already exists: " + name)
end if
// Generate key using openssl
let cmd = "openssl genpkey -algorithm ed25519 -out \"" + private_path + "\" && " +
"openssl pkey -in \"" + private_path + "\" -pubout -out \"" + public_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return error_sign_result("Failed to start key generation")
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
return error_sign_result("Key generation failed")
end if
return SignResult{ success: true, signature: "", error: "" }
end generate_keypair
// Sign a file with Ed25519
fn sign_file(file_path: string, key_path: string): SignResult
if not file.fileExists(file_path)
return error_sign_result("File not found: " + file_path)
end if
if not file.fileExists(key_path)
return error_sign_result("Key not found: " + key_path)
end if
let sig_path = file_path + ".sig"
// Sign using openssl
let cmd = "openssl pkeyutl -sign -inkey \"" + key_path + "\" -in \"" + file_path + "\" -out \"" + sig_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return error_sign_result("Failed to start signing")
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
return error_sign_result("Signing failed")
end if
return SignResult{ success: true, signature: sig_path, error: "" }
end sign_file
// Verify a file signature
fn verify_file(file_path: string, sig_path: string, key_path: string): VerifyResult
if not file.fileExists(file_path)
return error_verify_result("File not found: " + file_path)
end if
if not file.fileExists(sig_path)
return error_verify_result("Signature not found: " + sig_path)
end if
if not file.fileExists(key_path)
return error_verify_result("Key not found: " + key_path)
end if
// Verify using openssl
let cmd = "openssl pkeyutl -verify -pubin -inkey \"" + key_path + "\" -in \"" + file_path + "\" -sigfile \"" + sig_path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return error_verify_result("Failed to start verification")
end if
let exit_code = process.process_wait(pid)
if exit_code == 0
return VerifyResult{ success: true, valid: true, keyid: "", error: "" }
else
return VerifyResult{ success: true, valid: false, keyid: "", error: "Signature verification failed" }
end if
end verify_file
// Import a public key
fn import_key(key_data: string, name: string): SignResult
let keyring = get_keyring_dir()
if not dir.dir_exists(keyring)
if not res.is_ok(dir.create_dir_all(keyring))
return error_sign_result("Failed to create keyring directory")
end if
end if
let key_path = path.join_path(keyring, name + ".pub")
if file.fileExists(key_path)
return error_sign_result("Key already exists: " + name)
end if
if not res.is_ok(file.writeFile(key_path, key_data))
return error_sign_result("Failed to write key file")
end if
return SignResult{ success: true, signature: "", error: "" }
end import_key
// List all keys in keyring
fn list_keys(keys: [KeyPair], max_count: int): int
let keyring = get_keyring_dir()
if not dir.dir_exists(keyring)
return 0
end if
let entries = res.unwrap_or(dir.list_dir(keyring), new [string](0))
let entry_count = entries.length()
mut count = 0
mut i = 0
while i < entry_count and count < max_count
let entry = entries[i]
// Look for .pub files
if str.ends_with(entry, ".pub")
let name_len = str.length(entry) - 4
let name = str.substring(entry, 0, name_len)
mut kp = new_keypair()
kp.name = name
kp.trusted = true // Local keys are trusted
// Read public key
let pub_path = path.join_path(keyring, entry)
kp.public_key = res.unwrap_or(file.readFile(pub_path), "")
// Check for private key
let priv_path = path.join_path(keyring, name + ".key")
if file.fileExists(priv_path)
kp.private_key = "(present)"
end if
keys[count] = kp
count = count + 1
end if
i = i + 1
end while
return count
end list_keys
// Get the trusted keys directory
fn get_trusted_keys_dir(): string
return "/var/lib/coral/trusted-keys"
end get_trusted_keys_dir
// Check if a key is in the trusted keys list
fn is_key_trusted(keyid: string): bool
let trusted_dir = get_trusted_keys_dir()
if not dir.dir_exists(trusted_dir)
return false
end if
// Look for key file by keyid
let key_path = path.join_path(trusted_dir, keyid + ".pub")
if file.fileExists(key_path)
return true
end if
// Also check the main keyring
let keyring_path = path.join_path(get_keyring_dir(), keyid + ".pub")
return file.fileExists(keyring_path)
end is_key_trusted
// Get path to a trusted key by keyid
fn get_trusted_key_path(keyid: string): string
// Try trusted-keys directory first
let trusted_dir = get_trusted_keys_dir()
let trusted_path = path.join_path(trusted_dir, keyid + ".pub")
if file.fileExists(trusted_path)
return trusted_path
end if
// Fall back to main keyring
let keyring_path = path.join_path(get_keyring_dir(), keyid + ".pub")
if file.fileExists(keyring_path)
return keyring_path
end if
return ""
end get_trusted_key_path
// Verify a package with any trusted key
fn verify_package(pkg_path: string, sig_path: string): VerifyResult
if not file.fileExists(pkg_path)
return error_verify_result("Package not found: " + pkg_path)
end if
if not file.fileExists(sig_path)
return error_verify_result("Signature not found: " + sig_path)
end if
// Try to verify with each trusted key
let trusted_dir = get_trusted_keys_dir()
let keyring_dir = get_keyring_dir()
// Collect all public keys from both directories
mut all_keys: [string] = new [string](64)
mut key_count = 0
// Get keys from trusted-keys directory
if dir.dir_exists(trusted_dir)
let entries = res.unwrap_or(dir.list_dir(trusted_dir), new [string](0))
let entry_count = entries.length()
mut i = 0
while i < entry_count and key_count < 64
if str.ends_with(entries[i], ".pub")
all_keys[key_count] = path.join_path(trusted_dir, entries[i])
key_count = key_count + 1
end if
i = i + 1
end while
end if
// Get keys from keyring directory
if dir.dir_exists(keyring_dir)
let entries = res.unwrap_or(dir.list_dir(keyring_dir), new [string](0))
let entry_count = entries.length()
mut i = 0
while i < entry_count and key_count < 64
if str.ends_with(entries[i], ".pub")
let key_path = path.join_path(keyring_dir, entries[i])
// Avoid duplicates
mut is_dup = false
mut j = 0
while j < key_count
if str.equals(all_keys[j], key_path)
is_dup = true
end if
j = j + 1
end while
if not is_dup
all_keys[key_count] = key_path
key_count = key_count + 1
end if
end if
i = i + 1
end while
end if
if key_count == 0
return error_verify_result("No trusted keys found")
end if
// Try each key
mut i = 0
while i < key_count
let key_path = all_keys[i]
let result = verify_file(pkg_path, sig_path, key_path)
if result.success and result.valid
// Extract keyid from path
let filename = path.basename(key_path)
let keyid = str.substring(filename, 0, str.length(filename) - 4)
return VerifyResult{ success: true, valid: true, keyid: keyid, error: "" }
end if
i = i + 1
end while
return VerifyResult{ success: true, valid: false, keyid: "", error: "Signature does not match any trusted key" }
end verify_package
// Verify a repository manifest (repo.toml and repo.toml.sig)
fn verify_manifest(manifest_path: string): VerifyResult
if not file.fileExists(manifest_path)
return error_verify_result("Manifest not found: " + manifest_path)
end if
let sig_path = manifest_path + ".sig"
if not file.fileExists(sig_path)
return error_verify_result("Manifest signature not found: " + sig_path)
end if
return verify_package(manifest_path, sig_path)
end verify_manifest
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: exitcodes.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Exit code constants for Coral package manager
******************************************************************************/
module exitcodes
export
// Success
fn EXIT_SUCCESS(): int
// General errors (1-9)
fn EXIT_ERROR(): int
fn EXIT_USAGE(): int
fn EXIT_CANCELLED(): int
// Package errors (10-19)
fn EXIT_PKG_NOT_FOUND(): int
fn EXIT_PKG_ALREADY_INSTALLED(): int
fn EXIT_PKG_INVALID(): int
fn EXIT_PKG_CHECKSUM_MISMATCH(): int
fn EXIT_PKG_SIGNATURE_INVALID(): int
fn EXIT_PKG_CONFLICT(): int
fn EXIT_INSTALL_FAILED(): int
fn EXIT_REMOVE_FAILED(): int
fn EXIT_UPGRADE_FAILED(): int
// Build errors (20-29)
fn EXIT_BUILD_FAILED(): int
fn EXIT_PORT_NOT_FOUND(): int
fn EXIT_SOURCE_MISSING(): int
fn EXIT_PATCH_FAILED(): int
fn EXIT_EXTRACT_FAILED(): int
fn EXIT_CHECKSUM_FAILED(): int
fn EXIT_PACKAGE_FAILED(): int
// Network errors (30-39)
fn EXIT_DOWNLOAD_FAILED(): int
fn EXIT_REPO_UNREACHABLE(): int
fn EXIT_TIMEOUT(): int
// Database errors (40-49)
fn EXIT_DB_ERROR(): int
fn EXIT_DB_REGISTER_FAILED(): int
fn EXIT_DB_CORRUPT(): int
fn EXIT_DB_INDEX_STALE(): int
// Permission errors (50-59)
fn EXIT_PERMISSION_DENIED(): int
fn EXIT_ROOT_REQUIRED(): int
// Dependency errors (60-69)
fn EXIT_DEPS_UNMET(): int
fn EXIT_DEPS_CIRCULAR(): int
fn EXIT_DEPS_CONFLICT(): int
fn EXIT_DEPS_BLOCKED(): int
// Config errors (70-79)
fn EXIT_CONFIG_ERROR(): int
fn EXIT_CONFIG_INVALID(): int
fn EXIT_CONFIG_MISSING(): int
// Informational codes for scripting (100+)
fn EXIT_UPDATE_AVAILABLE(): int
fn EXIT_MANIFEST_STALE(): int
fn EXIT_NO_UPDATES(): int
end export
// ============================================================================
// Success (0)
// ============================================================================
fn EXIT_SUCCESS(): int
return 0
end EXIT_SUCCESS
// ============================================================================
// General Errors (1-9)
// ============================================================================
fn EXIT_ERROR(): int
return 1
end EXIT_ERROR
fn EXIT_USAGE(): int
return 2
end EXIT_USAGE
fn EXIT_CANCELLED(): int
return 3
end EXIT_CANCELLED
// ============================================================================
// Package Errors (10-19)
// ============================================================================
fn EXIT_PKG_NOT_FOUND(): int
return 10
end EXIT_PKG_NOT_FOUND
fn EXIT_PKG_ALREADY_INSTALLED(): int
return 11
end EXIT_PKG_ALREADY_INSTALLED
fn EXIT_PKG_INVALID(): int
return 12
end EXIT_PKG_INVALID
fn EXIT_PKG_CHECKSUM_MISMATCH(): int
return 13
end EXIT_PKG_CHECKSUM_MISMATCH
fn EXIT_PKG_SIGNATURE_INVALID(): int
return 14
end EXIT_PKG_SIGNATURE_INVALID
fn EXIT_PKG_CONFLICT(): int
return 15
end EXIT_PKG_CONFLICT
fn EXIT_INSTALL_FAILED(): int
return 16
end EXIT_INSTALL_FAILED
fn EXIT_REMOVE_FAILED(): int
return 17
end EXIT_REMOVE_FAILED
fn EXIT_UPGRADE_FAILED(): int
return 18
end EXIT_UPGRADE_FAILED
// ============================================================================
// Build Errors (20-29)
// ============================================================================
fn EXIT_BUILD_FAILED(): int
return 20
end EXIT_BUILD_FAILED
fn EXIT_PORT_NOT_FOUND(): int
return 21
end EXIT_PORT_NOT_FOUND
fn EXIT_SOURCE_MISSING(): int
return 22
end EXIT_SOURCE_MISSING
fn EXIT_PATCH_FAILED(): int
return 23
end EXIT_PATCH_FAILED
fn EXIT_EXTRACT_FAILED(): int
return 24
end EXIT_EXTRACT_FAILED
fn EXIT_CHECKSUM_FAILED(): int
return 25
end EXIT_CHECKSUM_FAILED
fn EXIT_PACKAGE_FAILED(): int
return 26
end EXIT_PACKAGE_FAILED
// ============================================================================
// Network Errors (30-39)
// ============================================================================
fn EXIT_DOWNLOAD_FAILED(): int
return 30
end EXIT_DOWNLOAD_FAILED
fn EXIT_REPO_UNREACHABLE(): int
return 31
end EXIT_REPO_UNREACHABLE
fn EXIT_TIMEOUT(): int
return 32
end EXIT_TIMEOUT
// ============================================================================
// Database Errors (40-49)
// ============================================================================
fn EXIT_DB_ERROR(): int
return 40
end EXIT_DB_ERROR
fn EXIT_DB_REGISTER_FAILED(): int
return 41
end EXIT_DB_REGISTER_FAILED
fn EXIT_DB_CORRUPT(): int
return 42
end EXIT_DB_CORRUPT
fn EXIT_DB_INDEX_STALE(): int
return 43
end EXIT_DB_INDEX_STALE
// ============================================================================
// Permission Errors (50-59)
// ============================================================================
fn EXIT_PERMISSION_DENIED(): int
return 50
end EXIT_PERMISSION_DENIED
fn EXIT_ROOT_REQUIRED(): int
return 51
end EXIT_ROOT_REQUIRED
// ============================================================================
// Dependency Errors (60-69)
// ============================================================================
fn EXIT_DEPS_UNMET(): int
return 60
end EXIT_DEPS_UNMET
fn EXIT_DEPS_CIRCULAR(): int
return 61
end EXIT_DEPS_CIRCULAR
fn EXIT_DEPS_CONFLICT(): int
return 62
end EXIT_DEPS_CONFLICT
fn EXIT_DEPS_BLOCKED(): int
return 63
end EXIT_DEPS_BLOCKED
// ============================================================================
// Config Errors (70-79)
// ============================================================================
fn EXIT_CONFIG_ERROR(): int
return 70
end EXIT_CONFIG_ERROR
fn EXIT_CONFIG_INVALID(): int
return 71
end EXIT_CONFIG_INVALID
fn EXIT_CONFIG_MISSING(): int
return 72
end EXIT_CONFIG_MISSING
// ============================================================================
// Informational Codes for Scripting (100+)
// ============================================================================
fn EXIT_UPDATE_AVAILABLE(): int
return 100
end EXIT_UPDATE_AVAILABLE
fn EXIT_MANIFEST_STALE(): int
return 101
end EXIT_MANIFEST_STALE
fn EXIT_NO_UPDATES(): int
return 102
end EXIT_NO_UPDATES
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: main.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Entry point for Coral package manager
******************************************************************************/
import sys.args
import sys.process
import sys.env
import io.dir
import core.str
import types
import exitcodes as ec
import commands.build as cmd_build
import commands.install as cmd_install
import commands.remove as cmd_remove
import commands.upgrade as cmd_upgrade
import commands.info as cmd_info
import commands.list as cmd_list
import commands.files as cmd_files
import commands.owner as cmd_owner
import commands.search as cmd_search
import commands.depends as cmd_depends
import commands.sync as cmd_sync
import commands.outdated as cmd_outdated
import commands.repo as cmd_repo
import commands.key as cmd_key
import commands.db as cmd_db
import commands.clean as cmd_clean
import commands.ports as cmd_ports
import commands.verify as cmd_verify
import util.color
import util.priv
fn version(): string
return "0.4.5"
end version
proc print_usage()
println("coral " + version() + " - Package manager for Zygaena")
println("")
println("USAGE:")
println(" coral <command> [options] [packages...]")
println("")
println("COMMANDS:")
println(" Package Management:")
println(" install <pkg> Install packages")
println(" reinstall <pkg> Reinstall packages (same as install --force)")
println(" remove <pkg> Remove packages")
println(" upgrade Upgrade packages")
println("")
println(" Query Commands:")
println(" info <pkg> Show package info")
println(" list List installed packages")
println(" files <pkg> List package files")
println(" owner <file> Find file owner")
println(" search <term> Search packages")
println(" depends <pkg> Show dependencies")
println(" outdated Show available updates")
println(" verify <pkg> Verify package integrity")
println("")
println(" Build Commands:")
println(" build <port> Build package from port")
println(" sync Update ports tree")
println(" clean <target> Remove build artifacts (sources|packages|build|all)")
println("")
println(" System Commands:")
println(" db <cmd> Manage package database (init|rebuild|status)")
println(" ports <cmd> Port development tools (new|cache)")
println(" repo Manage repositories")
println(" key Manage signing keys")
println("")
println("OPTIONS:")
println(" -h, --help Show this help")
println(" --version Show version")
println(" -y, --yes Don't ask for confirmation")
println(" -f, --force Force operation")
println(" -v, --verbose Verbose output")
println(" -n, --dry-run Show what would be done")
println(" -q, --quiet Minimal output")
println(" --no-color Disable colored output")
println(" --root <path> Use alternative root directory")
println(" --prefix <path> Installation prefix (default: /usr)")
println(" --no-chroot-scripts Run maintainer scripts on the host, not chrooted")
println("")
println("EXIT CODES:")
println(" 0 Success")
println(" 1 General error")
println(" 2 Usage/syntax error")
println(" 10-19 Package errors")
println(" 20-29 Build errors")
println(" 30-39 Network errors")
println(" 50-59 Permission errors")
println(" 60-69 Dependency errors")
println(" 100+ Informational (scripting)")
end print_usage
// Find the index of the command argument, skipping global flags
fn find_command_index(): int
let argc = args.count()
mut i = 1
while i < argc
let arg = args.get(i)
// Skip flags that take a value
if arg == "--root" or arg == "--prefix"
i = i + 2 // Skip flag and its value
continue
end if
// Skip boolean flags
if arg == "-y" or arg == "--yes" or arg == "-f" or arg == "--force" or arg == "-v" or arg == "--verbose" or arg == "-n" or arg == "--dry-run" or arg == "-q" or arg == "--quiet" or arg == "--no-color" or arg == "--no-chroot-scripts"
i = i + 1
continue
end if
// Found the command
return i
end while
return -1
end find_command_index
// Parse global options from command line arguments
fn parse_global_options(): types.GlobalOptions
mut opts = types.new_global_options()
opts.yes = args.has_flag("y") or args.has_flag("yes")
opts.force = args.has_flag("f") or args.has_flag("force")
opts.verbose = args.has_flag("v") or args.has_flag("verbose")
opts.dry_run = args.has_flag("n") or args.has_flag("dry-run")
opts.quiet = args.has_flag("q") or args.has_flag("quiet")
// Check for --root option
if args.has_flag("root")
opts.root = args.get_flag_value("root")
end if
// Check for --prefix option
if args.has_flag("prefix")
opts.prefix = args.get_flag_value("prefix")
end if
// Check for --no-chroot-scripts option (valueless)
opts.no_chroot = args.has_flag("no-chroot-scripts")
return opts
end parse_global_options
// Check if a command is a query command (doesn't require root)
fn is_query_command(cmd: string): bool
// Query commands that don't modify the system
if cmd == "info"
return true
elif cmd == "list"
return true
elif cmd == "files"
return true
elif cmd == "owner"
return true
elif cmd == "search"
return true
elif cmd == "depends"
return true
elif cmd == "outdated"
return true
elif cmd == "verify"
return true
elif cmd == "build"
// Building packages doesn't require root - only writes to build directories
return true
elif cmd == "--help" or cmd == "-h"
return true
elif cmd == "--version" or cmd == "version"
return true
end if
return false
end is_query_command
fn main(): int
let argc = args.count()
if argc < 2
print_usage()
return ec.EXIT_USAGE()
end if
// Check for --help and --version before finding command
// (these can appear anywhere)
if args.has_flag("help") or args.has_flag("h")
print_usage()
return ec.EXIT_SUCCESS()
end if
if args.has_flag("version")
println("coral " + version())
return ec.EXIT_SUCCESS()
end if
// Find the actual command, skipping global flags
let cmd_index = find_command_index()
if cmd_index < 0
print_usage()
return ec.EXIT_USAGE()
end if
let cmd = args.get(cmd_index)
// Parse global options and set command index
mut opts = parse_global_options()
opts.cmd_index = cmd_index
// Check for root privileges if required
if not is_query_command(cmd)
if not priv.is_root()
color.print_error("This command requires root privileges")
println("Run 'coral " + cmd + "' as root or with sudo")
return ec.EXIT_ROOT_REQUIRED()
end if
end if
// Dispatch to command handlers
// Commands return exit codes
if cmd == "build"
return cmd_build.execute(opts)
elif cmd == "install"
return cmd_install.execute(opts)
elif cmd == "reinstall"
// Reinstall is install with force flag enabled
mut reinstall_opts = opts
reinstall_opts.force = true
return cmd_install.execute(reinstall_opts)
elif cmd == "remove"
return cmd_remove.execute(opts)
elif cmd == "upgrade"
return cmd_upgrade.execute(opts)
elif cmd == "info"
return cmd_info.execute(opts)
elif cmd == "list"
return cmd_list.execute(opts)
elif cmd == "files"
return cmd_files.execute(opts)
elif cmd == "owner"
return cmd_owner.execute(opts)
elif cmd == "search"
return cmd_search.execute()
elif cmd == "depends"
return cmd_depends.execute()
elif cmd == "sync"
return cmd_sync.execute()
elif cmd == "outdated"
return cmd_outdated.execute()
elif cmd == "repo"
return cmd_repo.execute()
elif cmd == "key"
return cmd_key.execute()
elif cmd == "db"
return cmd_db.execute(opts)
elif cmd == "clean"
return cmd_clean.execute()
elif cmd == "ports"
return cmd_ports.execute(opts)
elif cmd == "verify"
return cmd_verify.execute(opts)
elif cmd == "version"
println(version())
return ec.EXIT_SUCCESS()
else
color.print_error("unknown command '" + cmd + "'")
println("Run 'coral --help' for usage.")
return ec.EXIT_USAGE()
end if
end main
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: types.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Shared type definitions for Coral package manager
******************************************************************************/
module types
export
// Path getter functions (constants can't be exported across modules)
fn get_ports_dir(): string
fn get_sources_dir(): string
fn get_packages_dir(): string
fn get_build_dir(): string
fn get_db_dir(): string
fn get_index_dir(): string
fn get_repos_dir(): string
fn get_config_file(): string
fn get_groups_dir(): string
// Legacy (for compatibility)
fn get_work_dir(): string
fn get_pkg_dir(): string
// Types
type PackageInfo
type Dependencies
type Source
type SourceInfo
type PatchInfo
type ConfigInfo
type ScriptsInfo
type BuildConfig
type Port
type InstalledPackage
type BuildResult
type GlobalOptions
type PackageGroup
type PortResult
// Factory functions
fn new_package_info(): PackageInfo
fn new_dependencies(): Dependencies
fn new_global_options(): GlobalOptions
fn new_source(): Source
fn new_source_info(): SourceInfo
fn new_patch_info(): PatchInfo
fn new_config_info(): ConfigInfo
fn new_scripts_info(): ScriptsInfo
fn new_build_config(): BuildConfig
fn new_port(): Port
fn new_port_result(ok: bool, p: Port, err: string): PortResult
fn new_installed_package(): InstalledPackage
fn new_package_group(): PackageGroup
end export
// Zygaena/Coral filesystem paths
// Ports tree and build artifacts
const PORTS_DIR: string = "/usr/zports"
const GROUPS_DIR: string = "/usr/zports/groups"
const SOURCES_DIR: string = "/usr/zports/pkgs/sources"
const PACKAGES_DIR: string = "/usr/zports/pkgs/packages"
const BUILD_DIR: string = "/usr/zports/pkgs/build"
// System state (in /var/lib)
const DB_DIR: string = "/var/lib/coral/installed"
const INDEX_DIR: string = "/var/lib/coral/db"
const REPOS_DIR: string = "/var/lib/coral/repos"
// Configuration
const CONFIG_FILE: string = "/etc/coral/coral.conf"
// Legacy aliases (for compatibility during transition)
const WORK_DIR: string = "/usr/zports/pkgs/build"
const PKG_DIR: string = "/usr/zports/pkgs/build"
// Package metadata from package.toml
type PackageInfo = struct
name: string
version: string
release: int
description: string
url: string
license: string
maintainer: string
arch: string
alternatives: [string]
alternatives_count: int
conflicts: [string]
conflicts_count: int
runtime_deps: [string]
build_deps: [string]
runtime_deps_count: int
build_deps_count: int
end PackageInfo
// Dependencies
type Dependencies = struct
runtime: [string]
build: [string]
runtime_count: int
build_count: int
end Dependencies
// Individual source file with mirror support
type Source = struct
file: string // Output filename (what to save as)
urls: [string] // Mirror URLs (tried in order)
url_count: int // Number of URLs
checksum: string // SHA256 checksum (or "SKIP")
extract: bool // Whether to extract archive (default: true)
end Source
// Collection of source files to download
type SourceInfo = struct
sources: [Source] // Array of Source structs
count: int // Number of sources
end SourceInfo
// Patch configuration
type PatchInfo = struct
files: [string]
strip: int
count: int
end PatchInfo
// Config file protection
type ConfigInfo = struct
files: [string]
count: int
end ConfigInfo
// Install/remove scripts
type ScriptsInfo = struct
pre_install: string
post_install: string
pre_remove: string
post_remove: string
end ScriptsInfo
// Build configuration
type BuildConfig = struct
parallel: bool
jobs: int
end BuildConfig
// Complete port definition
type Port = struct
info: PackageInfo
deps: Dependencies
sources: SourceInfo
patches: PatchInfo
config: ConfigInfo
scripts: ScriptsInfo
build_cfg: BuildConfig
port_dir: string
category: string
// Per-package path overrides (from package.toml [paths] section)
prefix: string
sysconfdir: string
end Port
// Installed package record
type InstalledPackage = struct
info: PackageInfo
install_date: string
install_reason: string
files: [string]
files_count: int
end InstalledPackage
// Build result
type BuildResult = struct
success: bool
package_path: string
error_message: string
end BuildResult
// Global CLI options
type GlobalOptions = struct
yes: bool
force: bool
verbose: bool
dry_run: bool
quiet: bool
root: string
prefix: string
no_chroot: bool // --no-chroot-scripts: run maintainer scripts on the host, not chrooted
cmd_index: int // Index of the command in args (for subcommand parsing)
end GlobalOptions
// Package group (meta-package)
type PackageGroup = struct
name: string
description: string
members: [string]
members_count: int
end PackageGroup
// Parse result wrapper
type PortResult = struct
success: bool
port: Port
error: string
end PortResult
// Initialize empty PackageInfo
fn new_package_info(): PackageInfo
return PackageInfo{
name: "",
version: "",
release: 1,
description: "",
url: "",
license: "",
maintainer: "",
arch: "x86_64",
alternatives: new [string](0),
alternatives_count: 0,
conflicts: new [string](0),
conflicts_count: 0,
runtime_deps: new [string](64),
build_deps: new [string](64),
runtime_deps_count: 0,
build_deps_count: 0
}
end new_package_info
// Initialize empty Dependencies
fn new_dependencies(): Dependencies
return Dependencies{
runtime: new [string](0),
build: new [string](0),
runtime_count: 0,
build_count: 0
}
end new_dependencies
// Initialize empty GlobalOptions with defaults
fn new_global_options(): GlobalOptions
return GlobalOptions{
yes: false,
force: false,
verbose: false,
dry_run: false,
quiet: false,
root: "",
prefix: "",
no_chroot: false,
cmd_index: 1
}
end new_global_options
// Initialize empty Source
fn new_source(): Source
return Source{
file: "",
urls: new [string](16),
url_count: 0,
checksum: "SKIP",
extract: true
}
end new_source
// Initialize empty SourceInfo
fn new_source_info(): SourceInfo
return SourceInfo{
sources: new [Source](16),
count: 0
}
end new_source_info
// Initialize empty PatchInfo
fn new_patch_info(): PatchInfo
return PatchInfo{
files: new [string](0),
strip: 1,
count: 0
}
end new_patch_info
// Initialize empty ConfigInfo
fn new_config_info(): ConfigInfo
return ConfigInfo{
files: new [string](0),
count: 0
}
end new_config_info
// Initialize empty ScriptsInfo
fn new_scripts_info(): ScriptsInfo
return ScriptsInfo{
pre_install: "",
post_install: "",
pre_remove: "",
post_remove: ""
}
end new_scripts_info
// Initialize default BuildConfig
fn new_build_config(): BuildConfig
return BuildConfig{
parallel: true,
jobs: 0
}
end new_build_config
// Initialize empty Port
fn new_port(): Port
return Port{
info: new_package_info(),
deps: new_dependencies(),
sources: new_source_info(),
patches: new_patch_info(),
config: new_config_info(),
scripts: new_scripts_info(),
build_cfg: new_build_config(),
port_dir: "",
category: "",
prefix: "",
sysconfdir: ""
}
end new_port
// Create a PortResult
fn new_port_result(ok: bool, p: Port, err: string): PortResult
return PortResult{
success: ok,
port: p,
error: err
}
end new_port_result
// Path getter functions
fn get_ports_dir(): string
return PORTS_DIR
end get_ports_dir
fn get_sources_dir(): string
return SOURCES_DIR
end get_sources_dir
fn get_packages_dir(): string
return PACKAGES_DIR
end get_packages_dir
fn get_build_dir(): string
return BUILD_DIR
end get_build_dir
fn get_db_dir(): string
return DB_DIR
end get_db_dir
fn get_index_dir(): string
return INDEX_DIR
end get_index_dir
fn get_repos_dir(): string
return REPOS_DIR
end get_repos_dir
fn get_config_file(): string
return CONFIG_FILE
end get_config_file
fn get_groups_dir(): string
return GROUPS_DIR
end get_groups_dir
// Legacy aliases (for compatibility during transition)
fn get_work_dir(): string
return BUILD_DIR
end get_work_dir
fn get_pkg_dir(): string
return BUILD_DIR
end get_pkg_dir
// Initialize empty InstalledPackage
fn new_installed_package(): InstalledPackage
return InstalledPackage{ info: new_package_info(), install_date: "", install_reason: "", files: new [string](0), files_count: 0 }
end new_installed_package
fn new_package_group(): PackageGroup
return PackageGroup{ name: "", description: "", members: new [string](256), members_count: 0 }
end new_package_group
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: archive.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Tar/xz archive operations using shell commands
******************************************************************************/
module util.archive
import sys.process
import io.file
import io.dir
import io.path
import core.str
import core.result as res
export
// Archive type enumeration (as strings for simplicity)
const ARCHIVE_TAR_GZ: string
const ARCHIVE_TAR_XZ: string
const ARCHIVE_TAR_BZ2: string
const ARCHIVE_ZIP: string
const ARCHIVE_UNKNOWN: string
// Detect archive type from filename extension
fn detect_type(archive_path: string): string
// Extract an archive to destination directory
fn extract(archive_path: string, dest_dir: string): bool
// Create a .pkg.tar.xz package from a directory
fn create_package(source_dir: string, output_path: string): bool
// List contents of an archive (returns count, fills files array)
fn list_contents(archive_path: string, files: [string], max_count: int): int
end export
// Archive type constants
const ARCHIVE_TAR_GZ: string = "tar.gz"
const ARCHIVE_TAR_XZ: string = "tar.xz"
const ARCHIVE_TAR_BZ2: string = "tar.bz2"
const ARCHIVE_ZIP: string = "zip"
const ARCHIVE_UNKNOWN: string = "unknown"
// Get the tar command (use gtar on illumos/OmniOS, tar on Linux)
fn get_tar_cmd(): string
// On illumos, we need GNU tar for full compatibility
// Check if gtar exists, otherwise fall back to tar (for Linux)
if file.fileExists("/usr/bin/gtar")
return "/usr/bin/gtar"
elif file.fileExists("/usr/gnu/bin/tar")
return "/usr/gnu/bin/tar"
end if
// Fall back to system tar (Linux)
return "tar"
end get_tar_cmd
// Detect archive type from filename
fn detect_type(archive_path: string): string
let lower = str.to_lower(archive_path)
if str.ends_with(lower, ".tar.xz") or str.ends_with(lower, ".txz")
return ARCHIVE_TAR_XZ
elif str.ends_with(lower, ".tar.gz") or str.ends_with(lower, ".tgz")
return ARCHIVE_TAR_GZ
elif str.ends_with(lower, ".tar.bz2") or str.ends_with(lower, ".tbz2") or str.ends_with(lower, ".tbz")
return ARCHIVE_TAR_BZ2
elif str.ends_with(lower, ".zip")
return ARCHIVE_ZIP
elif str.ends_with(lower, ".tar")
// Plain tar (no compression)
return "tar"
end if
return ARCHIVE_UNKNOWN
end detect_type
// Build the tar extraction flags based on archive type
fn get_extract_flags(archive_type: string): string
if archive_type == ARCHIVE_TAR_XZ
return "-Jxf"
elif archive_type == ARCHIVE_TAR_GZ
return "-zxf"
elif archive_type == ARCHIVE_TAR_BZ2
return "-jxf"
elif archive_type == "tar"
return "-xf"
end if
return ""
end get_extract_flags
// Build the tar list flags based on archive type
fn get_list_flags(archive_type: string): string
if archive_type == ARCHIVE_TAR_XZ
return "-Jtf"
elif archive_type == ARCHIVE_TAR_GZ
return "-ztf"
elif archive_type == ARCHIVE_TAR_BZ2
return "-jtf"
elif archive_type == "tar"
return "-tf"
end if
return ""
end get_list_flags
// Extract an archive to the destination directory
fn extract(archive_path: string, dest_dir: string): bool
// Verify archive exists
if not file.fileExists(archive_path)
return false
end if
// Ensure destination directory exists
if not dir.dir_exists(dest_dir)
if not res.is_ok(dir.create_dir_all(dest_dir))
return false
end if
end if
let archive_type = detect_type(archive_path)
if archive_type == ARCHIVE_ZIP
// Use unzip for zip files
let cmd = "unzip -q -o \"" + archive_path + "\" -d \"" + dest_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
return exit_code == 0
end if
let flags = get_extract_flags(archive_type)
if str.length(flags) == 0
return false
end if
// Build tar command
let tar = get_tar_cmd()
let cmd = tar + " " + flags + " \"" + archive_path + "\" -C \"" + dest_dir + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
return exit_code == 0
end extract
// Create a .pkg.tar.xz package from a source directory
fn create_package(source_dir: string, output_path: string): bool
// Verify source directory exists
if not dir.dir_exists(source_dir)
return false
end if
// Ensure parent directory of output exists
let output_dir = path.dirname(output_path)
if str.length(output_dir) > 0 and not dir.dir_exists(output_dir)
if not res.is_ok(dir.create_dir_all(output_dir))
return false
end if
end if
// Create tar.xz archive
// Command: cd source_dir && tar -Jcf output_path .
let tar = get_tar_cmd()
let cmd = "cd \"" + source_dir + "\" && " + tar + " -Jcf \"" + output_path + "\" ."
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
let exit_code = process.process_wait(pid)
return exit_code == 0
end create_package
// List contents of an archive
fn list_contents(archive_path: string, files: [string], max_count: int): int
if not file.fileExists(archive_path)
return 0
end if
let archive_type = detect_type(archive_path)
if archive_type == ARCHIVE_ZIP
// For zip files, use unzip -l and parse output
// This is more complex, so for now return 0
// TODO: Implement zip listing if needed
return 0
end if
let flags = get_list_flags(archive_type)
if str.length(flags) == 0
return 0
end if
// Build tar command with output to temp file
let tar = get_tar_cmd()
let tmp_file = "/tmp/coral_archive_list_" + int_to_string(process.getpid()) + ".txt"
let cmd = tar + " " + flags + " \"" + archive_path + "\" > \"" + tmp_file + "\" 2>/dev/null"
let pid = process.process_spawn_shell(cmd)
if pid < 0
return 0
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
return 0
end if
// Read the temp file
if not file.fileExists(tmp_file)
return 0
end if
let content = res.unwrap_or(file.readFile(tmp_file), "")
// Clean up temp file
cleanup_temp_file(tmp_file)
if str.length(content) == 0
return 0
end if
// Split by newlines
mut lines: [string] = new [string](max_count)
let line_count = str.split(content, '\n', lines, max_count)
// Copy non-empty lines to output
mut count = 0
mut i = 0
while i < line_count and count < max_count
let line = str.trim_ws(lines[i])
if str.length(line) > 0
files[count] = line
count = count + 1
end if
i = i + 1
end while
return count
end list_contents
// Helper: remove temp file
fn cleanup_temp_file(path: string): bool
let cmd = "rm -f \"" + path + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return false
end if
process.process_wait(pid)
return true
end cleanup_temp_file
// Helper: convert int to string (local copy to avoid circular import)
fn int_to_string(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_string
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: checksum.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: SHA256 checksum verification utilities
******************************************************************************/
module util.checksum
import io.file
import core.str
import sys.process
import crypto.sha256 as sha
import core.result as res
export
// Compute SHA256 hash of a file, returns hex string (lowercase)
fn sha256_file(path: string): string
// Compute SHA256 hash of a string, returns hex string (lowercase)
fn sha256_string(data: string): string
// Verify a file matches expected checksum
fn verify_checksum(path: string, expected: string): bool
// Parse checksum format "algo:hash" and verify
fn verify_checksum_with_algo(path: string, checksum_str: string): bool
end export
// Compute SHA256 of a file
// Uses Reef's native streaming sha256_file() (Reef 0.1.14+)
// Falls back to sha256sum command if native fails
fn sha256_file(path: string): string
if not file.fileExists(path)
return ""
end if
// Use native streaming API (memory efficient, works on all file sizes)
// Reef 0.1.14 fixed the large file hang/segfault issue
let hash = sha.sha256_file(path)
if str.length(hash) == 64
return str.to_lower(hash)
end if
// Fallback to sha256sum command if native fails
return sha256_file_cmd(path)
end sha256_file
// Compute SHA256 using sha256sum command (for large files)
fn sha256_file_cmd(path: string): string
let output_file = "/tmp/coral_checksum_" + extract_basename(path)
let cmd = "sha256sum \"" + path + "\" | cut -d' ' -f1 > \"" + output_file + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
return ""
end if
process.process_wait(pid)
// Read the hash from output file
if not file.fileExists(output_file)
return ""
end if
let hash = str.trim_ws(res.unwrap_or(file.readFile(output_file), ""))
// Clean up
let rm_pid = process.process_spawn_shell("rm -f \"" + output_file + "\"")
if rm_pid > 0
process.process_wait(rm_pid)
end if
return hash
end sha256_file_cmd
// Extract basename from path for temp file naming
fn extract_basename(path: string): string
let last_slash = str.last_index_of_char(path, '/')
if last_slash < 0
return path
end if
return str.substring(path, last_slash + 1, str.length(path) - last_slash - 1)
end extract_basename
// Compute SHA256 of a string using native crypto
fn sha256_string(data: string): string
let hash = sha.sha256(data)
return str.to_lower(hash)
end sha256_string
// Verify that a file's SHA256 matches the expected value
fn verify_checksum(path: string, expected: string): bool
let computed = sha256_file(path)
if str.length(computed) == 0
return false
end if
// Compare case-insensitively (normalize to lowercase)
let computed_lower = str.to_lower(computed)
let expected_lower = str.to_lower(expected)
return computed_lower == expected_lower
end verify_checksum
// Parse and verify checksum in format "algo:hash" or just "hash"
// Supported algorithms: sha256, sha256sum
// If no algorithm prefix, assumes sha256
fn verify_checksum_with_algo(path: string, checksum_str: string): bool
// Check for algorithm prefix
let colon_idx = str.index_of_char(checksum_str, ':')
if colon_idx < 0
// No prefix, assume SHA256
return verify_checksum(path, checksum_str)
end if
// Extract algorithm and hash
let algo = str.to_lower(str.substring(checksum_str, 0, colon_idx))
let hash = str.substring(checksum_str, colon_idx + 1, str.length(checksum_str) - colon_idx - 1)
// Verify based on algorithm
if algo == "sha256" or algo == "sha256sum"
return verify_checksum(path, hash)
end if
// Unsupported algorithm
return false
end verify_checksum_with_algo
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: color.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Terminal color utilities for Coral
******************************************************************************/
module util.color
import sys.args
import sys.env
import sys.platform.runtime as runtime
export
// Color functions - wrap text in ANSI color codes
fn bold(s: string): string
fn dim(s: string): string
fn red(s: string): string
fn green(s: string): string
fn yellow(s: string): string
fn blue(s: string): string
fn cyan(s: string): string
fn magenta(s: string): string
// Formatted output helpers
proc print_error(msg: string)
proc print_success(msg: string)
proc print_warning(msg: string)
proc print_info(msg: string)
proc print_action(msg: string)
end export
// ANSI escape code prefix: ESC[ (ASCII 27)
// Reset code: ESC[0m
// Helper to convert int to char (for ESC character)
fn int_to_char(n: int): char
unsafe
let result: char = n
return result
end unsafe
end int_to_char
// Get ESC character (ASCII 27) as a single-character string
fn get_esc(): string
unsafe
let result: string = runtime.reef_alloc_string_buffer(2)
result[0] = int_to_char(27)
return result
end unsafe
end get_esc
// Check if color output should be disabled
// Respects --no-color flag and NO_COLOR environment variable
fn no_color(): bool
if args.has_flag("no-color")
return true
end if
if env.has_env("NO_COLOR")
return true
end if
return false
end no_color
// Helper to wrap text with ANSI codes
fn wrap_color(s: string, code: string): string
if no_color()
return s
end if
// ESC[ + code + m + text + ESC[0m
let esc = get_esc()
return esc + "[" + code + "m" + s + esc + "[0m"
end wrap_color
// Bold text (code 1)
fn bold(s: string): string
return wrap_color(s, "1")
end bold
// Dim text (code 2)
fn dim(s: string): string
return wrap_color(s, "2")
end dim
// Red text (code 31)
fn red(s: string): string
return wrap_color(s, "31")
end red
// Green text (code 32)
fn green(s: string): string
return wrap_color(s, "32")
end green
// Yellow text (code 33)
fn yellow(s: string): string
return wrap_color(s, "33")
end yellow
// Blue text (code 34)
fn blue(s: string): string
return wrap_color(s, "34")
end blue
// Magenta text (code 35)
fn magenta(s: string): string
return wrap_color(s, "35")
end magenta
// Cyan text (code 36)
fn cyan(s: string): string
return wrap_color(s, "36")
end cyan
// Print error message with red X prefix
proc print_error(msg: string)
if no_color()
println("ERROR: " + msg)
else
println(red("error:") + " " + msg)
end if
end print_error
// Print success message with green checkmark prefix
proc print_success(msg: string)
if no_color()
println("OK: " + msg)
else
println(green("ok:") + " " + msg)
end if
end print_success
// Print warning message with yellow prefix
proc print_warning(msg: string)
if no_color()
println("WARNING: " + msg)
else
println(yellow("warning:") + " " + msg)
end if
end print_warning
// Print info message with blue arrow prefix
proc print_info(msg: string)
if no_color()
println("-> " + msg)
else
println(blue("->") + " " + msg)
end if
end print_info
// Print action message with bold arrow prefix
proc print_action(msg: string)
if no_color()
println("=> " + msg)
else
println(bold("=>") + " " + msg)
end if
end print_action
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: http.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: HTTP download utilities using native Reef net.http
Requires Reef 0.1.16+ for progress bar support
******************************************************************************/
module util.http
import net.http
import net.extras
import io.file
import core.str
import core.result as res
import sys.process
import util.color
export
// Download a file from URL to destination path
fn download(url: string, dest: string): bool
// Download with verbose progress output
fn download_verbose(url: string, dest: string): bool
// Fetch URL content as text
fn fetch_text(url: string): string
// Fetch URL content with timeout
fn fetch_text_timeout(url: string, timeout_ms: int): string
// Check if a URL is reachable (HEAD request)
fn check_url(url: string): bool
// Get response status code for a URL
fn get_status(url: string): int
// Configure proxy usage (call before downloads)
proc enable_proxy(use_proxy: bool)
end export
// Module-level proxy setting
mut proxy_enabled = false
// Default timeout in milliseconds (30 seconds)
fn default_timeout(): int
return 30000
end default_timeout
// Internal: download with progress bar (Style C: solid block)
// Returns true on success, false on failure
fn download_with_progress(url: string, dest: string): bool
// Configure progress bar - Style C: solid block character
extras.progress_bar_set_char("█")
extras.progress_bar_set_width(30)
extras.progress_bar_init(url)
// Download with progress callback
let cb = fn(p: http.HttpDownloadProgress): bool => extras.progress_bar(p)
return res.is_ok(http.http_download_file_callback(url, dest, cb))
end download_with_progress
// Check if URL will redirect (3xx status) - native HTTP download crashes on redirects
fn url_will_redirect(url: string): bool
let status = get_status(url)
return status >= 300 and status < 400
end url_will_redirect
// Download a file from URL to destination with progress bar
// Uses native Reef http_download_file_callback() (requires Reef 0.1.16+)
// Falls back to curl if native download fails or URL redirects
fn download(url: string, dest: string): bool
let filename = extract_filename(url)
print(" " + filename + " ")
// Check for redirects first - native HTTP crashes on 302s
if not url_will_redirect(url)
// Try native Reef download with progress bar
if download_with_progress(url, dest)
println("") // Newline after progress bar completes
return true
end if
println("") // Newline after failed progress
end if
// Fallback to curl (handles redirects with -L flag)
print(" (using curl) ... ")
if download_with_curl(url, dest)
println("done")
return true
end if
println("failed")
return false
end download
// Download with verbose progress output
// Uses native Reef http_download_file_callback() with progress bar (requires Reef 0.1.16+)
fn download_verbose(url: string, dest: string): bool
let filename = extract_filename(url)
println(" " + url)
print(" " + filename + " ")
// Check for redirects first - native HTTP crashes on 302s
if not url_will_redirect(url)
// Try native Reef download with progress bar
if download_with_progress(url, dest)
println("") // Newline after progress bar completes
color.print_success("Download complete: " + filename)
return true
end if
println("") // Newline after failed progress
end if
// Fallback to curl (handles redirects with -L flag)
print(" (using curl) ... ")
if download_with_curl(url, dest)
println("done")
color.print_success("Download complete: " + filename)
return true
end if
println("failed")
color.print_error("Download failed: " + url)
return false
end download_verbose
// Fetch URL content as text
fn fetch_text(url: string): string
return fetch_text_timeout(url, default_timeout())
end fetch_text
// Fetch URL content with timeout
// Uses http_get_auto() which handles redirects and is safe for text/binary
fn fetch_text_timeout(url: string, timeout_ms: int): string
// Create request with timeout
let req = http.http_request_new("GET", url)
http.http_request_set_header(req, "User-Agent", "Coral/1.0")
let resp_r = http.http_send_timeout(req, timeout_ms)
// Check for errors (transport failure is now Err; HttpResponse no longer has an error field)
if res.is_err(resp_r)
return ""
end if
let resp = res.unwrap_ok(resp_r)
// Check for success
if not http.http_response_is_ok(resp)
return ""
end if
return http.http_response_body(resp)
end fetch_text_timeout
// Check if a URL is reachable
fn check_url(url: string): bool
let req = http.http_request_new("HEAD", url)
http.http_request_set_header(req, "User-Agent", "Coral/1.0")
let resp_r = http.http_send_timeout(req, 10000)
if res.is_err(resp_r)
return false
end if
let resp = res.unwrap_ok(resp_r)
// Accept success codes and redirects as "reachable"
return resp.status_code >= 200 and resp.status_code < 400
end check_url
// Get response status code for a URL
fn get_status(url: string): int
let req = http.http_request_new("HEAD", url)
http.http_request_set_header(req, "User-Agent", "Coral/1.0")
let resp_r = http.http_send_timeout(req, 10000)
if res.is_err(resp_r)
return 0
end if
let resp = res.unwrap_ok(resp_r)
return resp.status_code
end get_status
// Extract filename from URL
fn extract_filename(url: string): string
// Find last slash
let last_slash = str.last_index_of_char(url, '/')
if last_slash < 0
return url
end if
let filename = str.substring(url, last_slash + 1, str.length(url) - last_slash - 1)
// Remove query string if present
let query_pos = str.index_of_char(filename, '?')
if query_pos > 0
return str.substring(filename, 0, query_pos)
end if
return filename
end extract_filename
// Helper: convert int to string
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value % 10
result = str.concat(str.substring("0123456789", digit, 1), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
proc enable_proxy(use_proxy: bool)
proxy_enabled = use_proxy
end enable_proxy
// Download using curl command
// Handles HTTP redirects, chunked encoding, and SSL/TLS properly
fn download_with_curl(url: string, dest: string): bool
// Use curl with:
// -L: follow redirects (required for GitHub, etc.)
// -f: fail silently on HTTP errors (returns non-zero exit code)
// -s: silent mode (no progress meter)
// -S: show errors even in silent mode
// -o: output file
mut proxy_flag = " --noproxy \"*\""
if proxy_enabled
proxy_flag = ""
end if
let cmd = "curl -L -f -s -S" + proxy_flag + " -o \"" + dest + "\" \"" + url + "\""
let pid = process.process_spawn_shell(cmd)
if pid < 0
color.print_error("Failed to spawn curl")
return false
end if
let exit_code = process.process_wait(pid)
if exit_code != 0
color.print_error("Download failed: " + url)
return false
end if
return true
end download_with_curl
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: mtree.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: mtree-format manifest for package file inventory
******************************************************************************/
module util.mtree
import io.file
import io.dir
import io.path
import core.str
import fs.stat
import fs.link
import crypto.sha256 as sha
import util.checksum
import text.stringbuilder as sb
import core.result as res
import core.option as opt
export
// Manifest entry representing a single file, directory, or symlink
type ManifestEntry
// Parse an mtree manifest string into an array of entries
// Returns the number of entries parsed
fn parse_manifest(content: string, entries: [ManifestEntry], max_entries: int): int
// Generate an mtree manifest string from a package staging directory
fn generate_manifest(pkg_dir: string): string
// Accessors
fn entry_path(entry: ManifestEntry): string
fn entry_type(entry: ManifestEntry): string
fn entry_mode(entry: ManifestEntry): int
fn entry_uname(entry: ManifestEntry): string
fn entry_gname(entry: ManifestEntry): string
fn entry_sha256(entry: ManifestEntry): string
fn entry_link(entry: ManifestEntry): string
// Format a ManifestEntry as an mtree line
fn format_entry(entry: ManifestEntry): string
// Uid/gid name resolution helpers
fn uid_to_name(uid: int): string
fn gid_to_name(gid: int): string
fn name_to_uid(name: string): int
fn name_to_gid(name: string): int
end export
// ============================================================================
// Types
// ============================================================================
type ManifestEntry = struct
epath: string // Relative path (e.g., ./usr/bin/foo)
etype: string // "file", "dir", or "link"
mode: int // Permission bits as integer (e.g., 0755 = 493)
uname: string // Owner user name
gname: string // Owner group name
sha256: string // SHA256 checksum (files only)
link_target: string // Symlink target (links only)
end ManifestEntry
// ============================================================================
// Accessors
// ============================================================================
fn entry_path(entry: ManifestEntry): string
return entry.epath
end entry_path
fn entry_type(entry: ManifestEntry): string
return entry.etype
end entry_type
fn entry_mode(entry: ManifestEntry): int
return entry.mode
end entry_mode
fn entry_uname(entry: ManifestEntry): string
return entry.uname
end entry_uname
fn entry_gname(entry: ManifestEntry): string
return entry.gname
end entry_gname
fn entry_sha256(entry: ManifestEntry): string
return entry.sha256
end entry_sha256
fn entry_link(entry: ManifestEntry): string
return entry.link_target
end entry_link
// ============================================================================
// Parser
// ============================================================================
// Parse an mtree manifest string into entries.
// Format per line: ./path type=T mode=OOOO uname=U gname=G [sha256=H] [link=T]
// Lines starting with # are comments. Empty lines are skipped.
fn parse_manifest(content: string, entries: [ManifestEntry], max_entries: int): int
if str.length(content) == 0
return 0
end if
// Split into lines
mut lines: [string] = new [string](max_entries + 64)
let line_count = str.split(content, '\n', lines, max_entries + 64)
mut count = 0
mut i = 0
while i < line_count and count < max_entries
let line = str.trim_ws(lines[i])
let line_len = str.length(line)
// Skip empty lines and comments
if line_len == 0
i = i + 1
continue
end if
if line[0] == '#'
i = i + 1
continue
end if
// Parse the line: first token is path, rest are key=value
let entry = parse_entry_line(line)
if str.length(entry.epath) > 0
entries[count] = entry
count = count + 1
end if
i = i + 1
end while
return count
end parse_manifest
// Parse a single mtree line into a ManifestEntry
fn parse_entry_line(line: string): ManifestEntry
mut entry = ManifestEntry{
epath: "",
etype: "",
mode: 0,
uname: "root",
gname: "root",
sha256: "",
link_target: ""
}
// Split line by spaces
mut tokens: [string] = new [string](16)
let token_count = str.split(line, ' ', tokens, 16)
if token_count == 0
return entry
end if
// First token is always the path
entry.epath = tokens[0]
// Remaining tokens are key=value pairs
mut t = 1
while t < token_count
let token = tokens[t]
let eq_pos = str.index_of_char(token, '=')
if eq_pos > 0
let key = str.substring(token, 0, eq_pos)
let val = str.substring(token, eq_pos + 1, str.length(token) - eq_pos - 1)
if str.equals(key, "type")
entry.etype = val
elif str.equals(key, "mode")
entry.mode = octal_to_int(val)
elif str.equals(key, "uname")
entry.uname = val
elif str.equals(key, "gname")
entry.gname = val
elif str.equals(key, "sha256")
entry.sha256 = val
elif str.equals(key, "link")
entry.link_target = val
end if
end if
t = t + 1
end while
return entry
end parse_entry_line
// ============================================================================
// Generator
// ============================================================================
// Generate an mtree manifest for all files in a package staging directory.
// Walks the directory tree, collects entries, sorts them, and returns the
// formatted manifest string.
fn generate_manifest(pkg_dir: string): string
// Collect entries by walking the directory tree
mut entries: [ManifestEntry] = new [ManifestEntry](8192)
let count = walk_directory(pkg_dir, pkg_dir, entries, 0, 8192)
if count == 0
return ""
end if
// Sort entries by path (simple insertion sort — fine for package file counts)
sort_entries(entries, count)
// Build the output string using StringBuilder to avoid O(n²) heap
// fragmentation from repeated string concatenation (Reef BUG-027)
let builder = sb.sb_new()
sb.sb_append(builder, "#mtree\n")
mut i = 0
while i < count
sb.sb_append(builder, format_entry(entries[i]))
sb.sb_append(builder, "\n")
i = i + 1
end while
return sb.sb_build(builder)
end generate_manifest
// Recursively walk a directory, collecting ManifestEntry records.
// base_dir is the package root (for computing relative paths).
// current_dir is the directory being walked.
// Returns total number of entries added (starting from offset).
fn walk_directory(base_dir: string, current_dir: string, entries: [ManifestEntry], offset: int, max: int): int
mut count = offset
// Add the current directory itself (unless it's the base)
if not str.equals(current_dir, base_dir) and count < max
let rel = get_relative_path(base_dir, current_dir)
if not is_metadata_path(rel)
let mode = res.unwrap_or(stat.file_mode(current_dir), 0)
let uid = res.unwrap_or(stat.file_uid(current_dir), 0)
let gid = res.unwrap_or(stat.file_gid(current_dir), 0)
entries[count] = ManifestEntry{
epath: "./" + rel,
etype: "dir",
mode: mode,
uname: uid_to_name(uid),
gname: gid_to_name(gid),
sha256: "",
link_target: ""
}
count = count + 1
end if
end if
// List directory contents
let dir_entries = res.unwrap_or(dir.list_dir(current_dir), new [string](0))
let entry_count = dir_entries.length()
mut i = 0
while i < entry_count and count < max
let name = dir_entries[i]
// Skip . and .. to prevent infinite recursion
if str.equals(name, ".") or str.equals(name, "..")
i = i + 1
continue
end if
let full_path = path.join_path(current_dir, name)
let rel = get_relative_path(base_dir, full_path)
// Skip metadata files and directories
if is_metadata_path(rel)
i = i + 1
continue
end if
// Check type: symlink first (symlinks to dirs would match is_directory)
if stat.is_symlink(full_path)
let target = res.unwrap_or(link.readlink(full_path), "")
let uid = res.unwrap_or(stat.file_uid(current_dir), 0)
let gid = res.unwrap_or(stat.file_gid(current_dir), 0)
entries[count] = ManifestEntry{
epath: "./" + rel,
etype: "link",
mode: 0,
uname: uid_to_name(uid),
gname: gid_to_name(gid),
sha256: "",
link_target: target
}
count = count + 1
elif stat.is_directory(full_path)
// Recurse into subdirectory
count = walk_directory(base_dir, full_path, entries, count, max)
elif stat.is_file(full_path)
let mode = res.unwrap_or(stat.file_mode(full_path), 0)
let uid = res.unwrap_or(stat.file_uid(full_path), 0)
let gid = res.unwrap_or(stat.file_gid(full_path), 0)
let hash = checksum.sha256_file(full_path)
entries[count] = ManifestEntry{
epath: "./" + rel,
etype: "file",
mode: mode,
uname: uid_to_name(uid),
gname: gid_to_name(gid),
sha256: hash,
link_target: ""
}
count = count + 1
end if
i = i + 1
end while
return count
end walk_directory
// Check if a relative path is a package metadata file/directory
fn is_metadata_path(rel: string): bool
if str.equals(rel, ".PKGINFO") or str.equals(rel, ".MANIFEST")
return true
end if
if str.equals(rel, ".FOOTPRINT") or str.equals(rel, ".CONFIG")
return true
end if
if str.equals(rel, ".SCRIPTS")
return true
end if
if str.starts_with(rel, ".SCRIPTS/")
return true
end if
return false
end is_metadata_path
// Get relative path by stripping the base directory prefix
fn get_relative_path(base: string, full: string): string
let base_len = str.length(base)
let full_len = str.length(full)
if full_len <= base_len
return ""
end if
// Skip the base prefix and the trailing /
mut start = base_len
if start < full_len and full[start] == '/'
start = start + 1
end if
return str.substring(full, start, full_len - start)
end get_relative_path
// ============================================================================
// Formatting
// ============================================================================
// Format a ManifestEntry as a single mtree line
fn format_entry(entry: ManifestEntry): string
mut line = entry.epath + " type=" + entry.etype
if str.equals(entry.etype, "file") or str.equals(entry.etype, "dir")
line = line + " mode=" + int_to_octal(entry.mode)
end if
line = line + " uname=" + entry.uname
line = line + " gname=" + entry.gname
if str.equals(entry.etype, "file") and str.length(entry.sha256) > 0
line = line + " sha256=" + entry.sha256
end if
if str.equals(entry.etype, "link") and str.length(entry.link_target) > 0
line = line + " link=" + entry.link_target
end if
return line
end format_entry
// ============================================================================
// Sorting
// ============================================================================
// Insertion sort entries by path (lexicographic).
// Package file counts are typically <1000, so insertion sort is adequate.
proc sort_entries(entries: [ManifestEntry], count: int)
mut i = 1
while i < count
let key_entry = entries[i]
let key_path = entries[i].epath
mut j = i - 1
while j >= 0 and str.compare(entries[j].epath, key_path) > 0
entries[j + 1] = entries[j]
j = j - 1
end while
entries[j + 1] = key_entry
i = i + 1
end while
end sort_entries
// ============================================================================
// Numeric Conversion Helpers
// ============================================================================
// Convert an octal string (e.g., "0755", "4755") to an integer
fn octal_to_int(s: string): int
let slen = str.length(s)
if slen == 0
return 0
end if
mut result = 0
mut i = 0
while i < slen
let c = s[i]
if c >= '0' and c <= '7'
result = result * 8 + (c - '0')
end if
i = i + 1
end while
return result
end octal_to_int
// Convert an integer to a 4-digit octal string (e.g., 493 -> "0755")
fn int_to_octal(n: int): string
if n == 0
return "0000"
end if
mut value = n
mut digits: [int] = new [int](16)
mut count = 0
while value > 0 and count < 16
digits[count] = value - (value / 8 * 8)
value = value / 8
count = count + 1
end while
// Pad to 4 digits minimum
while count < 4
digits[count] = 0
count = count + 1
end while
// Build string in reverse (most significant first)
mut result = ""
mut i = count - 1
while i >= 0
result = result + digit_char(digits[i])
i = i - 1
end while
return result
end int_to_octal
// Single digit to string character
fn digit_char(d: int): string
if d == 0
return "0"
elif d == 1
return "1"
elif d == 2
return "2"
elif d == 3
return "3"
elif d == 4
return "4"
elif d == 5
return "5"
elif d == 6
return "6"
elif d == 7
return "7"
end if
return "0"
end digit_char
// Convert int to decimal string (local helper to avoid circular imports)
fn int_to_str(n: int): string
if n == 0
return "0"
end if
mut negative = false
mut value = n
if n < 0
negative = true
value = 0 - n
end if
mut result = ""
while value > 0
let digit = value - (value / 10 * 10)
result = str.concat(digit_char(digit), result)
value = value / 10
end while
if negative
result = str.concat("-", result)
end if
return result
end int_to_str
// ============================================================================
// UID/GID Name Resolution
// ============================================================================
// Resolve a numeric uid to a username.
// Uses POSIX getpwuid() via Reef's fs.stat.uid_name() — zero heap allocation.
fn uid_to_name(uid: int): string
return opt.unwrap_or(stat.uid_name(uid), "")
end uid_to_name
// Resolve a numeric gid to a group name.
// Uses POSIX getgrgid() via Reef's fs.stat.gid_name() — zero heap allocation.
fn gid_to_name(gid: int): string
return opt.unwrap_or(stat.gid_name(gid), "")
end gid_to_name
// Resolve a username to numeric uid by reading /etc/passwd.
// Only used during verify/install (low call count), not the hot manifest walk.
fn name_to_uid(name: string): int
if str.equals(name, "root")
return 0
end if
let content = res.unwrap_or(file.readFile("/etc/passwd"), "")
if str.length(content) == 0
return 0
end if
mut lines: [string] = new [string](256)
let line_count = str.split(content, '\n', lines, 256)
mut i = 0
while i < line_count
let line = lines[i]
if str.length(line) > 0
mut fields: [string] = new [string](8)
let field_count = str.split(line, ':', fields, 8)
if field_count >= 3 and str.equals(fields[0], name)
return str_to_int(fields[2])
end if
end if
i = i + 1
end while
return 0
end name_to_uid
// Resolve a group name to numeric gid by reading /etc/group.
// Only used during verify/install (low call count), not the hot manifest walk.
fn name_to_gid(name: string): int
if str.equals(name, "root")
return 0
end if
let content = res.unwrap_or(file.readFile("/etc/group"), "")
if str.length(content) == 0
return 0
end if
mut lines: [string] = new [string](256)
let line_count = str.split(content, '\n', lines, 256)
mut i = 0
while i < line_count
let line = lines[i]
if str.length(line) > 0
mut fields: [string] = new [string](8)
let field_count = str.split(line, ':', fields, 8)
if field_count >= 3 and str.equals(fields[0], name)
return str_to_int(fields[2])
end if
end if
i = i + 1
end while
return 0
end name_to_gid
// Simple string-to-int conversion
fn str_to_int(s: string): int
let slen = str.length(s)
if slen == 0
return 0
end if
mut result = 0
mut i = 0
while i < slen
let c = s[i]
if c >= '0' and c <= '9'
result = result * 10 + (c - '0')
end if
i = i + 1
end while
return result
end str_to_int
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: priv.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Privilege detection helpers
******************************************************************************/
module util.priv
import io.file
import core.result as res
export
// Check if we are running as root (UID 0)
fn is_root(): bool
end export
// Check if we are running as root (UID 0)
// Uses file test to check write permission on system directory
fn is_root(): bool
// Try to create a temp file in /var/lib/coral - only root can write there
let test_file = "/var/lib/coral/.root_check"
// writeFile now returns Result[bool, Error] (Reef 0.7.5); Ok means we wrote it
if res.is_ok(file.writeFile(test_file, "1"))
// Successfully wrote - we have root-level access
// File will be overwritten next time, no need to delete
return true
end if
return false
end is_root
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: prompt.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: User prompt utilities for Coral
******************************************************************************/
module util.prompt
import io.console
import core.option as opt
import core.str
import core.convert
import util.color
import types
export
fn has_yes_flag(opts: types.GlobalOptions): bool
fn confirm(message: string, opts: types.GlobalOptions): bool
fn confirm_packages(action: string, packages: [string], count: int, opts: types.GlobalOptions): bool
fn confirm_install(to_install: [string], install_count: int, to_upgrade: [string], upgrade_count: int, opts: types.GlobalOptions): bool
fn confirm_remove(to_remove: [string], count: int, dependents: [string], dep_count: int, opts: types.GlobalOptions): bool
fn confirm_build_plan(packages: [string], versions: [string], count: int, target: string, opts: types.GlobalOptions): bool
end export
// Check if -y or --yes flag is present
fn has_yes_flag(opts: types.GlobalOptions): bool
return opts.yes
end has_yes_flag
// Ask for confirmation, returns true if user confirms
fn confirm(message: string, opts: types.GlobalOptions): bool
// Skip if -y flag
if has_yes_flag(opts)
return true
end if
print(message + " [Y/n] ")
let response = opt.unwrap_or(console.readLine(), "")
let r = str.trim_ws(response)
// Empty or Y/y means yes
if str.length(r) == 0
return true
end if
if r == "Y" or r == "y" or r == "yes" or r == "Yes" or r == "YES"
return true
end if
return false
end confirm
// Display list of packages and ask for confirmation
fn confirm_packages(action: string, packages: [string], count: int, opts: types.GlobalOptions): bool
if count == 0
return false
end if
println("")
println(color.bold("Packages to " + action + ":"))
println("")
// Display packages in columns
mut i = 0
while i < count
println(" " + packages[i])
i = i + 1
end while
println("")
println(color.dim("Total: " + convert.to_string(count) + " package(s)"))
println("")
return confirm("Proceed?", opts)
end confirm_packages
// Display package info and ask for install confirmation
fn confirm_install(to_install: [string], install_count: int,
to_upgrade: [string], upgrade_count: int,
opts: types.GlobalOptions): bool
if install_count == 0 and upgrade_count == 0
return false
end if
println("")
if install_count > 0
println(color.bold("New packages to install:"))
mut i = 0
while i < install_count
println(" " + color.green("+") + " " + to_install[i])
i = i + 1
end while
println("")
end if
if upgrade_count > 0
println(color.bold("Packages to upgrade:"))
mut i = 0
while i < upgrade_count
println(" " + color.cyan("^") + " " + to_upgrade[i])
i = i + 1
end while
println("")
end if
let total = install_count + upgrade_count
println(color.dim("Total: " + convert.to_string(total) + " package(s)"))
println("")
return confirm("Proceed with installation?", opts)
end confirm_install
// Display packages to remove and ask for confirmation
fn confirm_remove(to_remove: [string], count: int,
dependents: [string], dep_count: int,
opts: types.GlobalOptions): bool
if count == 0
return false
end if
println("")
println(color.bold("Packages to remove:"))
mut i = 0
while i < count
println(" " + color.red("-") + " " + to_remove[i])
i = i + 1
end while
if dep_count > 0
println("")
println(color.yellow("The following packages depend on these and will also be removed:"))
i = 0
while i < dep_count
println(" " + color.yellow("-") + " " + dependents[i])
i = i + 1
end while
end if
println("")
let total = count + dep_count
println(color.dim("Total: " + convert.to_string(total) + " package(s)"))
println("")
return confirm("Proceed with removal?", opts)
end confirm_remove
// Display build plan and ask for confirmation
fn confirm_build_plan(packages: [string], versions: [string], count: int, target: string, opts: types.GlobalOptions): bool
if count == 0
return true
end if
println("")
println(color.bold("Build plan for '" + target + "':"))
println("")
println("Packages to build from source:")
mut i = 0
while i < count
mut line = " " + color.green("+") + " " + packages[i]
if str.length(versions[i]) > 0
line = line + " " + color.dim(versions[i])
end if
println(line)
i = i + 1
end while
println("")
println(color.dim("Total: " + convert.to_string(count) + " package(s) to build"))
println("")
return confirm("Proceed with build?", opts)
end confirm_build_plan
end module
/******************************************************************************
__ ____ __
/ / ___ ____ _/ __/_____________ _/ /__
/ / / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
/ /___/ __/ /_/ / __(__ ) /__/ /_/ / / __/
/_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/
(C)opyright 2025, Leafscale, LLC - https://www.leafscale.com
Project: Zygaena
Filename: version.reef
Authors: Chris Tusa <chris.tusa@leafscale.com>
License: <see LICENSE file included with this source code>
Description: Semantic version parsing and comparison utilities
******************************************************************************/
module util.version
import core.str
export
// Version constraint parsing
type DepConstraint
// Compare two version strings semantically
// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
fn compare_versions(v1: string, v2: string): int
// Check if v1 is newer than v2
fn is_newer(v1: string, v2: string): bool
// Parse a dependency string with optional version constraint
// e.g., "libfoo>=1.0" -> { name: "libfoo", op: ">=", version: "1.0" }
fn parse_dep_constraint(dep: string): DepConstraint
// Check if an installed version satisfies a version constraint
fn check_version_constraint(installed_version: string, op: string, required_version: string): bool
// Accessor functions for DepConstraint
fn constraint_name(c: DepConstraint): string
fn constraint_op(c: DepConstraint): string
fn constraint_version(c: DepConstraint): string
fn has_constraint(c: DepConstraint): bool
// Extract version from package filename
// e.g., "reef-0.1.10-1.pkg.tar.xz" -> "0.1.10"
fn extract_version_from_filename(filename: string, pkg_name: string): string
// Extract release number from package filename
// e.g., "reef-0.1.10-1.pkg.tar.xz" -> 1
fn extract_release_from_filename(filename: string): int
end export
// Parsed dependency constraint
type DepConstraint = struct
name: string
op: string
version: string
end DepConstraint
// Compare two version strings semantically
// Handles versions like "0.1.10" vs "0.1.7" correctly (0.1.10 > 0.1.7)
fn compare_versions(v1: string, v2: string): int
// Parse version components
mut v1_parts: [int] = new [int](10)
mut v2_parts: [int] = new [int](10)
let v1_count = parse_version(v1, v1_parts, 10)
let v2_count = parse_version(v2, v2_parts, 10)
// Compare each component
let max_parts = max_int(v1_count, v2_count)
mut i = 0
while i < max_parts
let p1 = get_part(v1_parts, v1_count, i)
let p2 = get_part(v2_parts, v2_count, i)
if p1 > p2
return 1
elif p1 < p2
return -1
end if
i = i + 1
end while
return 0
end compare_versions
// Check if v1 is newer than v2
fn is_newer(v1: string, v2: string): bool
return compare_versions(v1, v2) > 0
end is_newer
// Parse version string into integer components
// "0.1.10" -> [0, 1, 10]
fn parse_version(version: string, parts: [int], max_parts: int): int
mut count = 0
mut current = 0
mut in_number = false
mut i = 0
while i < str.length(version) and count < max_parts
let c = str.char_at(version, i)
if is_digit(c)
current = current * 10 + char_to_digit(c)
in_number = true
elif c == '.' or c == '-'
if in_number
parts[count] = current
count = count + 1
current = 0
in_number = false
end if
else
// Skip non-numeric characters (like 'alpha', 'beta', 'rc')
if in_number
parts[count] = current
count = count + 1
current = 0
in_number = false
end if
end if
i = i + 1
end while
// Don't forget the last number
if in_number and count < max_parts
parts[count] = current
count = count + 1
end if
return count
end parse_version
// Extract version from package filename
// e.g., "reef-0.1.10-1.pkg.tar.xz" with pkg_name "reef" -> "0.1.10"
fn extract_version_from_filename(filename: string, pkg_name: string): string
// Remove package name prefix and dash
let prefix_len = str.length(pkg_name) + 1
if str.length(filename) <= prefix_len
return ""
end if
// Get the part after "pkgname-"
let rest = str.substring(filename, prefix_len, str.length(filename) - prefix_len)
// Find the last dash before .pkg.tar.xz (that's the release separator)
// e.g., "0.1.10-1.pkg.tar.xz" -> version is "0.1.10"
let suffix = ".pkg.tar.xz"
let suffix_len = str.length(suffix)
if not str.ends_with(rest, suffix)
return ""
end if
// Remove suffix: "0.1.10-1.pkg.tar.xz" -> "0.1.10-1"
let ver_rel = str.substring(rest, 0, str.length(rest) - suffix_len)
// Find last dash (release separator)
let last_dash = str.last_index_of_char(ver_rel, '-')
if last_dash < 0
return ver_rel
end if
// Return version part: "0.1.10-1" -> "0.1.10"
return str.substring(ver_rel, 0, last_dash)
end extract_version_from_filename
// Extract release number from package filename
// e.g., "reef-0.1.10-1.pkg.tar.xz" -> 1
fn extract_release_from_filename(filename: string): int
let suffix = ".pkg.tar.xz"
if not str.ends_with(filename, suffix)
return 1
end if
// Remove suffix
let without_suffix = str.substring(filename, 0, str.length(filename) - str.length(suffix))
// Find last dash
let last_dash = str.last_index_of_char(without_suffix, '-')
if last_dash < 0
return 1
end if
// Extract release number
let release_str = str.substring(without_suffix, last_dash + 1, str.length(without_suffix) - last_dash - 1)
return parse_int(release_str)
end extract_release_from_filename
// Helper: check if character is a digit
fn is_digit(c: char): bool
return c >= '0' and c <= '9'
end is_digit
// Helper: convert digit character to integer
fn char_to_digit(c: char): int
return c - '0'
end char_to_digit
// Helper: get part at index, or 0 if out of bounds
fn get_part(parts: [int], count: int, idx: int): int
if idx < count
return parts[idx]
end if
return 0
end get_part
// Helper: max of two integers
fn max_int(a: int, b: int): int
if a > b
return a
end if
return b
end max_int
// Helper: parse string to int
fn parse_int(s: string): int
mut result = 0
mut i = 0
while i < str.length(s)
let c = str.char_at(s, i)
if is_digit(c)
result = result * 10 + char_to_digit(c)
else
break
end if
i = i + 1
end while
return result
end parse_int
// Parse a dependency string into name, operator, and version
// Handles: "libfoo", "libfoo>=1.0", "libfoo<=2.0", "libfoo>1.0", "libfoo<2.0", "libfoo=1.0"
fn parse_dep_constraint(dep: string): DepConstraint
let len = str.length(dep)
mut i = 0
while i < len
let c = str.char_at(dep, i)
if c == '>' or c == '<' or c == '='
let name = str.substring(dep, 0, i)
// Check for two-char operators (>=, <=)
if i + 1 < len
let next = str.char_at(dep, i + 1)
if next == '='
let op = str.substring(dep, i, 2)
let ver = str.substring(dep, i + 2, len - i - 2)
return DepConstraint{ name: name, op: op, version: ver }
end if
end if
// Single char operator (>, <, =)
let op = str.substring(dep, i, 1)
let ver = str.substring(dep, i + 1, len - i - 1)
return DepConstraint{ name: name, op: op, version: ver }
end if
i = i + 1
end while
// No constraint
return DepConstraint{ name: dep, op: "", version: "" }
end parse_dep_constraint
// Check if an installed version satisfies a version constraint
fn check_version_constraint(installed_version: string, op: string, required_version: string): bool
if str.length(op) == 0
return true
end if
let cmp = compare_versions(installed_version, required_version)
if str.equals(op, ">=")
return cmp >= 0
elif str.equals(op, "<=")
return cmp <= 0
elif str.equals(op, ">")
return cmp > 0
elif str.equals(op, "<")
return cmp < 0
elif str.equals(op, "=")
return cmp == 0
end if
return true
end check_version_constraint
// Accessor functions
fn constraint_name(c: DepConstraint): string
return c.name
end constraint_name
fn constraint_op(c: DepConstraint): string
return c.op
end constraint_op
fn constraint_version(c: DepConstraint): string
return c.version
end constraint_version
fn has_constraint(c: DepConstraint): bool
return str.length(c.op) > 0
end has_constraint
end module
|