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
|
-*- mode: org -*-
#+TITLE: gleam lib
#+DESCRIPTION: gleam lib
#+FILETAGS: :spine:build:tools:
#+AUTHOR: Ralph Amissah
#+EMAIL: [[mailto:ralph.amissah@gmail.com][ralph.amissah@gmail.com]]
#+COPYRIGHT: Copyright (C) 2015 (continuously updated, current 2026) Ralph Amissah
#+LANGUAGE: en
#+STARTUP: show2levels hideblocks hidestars noindent entitiespretty
#+PROPERTY: header-args+ :eval never-export :exports code
#+PROPERTY: header-args+ :tangle-mode :noweb no :padline no :tangle-mode :no-expand
#+PROPERTY: header-args+ :results silent :cache no
#+PROPERTY: header-args+ :mkdirp yes
#+OPTIONS: H:3 num:nil toc:t \n:t ::t |:t ^:nil -:t f:t *:t
- magic single double-quote → " ← FIX changes hilighting behavior (occuring
after it) in org document. INVESTIGATE (org-mode CONFIG?) FIND & FIX
* ocda
** ocda lib
#+NAME: ocda_lib
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// ocda-lib, in Gleam: the abstraction as a library, put to the question.
////
//// A library has no binary, so this is the programs over it: the reader,
//// and the two that test its claims.
////
//// ocda-lib dump [--unknown] <file>.ssp|<file>.ocda.db [lang]
//// ocda-lib agree <doc>.ssp <doc>.ocda.db [lang]
//// ocda-lib read [options] <file> [lang] (also installed as ocda-read)
////
//// `dump` writes the whole loaded model out canonically, byte for byte as
//// the D library's `ocda-dump` writes it, so that the two implementations
//// can be diffed. `agree` asks the same question the D library's
//// `ocda-agree` asks, within this language: does loading a document's
//// `.ssp` give what loading its `.ocda.db` gives?
import argv
import gleam/int
import gleam/io
import gleam/list
import gleam/string
import ocda/dump
import ocda/load
import ocda/model.{type Document}
import read/main as reader
pub fn main() {
case argv.load().arguments {
["dump", "--unknown", path] -> dump_file(path, "", True)
["dump", "--unknown", path, lang] -> dump_file(path, lang, True)
["dump", path] -> dump_file(path, "", False)
["dump", path, lang] -> dump_file(path, lang, False)
["agree", ssp, db] -> agree(ssp, db, "")
["agree", ssp, db, lang] -> agree(ssp, db, lang)
["read", ..rest] ->
case reader.run(rest) {
0 -> Nil
code -> halt(code)
}
_ -> usage()
}
}
fn usage() -> Nil {
io.println_error(
"usage: ocda-lib dump [--unknown] <file>.ssp|<file>.ocda.db [lang]
ocda-lib agree <doc>.ssp <doc>.ocda.db [lang]
ocda-lib read [--help] [options] <file> [lang]",
)
halt(2)
}
fn dump_file(path: String, lang: String, unknown: Bool) -> Nil {
case load.load(path, lang, False) {
Error(message) -> fail(message)
Ok(doc) ->
case unknown {
True -> io.print(dump.unknown(doc))
False -> io.print(dump.document(doc))
}
}
}
/// The library's whole purpose is that a writer cannot tell which
/// serialisation it was handed. That is only true if the two loaders give
/// the same model, so this asks, and says where they part company rather
/// than only that they did.
fn agree(ssp_path: String, db_path: String, lang: String) -> Nil {
case load.load(ssp_path, "", False), load.load(db_path, lang, False) {
Error(message), _ -> fail(message)
_, Error(message) -> fail(message)
Ok(from_ssp), Ok(from_db) -> {
let differences = compare(from_ssp, from_db)
case differences {
[] -> io.println("agree: the two loaders give the same model")
_ -> {
list.each(list.take(differences, 12), io.println)
case list.length(differences) > 12 {
True -> io.println(" ... stopping after 12")
False -> Nil
}
io.println(int.to_string(list.length(differences)) <> " difference(s)")
halt(1)
}
}
}
}
}
/// Compared through the dump rather than field by field, which is both
/// shorter and stricter: the dump carries every field, so nothing can
/// differ without showing here.
fn compare(from_ssp: Document, from_db: Document) -> List(String) {
let a = dump.document(from_ssp)
let b = dump.document(from_db)
case a == b {
True -> []
False -> diff_lines(a, b)
}
}
fn diff_lines(a: String, b: String) -> List(String) {
let la = split_lines(a)
let lb = split_lines(b)
case list.length(la) == list.length(lb) {
False -> [
" differ: line count",
" .ssp: " <> int.to_string(list.length(la)),
" .ocda.db: " <> int.to_string(list.length(lb)),
..pairwise(la, lb)
]
True -> pairwise(la, lb)
}
}
fn pairwise(la: List(String), lb: List(String)) -> List(String) {
list.zip(la, lb)
|> list.index_map(fn(pair, i) { #(i, pair.0, pair.1) })
|> list.filter(fn(t) { t.1 != t.2 })
|> list.map(fn(t) {
" differ: line "
<> int.to_string(t.0 + 1)
<> "\n .ssp: "
<> t.1
<> "\n .ocda.db: "
<> t.2
})
}
fn split_lines(text: String) -> List(String) {
case text {
"" -> []
_ -> string.split(text, on: "\n")
}
}
fn fail(message: String) -> Nil {
io.println_error("error: " <> message)
halt(2)
}
/// Gleam has no standard exit, and the exit status is what a sweep script
/// reads.
@external(erlang, "erlang", "halt")
fn halt(code: Int) -> Nil
#+END_SRC
** ocda
*** model
#+NAME: model
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// The object-centric document abstraction, as Gleam types.
////
//// A deliberate mirror of the D library's `ocda.model`, field for field.
//// The two are meant to agree, and the cheapest way to make that testable
//// is for them to hold the same things under the same names: the dump of a
//// loaded document is then identical by construction rather than by
//// negotiation.
////
//// Written against specs/sisudoc-abstraction-format: `ocda-model.md` for
//// the model, the two format specifications for what each serialisation
//// says about it.
import gleam/dict.{type Dict}
import gleam/list
import gleam/string
/// The format major version this library knows.
///
/// The `.ssp` and the `.ocda.db` carry one version between them, declared
/// in band. The minor part rises when a property is added and a reader of
/// the newer format still reads the older, so only the major is checked.
pub const format_major_read = "2"
/// The nine sections, in the order the format gives them, which is not the
/// order a sorted key list or a `group by` would give.
pub const section_names = [
"head", "toc", "body", "endnotes", "glossary", "bibliography", "bookindex",
"blurb", "tail",
]
/// The four blocks that are document preamble rather than sections of
/// objects.
pub const preamble_blocks = ["source", "meta", "make", "doc_has"]
/// A repeatable `.image` record: the file as the abstraction found it.
pub type Image {
Image(
/// filename as the object refers to it
name: String,
/// hex, uppercase
sha256: String,
bytes: Int,
/// the file's own pixel dimensions, not any display width
width: Int,
height: Int,
/// absent or unreadable, so no digest and no size
missing: Bool,
/// any further key:value fields, kept rather than dropped
fields: Dict(String, String),
)
}
pub fn new_image() -> Image {
Image(
name: "",
sha256: "",
bytes: 0,
width: 0,
height: 0,
missing: False,
fields: dict.new(),
)
}
/// One object of the abstraction.
///
/// `text` is one string with the lines joined by newline, as in the D
/// library and for the same reason: an object whose only text line is
/// blank is then indistinguishable from an object with no text, in both
/// libraries, in the same place. A difference that exists in one language
/// and not the other would be worse than a loss both share.
pub type Object {
Object(
ocn: Int,
/// one of the sixteen kinds
is_a: String,
/// the section this object was found in
section: String,
/// headings: A B C D 1 2 3 4
heading_level: String,
identifier: String,
part: String,
/// how the text behaves: para, block, comment
is_of_type: String,
/// the object's own section, when it differs from the block it sits in
own_section: String,
segment_html_is: String,
segment_epub: String,
segment_epub_is: String,
table_aligns: String,
stow_link: List(String),
anchor_tags: List(String),
parent_ocn: Int,
last_descendant_ocn: Int,
ocn_range_first: Int,
ocn_range_last: Int,
children: List(Int),
ancestors: List(Int),
dummy_heading: Bool,
ocn_off: Bool,
indent_base: Int,
indent_hang: Int,
bullet: Bool,
lang: String,
has_links: Bool,
has_notes_reg: Bool,
has_notes_star: Bool,
has_images: Bool,
segment: String,
segment_prev: String,
segment_next: String,
anchor: String,
heading_lev_anchor: String,
table_cols: Int,
table_widths: String,
table_header: Bool,
code_syntax: String,
code_linenumbers: Bool,
heading_ancestors_text: String,
sha256: String,
images: List(Image),
text: String,
)
}
pub fn new_object() -> Object {
Object(
ocn: 0,
is_a: "",
section: "",
heading_level: "",
identifier: "",
part: "",
is_of_type: "",
own_section: "",
segment_html_is: "",
segment_epub: "",
segment_epub_is: "",
table_aligns: "",
stow_link: [],
anchor_tags: [],
parent_ocn: 0,
last_descendant_ocn: 0,
ocn_range_first: 0,
ocn_range_last: 0,
children: [],
ancestors: [],
dummy_heading: False,
ocn_off: False,
indent_base: 0,
indent_hang: 0,
bullet: False,
lang: "",
has_links: False,
has_notes_reg: False,
has_notes_star: False,
has_images: False,
segment: "",
segment_prev: "",
segment_next: "",
anchor: "",
heading_lev_anchor: "",
table_cols: 0,
table_widths: "",
table_header: False,
code_syntax: "",
code_linenumbers: False,
heading_ancestors_text: "",
sha256: "",
images: [],
text: "",
)
}
/// Whether this object is rendered at all.
///
/// `is_of_type` "comment" is markup commentary: carried by the abstraction
/// so that nothing is lost, and not put into output. An output that
/// renders it leaks the author's notes into the document, which is what
/// spine itself does not do.
pub fn renders(object: Object) -> Bool {
object.is_of_type != "comment"
}
/// The section this object belongs to: the block it sits in, unless it
/// says otherwise.
pub fn section_of(object: Object) -> String {
case object.own_section {
"" -> object.section
own -> own
}
}
/// What the loader met and did not understand.
///
/// A loader that silently drops what it does not know cannot say whether
/// it understood the document, and so cannot be used to check a
/// specification against an implementation: silence and understanding look
/// alike.
pub type Unknown {
Unknown(
/// `.name` -> times seen
property: Dict(String, Int),
/// `@name` -> times seen
block: Dict(String, Int),
/// first character -> times seen, for lines of no known shape
line: Dict(String, Int),
)
}
pub fn new_unknown() -> Unknown {
Unknown(property: dict.new(), block: dict.new(), line: dict.new())
}
pub fn any_unknown(unknown: Unknown) -> Bool {
dict.size(unknown.property) > 0
|| dict.size(unknown.block) > 0
|| dict.size(unknown.line) > 0
}
pub type Document {
Document(
/// as declared on line 1 of a `.ssp` or in `schema.version`, "" when
/// absent
format_version: String,
source_filename: String,
/// language, languages, digest
source: Dict(String, String),
unknown: Unknown,
metadata: Dict(String, String),
make: Dict(String, String),
doc_has: Dict(String, String),
/// section name -> objects, in document order
sections: Dict(String, List(Object)),
)
}
pub fn new_document() -> Document {
Document(
format_version: "",
source_filename: "",
source: dict.new(),
unknown: new_unknown(),
metadata: dict.new(),
make: dict.new(),
doc_has: dict.new(),
sections: dict.new(),
)
}
/// The major part of the declared version, "" when none was declared.
pub fn version_major(document: Document) -> String {
case string.split_once(document.format_version, ".") {
Ok(#(major, _)) -> major
Error(_) -> document.format_version
}
}
pub fn meta(document: Document, key: String) -> String {
case dict.get(document.metadata, key) {
Ok(value) -> value
Error(_) -> ""
}
}
/// The objects of a named section, empty when the document has none.
pub fn section(document: Document, name: String) -> List(Object) {
case dict.get(document.sections, name) {
Ok(objects) -> objects
Error(_) -> []
}
}
/// Is this one of the nine sections of the format?
pub fn is_section(name: String) -> Bool {
list.contains(section_names, name)
}
/// Is this one of the four preamble blocks?
pub fn is_preamble_block(name: String) -> Bool {
list.contains(preamble_blocks, name)
}
#+END_SRC
*** what to load
**** inventory
#+NAME: ocda_inventory
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// What a source holds, beyond the one document the model is loaded from.
////
//// The model is one language of one document. Two questions a reader asks
//// are about the file instead: which languages it holds, and, for a
//// database, what else it carries. They are here rather than in a reader
//// because the answer depends on the input form, which is the library's to
//// know, and so that a reader asking them does not learn which form it was
//// handed. A mirror of the D library's `ocda.inventory`.
////
//// `languages` answers for every form, and answers the same: the languages
//// in the order the manifest gave them (which every `.ssp` records, in
//// `@source languages`), each with the markup file it was made from and the
//// sha256 of its `.ssp`. The database stores that digest; for a `.ssp` and a
//// pod it is taken from the bytes, which are the same bytes.
////
//// `carried` is the database's: a `.ocda.db` holds the markup, images,
//// configuration and catalogues it was built from, a `.ssp` holds none of
//// them, and a pod's are its archive entries rather than anything the
//// abstraction says.
import gleam/bit_array
import gleam/dict
import gleam/list
import gleam/result
import gleam/string
import ocda/load
import ocda/load_db
import ocda/load_pod
import ocda/load_ssp
import ocda/zip
import simplifile
pub type Language {
Language(lang: String, source_filename: String, ssp_digest: String)
}
pub type Carried {
Carried(
role: String,
compression: String,
count: String,
bytes: String,
stored: String,
)
}
pub fn languages(path: String) -> Result(List(Language), String) {
case load.source_of(path) {
load.OcdaDb -> {
use held <- result.try(load_db.languages_of_file(path))
Ok(
list.map(held, fn(l) {
Language(l.lang, l.source_filename, l.ssp_digest)
}),
)
}
load.Ssp -> {
use bytes <- result.try(
simplifile.read_bits(path)
|> result.map_error(fn(e) { path <> ": " <> simplifile.describe_error(e) }),
)
use text <- result.try(
bit_array.to_string(bytes)
|> result.replace_error(path <> ": not valid UTF-8"),
)
let doc = load_ssp.parse(text)
Ok([
Language(
source_value(doc.source, "language"),
doc.source_filename,
sha256_hex(bytes),
),
])
}
load.Pod -> {
use archive <- result.try(load_pod.archive_bytes(path))
use entries <- result.try(zip.entries(archive))
use found <- result.try(
zip.find_suffix(entries, ".ssp")
|> list.try_map(fn(e) {
use bytes <- result.try(zip.read(archive, e))
use text <- result.try(
bit_array.to_string(bytes)
|> result.replace_error(e.name <> ": not valid UTF-8"),
)
let doc = load_ssp.parse(text)
let lang = result.unwrap(load_pod.lang_of(e.name), "")
Ok(#(
Language(lang, doc.source_filename, sha256_hex(bytes)),
string.split(source_value(doc.source, "languages"), " "),
))
}),
)
let order = case found {
[#(_, o), ..] -> list.filter(o, fn(l) { l != "" })
[] -> []
}
let by_lang = list.map(found, fn(f) { #({ f.0 }.lang, f.0) }) |> dict.from_list
// the manifest's order, and anything it did not name after it
let named = list.filter_map(order, fn(l) { dict.get(by_lang, l) })
let rest =
list.filter(found, fn(f) { !list.contains(order, { f.0 }.lang) })
|> list.map(fn(f) { f.0 })
Ok(list.append(named, rest))
}
load.Unknown -> Error(path <> ": " <> load.source_name(load.Unknown))
}
}
/// Only a `.ocda.db` carries files.
pub fn is_carrier(path: String) -> Bool {
load.source_of(path) == load.OcdaDb
}
pub fn carried(path: String) -> Result(List(Carried), String) {
case is_carrier(path) {
False -> Ok([])
True -> {
use rows <- result.try(load_db.carried_of_file(path))
Ok(
list.filter_map(rows, fn(r) {
case r {
[role, compression, n, bytes, stored] ->
Ok(Carried(role, compression, n, bytes, stored))
_ -> Error(Nil)
}
}),
)
}
}
}
fn source_value(source: dict.Dict(String, String), key: String) -> String {
result.unwrap(dict.get(source, key), "")
}
@external(erlang, "ocda_ffi", "sha256_hex")
fn sha256_hex(bytes: BitArray) -> String
#+END_SRC
**** load
***** load
#+NAME: ocda_load
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// What a path is, and loading it.
////
//// One place that decides, so that every reader and every writer accepts
//// the same inputs and a new input form is added once. This mirrors
//// spine's own `ocda/abstraction/load.d`, which names the sources it can
//// enter the pipeline from and tells them apart by suffix.
////
//// Deliberately *not* here: `.sst` and `.ssm` markup. Reading markup means
//// implementing the parser, which is spine's work and a far larger thing
//// than a reader or a sample writer needs. This library reads
//// abstractions.
import gleam/list
import gleam/string
import ocda/load_db
import ocda/load_pod
import ocda/load_ssp
import ocda/model.{type Document}
pub type Source {
/// `.ssp`, the abstraction as text
Ssp
/// `.ocda.db`, the abstraction as sqlite
OcdaDb
/// `.sisupod` or `.zip`, an archive carrying a `.ssp`
Pod
Unknown
}
/// `.sisupod` is the archive spine writes now; `.zip` is what it wrote
/// before, and every pod already published carries that name, so both are
/// recognised. What is inside decides how it is opened, not the name.
const suffixes = [
#(".ocda.db", OcdaDb),
#(".ssp", Ssp),
#(".sisupod", Pod),
#(".zip", Pod),
#(".db", OcdaDb),
]
pub fn source_of(path: String) -> Source {
case list.find(suffixes, fn(s) { string.ends_with(path, s.0) }) {
Ok(#(_, source)) -> source
Error(_) -> Unknown
}
}
pub fn source_name(source: Source) -> String {
case source {
Ssp -> ".ssp (the abstraction as text)"
OcdaDb -> ".ocda.db (the abstraction as sqlite)"
Pod -> "a pod archive carrying a .ssp"
Unknown -> "not an abstraction this library reads"
}
}
/// Load whatever the path is into the model.
///
/// `lang` names which language to take from a `.ocda.db`, which holds
/// every language of its document, and from a pod, which may carry more than
/// one `.ssp`. A `.ssp` is one language by construction and ignores it.
pub fn load(
path: String,
lang: String,
any_version: Bool,
) -> Result(Document, String) {
case source_of(path) {
Ssp -> load_ssp.load_file(path)
OcdaDb -> load_db.load_file(path, lang, any_version)
Pod -> load_pod.load_file(path, lang)
Unknown ->
Error(
path
<> ": "
<> source_name(Unknown)
<> " (expected .ssp, .ocda.db, .sisupod or .zip)",
)
}
}
#+END_SRC
***** load pod
#+NAME: ocda_load_pod
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// The abstraction out of a pod archive.
////
//// A pod built with `--pod2` carries the abstraction inside it, at
//// `media/abstraction/<uid>.<lang>.ssp`, and that is what is read. So this is
//// a third input form and *not* a third model: the `.ssp` inside is parsed by
//// `ocda/load_ssp` and comes back as the same value. A writer over the
//// library gains pods without being touched, which is the whole reason the
//// dispatch is in one place.
////
//// ## The one thing this cannot do
////
//// A `.sisupod` is **one zstd frame wrapping** the zip. This reads the zip
//// and **not the frame**, because there is no zstd on the BEAM without a NIF,
//// and the one that exists, `ezstd`, clones zstd from github in its build, so
//// it cannot be built in a sandbox without patching it. The D library has
//// both, through a declared `libzstd`.
////
//// So: a `.zip` pod is read, a `.sisupod` is refused, and the refusal says
//// why rather than pretending the file is malformed. It is the only place the
//// two libraries differ in what they accept, and it is a packaging limit
//// rather than anything about the format.
import gleam/list
import gleam/result
import gleam/string
import ocda/load_ssp
import ocda/model.{type Document}
import ocda/zip
import simplifile
/// The magic number of a zstd frame, little endian 0xFD2FB528.
const zstd_magic = <<0x28, 0xB5, 0x2F, 0xFD>>
/// Which languages of the abstraction the pod carries, sorted.
pub fn languages(path: String) -> Result(List(String), String) {
use bytes <- result.try(archive_bytes(path))
use entries <- result.try(zip.entries(bytes))
zip.find_suffix(entries, ".ssp")
|> list.filter_map(fn(e) { lang_of(e.name) })
|> list.sort(string.compare)
|> Ok
}
/// Load one language of the abstraction a pod carries.
///
/// `lang` == "" takes the only one there is, and where there is a choice it
/// says so rather than choosing, as the `.ocda.db` loader does.
pub fn load_file(path: String, lang: String) -> Result(Document, String) {
use bytes <- result.try(archive_bytes(path))
use entries <- result.try(zip.entries(bytes))
let ssps = zip.find_suffix(entries, ".ssp")
use chosen <- result.try(case ssps, lang {
[], _ ->
Error(
path
<> ": carries no .ssp. A pod carries the abstraction only when spine"
<> " was asked for it: spine --pod2 puts it in, spine --source does not.",
)
[only], "" -> Ok(only)
_, "" ->
Error(
path
<> ": holds more than one language ("
<> string.join(langs(ssps), " ")
<> "); name the one wanted",
)
_, wanted ->
case list.find(ssps, fn(e) { lang_of(e.name) == Ok(wanted) }) {
Ok(found) -> Ok(found)
Error(_) ->
Error(
path
<> ": no language '"
<> wanted
<> "'; it holds: "
<> string.join(langs(ssps), " "),
)
}
})
use content <- result.try(zip.read(bytes, chosen))
case bit_array_to_string(content) {
Ok(text) -> Ok(load_ssp.parse(text))
Error(_) -> Error(chosen.name <> ": not valid UTF-8")
}
}
fn langs(entries: List(zip.Entry)) -> List(String) {
list.filter_map(entries, fn(e) { lang_of(e.name) })
}
/// `<uid>.<lang>.ssp` -> `<lang>`
pub fn lang_of(name: String) -> Result(String, Nil) {
case string.ends_with(name, ".ssp") {
False -> Error(Nil)
True -> {
let stem = string.drop_end(name, 4)
case string.split(stem, on: ".") |> list.last {
Ok(lang) if lang != stem -> Ok(lang)
_ -> Error(Nil)
}
}
}
}
/// The bytes decide, not the name: a file misnamed either way is treated by
/// what it holds.
pub fn archive_bytes(path: String) -> Result(BitArray, String) {
case simplifile.read_bits(path) {
Error(e) -> Error(path <> ": " <> simplifile.describe_error(e))
Ok(bytes) ->
case is_zstd_frame(bytes) {
False -> Ok(bytes)
True ->
Error(
path
<> " is a zstd frame wrapping the archive, and this library has no"
<> " zstd: the only one on the BEAM is a NIF that fetches zstd in"
<> " its own build, so it cannot be built sandboxed. Unwrap it"
<> " first (zstd -d) and read the archive, or use the D library,"
<> " which reads both.",
)
}
}
}
fn is_zstd_frame(bytes: BitArray) -> Bool {
case bytes {
<<head:bytes-size(4), _:bits>> -> head == zstd_magic
_ -> False
}
}
@external(erlang, "unicode", "characters_to_binary")
fn bit_array_to_string_ffi(b: BitArray) -> String
pub fn bit_array_to_string(b: BitArray) -> Result(String, Nil) {
Ok(bit_array_to_string_ffi(b))
}
#+END_SRC
***** load ssp
#+NAME: ocda_load_ssp
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// Loading a `.ssp` into the model.
////
//// The format is line oriented and every line is one of eight shapes told
//// apart by its first character, so the loader is a fold over the lines
//// carrying the state the shapes need.
////
//// Written against `ssp-format-specification.org`. Where it and the D
//// library differ the D library is the bug, or this is: they are meant to
//// give the same model, and `ocda-dump` says whether they do.
import gleam/dict.{type Dict}
import gleam/int
import gleam/list
import gleam/option
import gleam/result
import gleam/string
import ocda/model.{type Document, type Image, type Object, Image, Object}
import simplifile
pub fn load_file(path: String) -> Result(Document, String) {
case simplifile.read(path) {
Ok(content) -> Ok(parse(content))
Error(e) -> Error(path <> ": " <> simplifile.describe_error(e))
}
}
type State {
State(
document: Document,
/// the block currently open, "" when none
block: String,
/// the section currently open, "" when in the preamble
section: String,
/// objects of the current section, newest first
objects: List(Object),
/// the object being read, if any
current: Result(Object, Nil),
/// text lines of the object being read, newest first
text: List(String),
/// whether a text line has been seen for the object being read.
/// Not "is the text non-empty": an object whose first text line is
/// blank, which the reference collection has seven of, would then lose
/// it.
seen_text: Bool,
)
}
pub fn parse(content: String) -> Document {
content
|> string.split(on: "\n")
|> list.fold(from: initial(), with: line)
|> finish
}
fn initial() -> State {
State(
document: model.new_document(),
block: "",
section: "",
objects: [],
current: Error(Nil),
text: [],
seen_text: False,
)
}
fn line(state: State, raw: String) -> State {
case raw {
"% SiSU Document Abstraction v" <> version ->
case state.document.format_version {
"" ->
State(
..state,
document: model.Document(
..state.document,
format_version: string.trim(version),
),
)
_ -> state
}
"% Source: " <> filename ->
case state.document.source_filename {
"" ->
State(
..state,
document: model.Document(
..state.document,
source_filename: string.trim(filename),
),
)
_ -> state
}
"%" <> _ -> state
"@" <> rest -> open_block(state, rest)
"}" <> _ -> close_block(state)
"[" <> rest -> declaration(state, rest)
"." <> rest -> property(state, rest)
"|" <> rest -> text_line(state, rest)
_ ->
case string.trim(raw) {
// a blank line ends the object being read
"" -> commit(state)
_ ->
case model.is_preamble_block(state.block) {
True -> preamble_pair(state, raw)
False -> unknown_line(state, raw)
}
}
}
}
fn open_block(state: State, rest: String) -> State {
let name = case string.split_once(rest, "{") {
Ok(#(name, _)) -> string.trim(name)
Error(_) -> string.trim(rest)
}
case model.is_preamble_block(name) {
True -> State(..flush(state), block: name)
False -> {
let state = flush(state)
let document = case model.is_section(name) {
True -> state.document
// a block that is neither preamble nor one of the nine sections:
// counted, so that a reader can say the file held something it did
// not expect
False ->
model.Document(
..state.document,
unknown: model.Unknown(
..state.document.unknown,
block: bump(state.document.unknown.block, name),
),
)
}
State(..state, block: name, section: name, document: document)
}
}
}
fn close_block(state: State) -> State {
State(..flush(state), block: "")
}
/// Commit the object being read, then put the section's objects into the
/// document and close the section.
fn flush(state: State) -> State {
let state = commit(state)
case state.section, state.objects {
"", _ -> state
_, [] -> State(..state, section: "", objects: [])
name, objects ->
State(
..state,
section: "",
objects: [],
document: model.Document(
..state.document,
sections: add_section(
state.document.sections,
name,
list.reverse(objects),
),
),
)
}
}
fn preamble_pair(state: State, raw: String) -> State {
case string.split_once(string.trim_start(raw), ":") {
Error(_) -> state
Ok(#(key, value)) -> {
let key = string.trim(key)
let value = string.trim(value)
let document = state.document
let document = case state.block {
"meta" ->
model.Document(
..document,
metadata: dict.insert(document.metadata, key, value),
)
"make" ->
model.Document(..document, make: dict.insert(document.make, key, value))
"source" ->
model.Document(
..document,
source: dict.insert(document.source, key, value),
)
_ ->
model.Document(
..document,
doc_has: dict.insert(document.doc_has, key, value),
)
}
State(..state, document: document)
}
}
}
/// `[<ocn>] <kind>`, and for a heading `[<ocn>] heading :<level>
/// [<identifier>]`.
fn declaration(state: State, rest: String) -> State {
let state = commit(state)
case string.split_once(rest, "]") {
Error(_) -> state
Ok(#(ocn_text, tail)) -> {
let ocn = parse_int(string.trim(ocn_text))
let object =
Object(..model.new_object(), ocn: ocn, section: state.section)
let object = case string.split(string.trim(tail), on: " ") {
["heading", level, ..identifier] ->
Object(
..object,
is_a: "heading",
heading_level: string.drop_start(level, 1),
identifier: string.join(identifier, " "),
)
[""] -> object
[kind, ..] -> Object(..object, is_a: kind)
[] -> object
}
State(..state, current: Ok(object), text: [], seen_text: False)
}
}
}
fn property(state: State, rest: String) -> State {
case state.current, string.split_once(rest, ":") {
Ok(object), Ok(#(name, raw_value)) -> {
let name = string.trim(name)
let value = string.trim(raw_value)
let #(object, known) = apply_property(object, name, value)
let document = case known {
True -> state.document
False ->
model.Document(
..state.document,
unknown: model.Unknown(
..state.document.unknown,
property: bump(state.document.unknown.property, name),
),
)
}
State(..state, current: Ok(object), document: document)
}
_, _ -> state
}
}
/// The properties this library reads, and what each sets.
///
/// A property it has no use for is counted rather than passed over:
/// ignoring one is conforming within a major version, doing so in silence
/// is what stops a reader being a check on the specification.
fn apply_property(
object: Object,
name: String,
value: String,
) -> #(Object, Bool) {
case name {
"part" -> #(Object(..object, part: value), True)
"is_of_type" -> #(Object(..object, is_of_type: value), True)
"section" -> #(Object(..object, own_section: value), True)
"identifier" -> #(Object(..object, identifier: value), True)
"segment_html_is" -> #(Object(..object, segment_html_is: value), True)
"segment_epub" -> #(Object(..object, segment_epub: value), True)
"segment_epub_is" -> #(Object(..object, segment_epub_is: value), True)
"table_aligns" -> #(Object(..object, table_aligns: value), True)
"stow_link" -> #(
Object(..object, stow_link: list.append(object.stow_link, [value])),
True,
)
"anchor_tag" -> #(
Object(..object, anchor_tags: list.append(object.anchor_tags, [value])),
True,
)
"parent" -> #(Object(..object, parent_ocn: parse_int(value)), True)
"last_descendant" -> #(
Object(..object, last_descendant_ocn: parse_int(value)),
True,
)
"ocn_range" ->
case numbers(value) {
[first, last] -> #(
Object(..object, ocn_range_first: first, ocn_range_last: last),
True,
)
_ -> #(object, True)
}
"children" -> #(Object(..object, children: numbers(value)), True)
"ancestors" -> #(Object(..object, ancestors: numbers(value)), True)
"dummy" -> #(Object(..object, dummy_heading: value == "true"), True)
"ocn_off" -> #(Object(..object, ocn_off: value == "true"), True)
"indent" -> {
let parts = string.split(value, on: " ")
let base = case parts {
[first, ..] -> parse_int(first)
[] -> 0
}
let hang = case parts {
[_, second, ..] -> parse_int(second)
_ -> 0
}
#(Object(..object, indent_base: base, indent_hang: hang), True)
}
"bullet" -> #(Object(..object, bullet: value == "true"), True)
"lang" -> #(Object(..object, lang: value), True)
"has" -> #(has_flags(object, value), True)
"segment" -> #(Object(..object, segment: value), True)
"segment_prev" -> #(Object(..object, segment_prev: value), True)
"segment_next" -> #(Object(..object, segment_next: value), True)
"anchor" -> #(Object(..object, anchor: value), True)
"heading_lev_anchor" -> #(
Object(..object, heading_lev_anchor: value),
True,
)
"table_cols" -> #(Object(..object, table_cols: parse_int(value)), True)
"table_widths" -> #(Object(..object, table_widths: value), True)
"table_header" -> #(Object(..object, table_header: value == "true"), True)
"code_syntax" -> #(Object(..object, code_syntax: value), True)
"code_linenumbers" -> #(
Object(..object, code_linenumbers: value == "true"),
True,
)
"heading_ancestors_text" -> #(
Object(..object, heading_ancestors_text: value),
True,
)
"sha256" -> #(Object(..object, sha256: value), True)
"image" -> #(
Object(..object, images: list.append(object.images, [image(value)])),
True,
)
_ -> #(object, False)
}
}
fn has_flags(object: Object, value: String) -> Object {
value
|> string.split(on: " ")
|> list.fold(from: object, with: fn(obj, flag) {
case flag {
"links" -> Object(..obj, has_links: True)
"notes_reg" -> Object(..obj, has_notes_reg: True)
"notes_star" -> Object(..obj, has_notes_star: True)
"images" -> Object(..obj, has_images: True)
_ -> obj
}
})
}
/// `<filename> sha256:<HEX> bytes:<n> [px:<w>x<h>] [missing:true] [...]`
///
/// The filename comes first, the rest are order-independent, and a field
/// this library does not recognise is kept rather than discarded.
fn image(value: String) -> Image {
case string.split(value, on: " ") {
[] -> model.new_image()
[name, ..fields] ->
list.fold(fields, model.new_image(), fn(img, field) {
case string.split_once(field, ":") {
Error(_) -> img
Ok(#(key, val)) ->
case key {
"sha256" -> Image(..img, sha256: val)
"bytes" -> Image(..img, bytes: parse_int(val))
"px" ->
case string.split_once(val, "x") {
Ok(#(w, h)) ->
Image(..img, width: parse_int(w), height: parse_int(h))
Error(_) -> img
}
"missing" -> Image(..img, missing: val == "true")
_ -> Image(..img, fields: dict.insert(img.fields, key, val))
}
}
})
|> fn(img) { Image(..img, name: name) }
}
}
/// `| <text>`, and `| ` alone for a blank line. Never a bare `|`: the
/// emitter writes the space.
fn text_line(state: State, rest: String) -> State {
case state.current {
Error(_) -> state
Ok(_) -> {
let content = string.drop_start(rest, 1)
State(..state, text: [content, ..state.text], seen_text: True)
}
}
}
fn unknown_line(state: State, raw: String) -> State {
let first = string.slice(raw, 0, 1)
State(
..state,
document: model.Document(
..state.document,
unknown: model.Unknown(
..state.document.unknown,
line: bump(state.document.unknown.line, first),
),
),
)
}
fn commit(state: State) -> State {
case state.current {
Error(_) -> state
Ok(object) -> {
let text = case state.seen_text {
True -> string.join(list.reverse(state.text), "\n")
False -> ""
}
let object = derive_omitted(Object(..object, text: text))
let objects = case model.is_section(state.section) {
True -> [object, ..state.objects]
False -> state.objects
}
State(
..state,
current: Error(Nil),
text: [],
seen_text: False,
objects: objects,
)
}
}
}
/// Two values the text form leaves out because they can be worked out.
///
/// `.identifier` is absent when it is simply the ocn, `.anchor` when it is
/// the segment name. The `.ocda.db`, being columns rather than lines,
/// stores both unconditionally. So a loader that takes the text form
/// literally gives a different model from the one the database gives, and
/// over one document that is 1,314 identifiers and 69 anchors.
fn derive_omitted(object: Object) -> Object {
let object = case object.identifier, object.ocn {
"", 0 -> object
"", ocn -> Object(..object, identifier: int.to_string(ocn))
_, _ -> object
}
case object.anchor, object.segment {
"", "" -> object
"", segment -> Object(..object, anchor: segment)
_, _ -> object
}
}
fn finish(state: State) -> Document {
flush(state).document
}
fn add_section(
sections: Dict(String, List(Object)),
name: String,
objects: List(Object),
) -> Dict(String, List(Object)) {
dict.upsert(sections, name, fn(existing) {
case existing {
option.Some(previous) -> list.append(previous, objects)
option.None -> objects
}
})
}
fn bump(counts: Dict(String, Int), key: String) -> Dict(String, Int) {
dict.upsert(counts, key, fn(existing) {
case existing {
option.Some(n) -> n + 1
option.None -> 1
}
})
}
fn parse_int(value: String) -> Int {
value |> string.trim |> int.parse |> result.unwrap(0)
}
fn numbers(value: String) -> List(Int) {
value
|> string.split(on: " ")
|> list.filter(fn(s) { s != "" })
|> list.map(parse_int)
}
#+END_SRC
***** load db
#+NAME: ocda_load_db
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// Loading a `.ocda.db` into the model.
////
//// The point of this module is that it returns *the same value*
//// `ocda/load_ssp` returns from the same document's `.ssp`. A writer is
//// then a function from the model to bytes and cannot tell which
//// serialisation it was given, exactly as spine's own writers cannot.
////
//// Written against `ocda-db-format-specification.org`, whose section 4
//// gives the column by column correspondence this module implements.
import gleam/dict
import gleam/dynamic/decode
import gleam/float
import gleam/int
import gleam/json
import gleam/list
import gleam/option
import gleam/result
import gleam/string
import ocda/model.{type Document, Image, Object}
import sqlight
/// The schema major version this loader knows.
pub const schema_major_read = "2"
/// One language of the database, as the manifest gives it.
pub type Language {
Language(doc_id: Int, lang: String, source_filename: String, ssp_digest: String)
}
/// Load one language of a database as the model. `lang` == "" takes the
/// first language the manifest gives.
pub fn load_file(
path: String,
lang: String,
any_version: Bool,
) -> Result(Document, String) {
// read only: a loader has no business writing, and a read-write open
// *creates* an empty database where a path is mistyped, which then reads
// as a document with nothing in it, a failure that looks like an answer
use conn <- with_connection("file:" <> path <> "?mode=ro", path)
use _ <- result.try(case
has(conn, "documents") && has(conn, "objects") && has(conn, "metadata")
{
True -> Ok(Nil)
False ->
Error(
path
<> ": no documents/objects/metadata tables; it does not look like a .ocda.db",
)
})
let schema_version =
one(conn, "select value from metadata where doc_id is null
and key = 'schema.version'")
use _ <- result.try(case schema_version, any_version {
"", _ -> Ok(Nil)
_, True -> Ok(Nil)
v, False ->
case major_of(v) == schema_major_read {
True -> Ok(Nil)
False ->
Error(
path
<> " is schema v"
<> v
<> ", this loader knows v"
<> schema_major_read
<> ".x",
)
}
})
let languages = languages(conn)
use chosen <- result.try(case languages, lang {
[], _ -> Error(path <> ": no documents rows")
[first, ..], "" -> Ok(first)
_, wanted ->
case list.find(languages, fn(l) { l.lang == wanted }) {
Ok(found) -> Ok(found)
Error(_) ->
Error(
path
<> ": no language '"
<> wanted
<> "'; it holds: "
<> string.join(list.map(languages, fn(l) { l.lang }), " "),
)
}
})
let source =
dict.new()
|> dict.insert("language", chosen.lang)
|> dict.insert(
"languages",
string.join(list.map(languages, fn(l) { l.lang }), " "),
)
let digest = meta_value(conn, chosen.doc_id, "source.digest")
let source = case digest {
"" -> source
d -> dict.insert(source, "digest", d)
}
let document =
model.Document(
..model.new_document(),
format_version: schema_version,
source_filename: chosen.source_filename,
source: source,
)
let document = metadata(conn, chosen.doc_id, document)
let document = objects(conn, chosen.doc_id, document)
let document = count_unread(conn, chosen.doc_id, document)
Ok(document)
}
fn with_connection(
uri: String,
path: String,
then: fn(sqlight.Connection) -> Result(a, String),
) -> Result(a, String) {
case sqlight.open(uri) {
Error(e) -> Error(path <> ": " <> e.message)
Ok(conn) -> {
let outcome = then(conn)
let _ = sqlight.close(conn)
outcome
}
}
}
/// Every language the database holds, in manifest order.
pub fn languages(conn: sqlight.Connection) -> List(Language) {
let d = {
use id <- decode.field(0, decode.int)
use lang <- decode.field(1, decode.string)
use source <- decode.field(2, decode.string)
use digest <- decode.field(3, decode.string)
decode.success(Language(id, lang, source, digest))
}
sqlight.query(
"select id, lang, coalesce(source_filename,''), coalesce(ssp_digest,'')
from documents order by id",
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
}
/// The three preamble blocks of the text form, out of the one metadata
/// table the database keeps them in.
fn metadata(
conn: sqlight.Connection,
doc_id: Int,
document: Document,
) -> Document {
let d = {
use key <- decode.field(0, decode.string)
use value <- decode.field(1, decode.string)
decode.success(#(key, value))
}
let rows =
sqlight.query(
"select key, value from metadata where doc_id = "
<> int.to_string(doc_id)
<> " order by key",
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
list.fold(rows, document, fn(doc, row) {
let #(key, raw) = row
let value = string.trim(raw)
case key {
// source.* describes the artefact rather than the document, and is
// @source in the text form
"source." <> _ -> doc
// translation.ocn_aligned says whether the languages of this document
// share one numbering. A .ocda.db can know it because it holds every
// language; a .ssp is one language and cannot. It is a fact about the
// file, not the document, and carrying it here would let a writer
// tell which serialisation it was handed.
"translation." <> _ -> doc
// the database tells the three blocks apart by a key prefix.
// Unprefixing them is what makes the two loaders give one model: a
// writer asks make["footer"], never metadata["make.footer"].
"make." <> rest ->
model.Document(..doc, make: dict.insert(doc.make, rest, value))
"doc_has." <> rest ->
model.Document(..doc, doc_has: dict.insert(doc.doc_has, rest, value))
_ ->
model.Document(..doc, metadata: dict.insert(doc.metadata, key, value))
}
})
}
/// The objects, in document order within each section, the sections in the
/// order the format gives rather than the alphabetical one sqlite would.
fn objects(
conn: sqlight.Connection,
doc_id: Int,
document: Document,
) -> Document {
let d = {
use section <- decode.field(0, decode.string)
use ocn <- decode.field(2, decode.int)
use is_a <- decode.field(3, decode.string)
use part <- decode.field(4, decode.string)
use is_of_section <- decode.field(5, decode.string)
use is_of_type <- decode.field(6, decode.string)
use heading_level <- decode.field(7, decode.int)
use identifier <- decode.field(8, decode.string)
use parent <- decode.field(9, decode.int)
use last_descendant <- decode.field(10, decode.int)
use children <- decode.field(11, decode.string)
use ancestors <- decode.field(12, decode.string)
use dummy <- decode.field(13, decode.int)
use ocn_off <- decode.field(14, decode.int)
use indent_base <- decode.field(15, decode.int)
use indent_hang <- decode.field(16, decode.int)
use bullet <- decode.field(17, decode.int)
use lang <- decode.field(18, decode.string)
use has_links <- decode.field(19, decode.int)
use has_notes_reg <- decode.field(20, decode.int)
use has_notes_star <- decode.field(21, decode.int)
use has_images <- decode.field(22, decode.int)
use segment <- decode.field(23, decode.string)
use segment_prev <- decode.field(24, decode.string)
use segment_next <- decode.field(25, decode.string)
use anchor <- decode.field(26, decode.string)
use segment_html_is <- decode.field(27, decode.string)
use table_cols <- decode.field(28, decode.int)
use table_widths <- decode.field(29, decode.string)
use table_aligns <- decode.field(30, decode.string)
use table_header <- decode.field(31, decode.int)
use code_linenumbers <- decode.field(32, decode.int)
use hat <- decode.field(33, decode.string)
use sha256 <- decode.field(34, decode.string)
use text <- decode.field(35, decode.string)
use id <- decode.field(36, decode.int)
use hla <- decode.field(37, decode.string)
use seg_epub <- decode.field(38, decode.string)
use seg_epub_is <- decode.field(39, decode.string)
use range_first <- decode.field(40, decode.int)
use range_last <- decode.field(41, decode.int)
decode.success(#(
id,
Object(
ocn: ocn,
is_a: is_a,
section: section,
heading_level: level_name(heading_level),
identifier: identifier,
part: part,
is_of_type: is_of_type,
own_section: case is_of_section == section {
True -> ""
False -> is_of_section
},
segment_html_is: segment_html_is,
table_aligns: json_words(table_aligns),
stow_link: [],
anchor_tags: [],
parent_ocn: parent,
last_descendant_ocn: last_descendant,
ocn_range_first: range_first,
ocn_range_last: range_last,
children: json_ints(children),
ancestors: json_ints(ancestors),
dummy_heading: dummy != 0,
ocn_off: ocn_off != 0,
indent_base: indent_base,
indent_hang: indent_hang,
bullet: bullet != 0,
lang: lang,
has_links: has_links != 0,
has_notes_reg: has_notes_reg != 0,
has_notes_star: has_notes_star != 0,
has_images: has_images != 0,
segment: segment,
segment_prev: segment_prev,
segment_next: segment_next,
anchor: anchor,
heading_lev_anchor: hla,
segment_epub: seg_epub,
segment_epub_is: seg_epub_is,
table_cols: table_cols,
table_widths: json_words(table_widths),
table_header: table_header != 0,
code_syntax: "",
code_linenumbers: code_linenumbers != 0,
heading_ancestors_text: json_joined(hat),
sha256: sha256,
images: [],
text: text,
),
))
}
let rows =
sqlight.query(
object_sql(doc_id, has_range_columns(conn)),
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
// Built newest-first per section and reversed once at the end. Appending
// to the tail of each section instead would be quadratic, and the largest
// document in the reference collection has some thousands of objects in
// one section.
let sections =
list.fold(rows, dict.new(), fn(acc, row) {
let #(id, object) = row
// the four repeatable properties of the text form are child tables
// here, one query each
let object =
Object(
..object,
images: images(conn, id),
stow_link: links(conn, id),
anchor_tags: anchors(conn, id),
)
case model.is_section(object.section) {
False -> acc
True ->
dict.upsert(acc, object.section, fn(existing) {
case existing {
option.Some(previous) -> [object, ..previous]
option.None -> [object]
}
})
}
})
|> dict.map_values(fn(_, objects) { list.reverse(objects) })
model.Document(..document, sections: sections)
}
/// 2.1 added the container range as two columns. A 2.0 database has
/// neither, and reads as having no range, which is what 2.0 meant.
fn has_range_columns(conn: sqlight.Connection) -> Bool {
let d = decode.field(0, decode.int, decode.success)
case
sqlight.query(
"select count(*) from pragma_table_info('objects')
where name = 'ocn_range_first'",
on: conn,
with: [],
expecting: d,
)
{
Ok([n]) -> n > 0
_ -> False
}
}
fn object_sql(doc_id: Int, has_range: Bool) -> String {
let range_cols = case has_range {
True -> "coalesce(ocn_range_first,0), coalesce(ocn_range_last,0)"
False -> "0, 0"
}
"select section, seq, ocn, is_a, coalesce(is_of_part,''),
coalesce(is_of_section,''), coalesce(is_of_type,''),
coalesce(heading_level,-1), coalesce(identifier,''),
coalesce(parent_ocn,0), coalesce(last_descendant_ocn,0),
coalesce(children,''), coalesce(ancestors,''),
coalesce(dummy_heading,0), coalesce(object_number_off,0),
coalesce(indent_base,0), coalesce(indent_hang,0),
coalesce(bullet,0), coalesce(lang,''),
coalesce(has_links,0), coalesce(has_notes_reg,0),
coalesce(has_notes_star,0), coalesce(has_images,0),
coalesce(segment,''), coalesce(segment_prev,''),
coalesce(segment_next,''), coalesce(anchor,''),
coalesce(segment_html_is,''),
coalesce(table_cols,0), coalesce(table_widths,''),
coalesce(table_aligns,''), coalesce(table_header,0),
coalesce(code_linenumbers,0),
coalesce(heading_ancestors_text,''), coalesce(sha256,''),
coalesce(text,''), id, coalesce(heading_lev_anchor,''),
coalesce(segment_epub,''), coalesce(segment_epub_is,''), " <> range_cols <> "
from objects where doc_id = " <> int.to_string(doc_id) <> "
order by case section
when 'head' then 1 when 'toc' then 2 when 'body' then 3
when 'endnotes' then 4 when 'glossary' then 5
when 'bibliography' then 6 when 'bookindex' then 7
when 'blurb' then 8 when 'tail' then 9 else 10 end, seq"
}
fn images(conn: sqlight.Connection, object_id: Int) -> List(model.Image) {
let d = {
use name <- decode.field(0, decode.string)
use sha256 <- decode.field(1, decode.string)
use bytes <- decode.field(2, decode.int)
use width <- decode.field(3, decode.int)
use height <- decode.field(4, decode.int)
use missing <- decode.field(5, decode.int)
decode.success(Image(
name: name,
sha256: sha256,
bytes: bytes,
width: width,
height: height,
missing: missing != 0,
fields: dict.new(),
))
}
sqlight.query(
"select name, coalesce(sha256,''), coalesce(bytes,0),
coalesce(width,0), coalesce(height,0), coalesce(missing,0)
from object_images where object_id = "
<> int.to_string(object_id)
<> " order by seq",
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
}
fn links(conn: sqlight.Connection, object_id: Int) -> List(String) {
let d = {
use url <- decode.field(0, decode.string)
decode.success(url)
}
sqlight.query(
"select url from object_links where object_id = "
<> int.to_string(object_id)
<> " order by seq",
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
}
fn anchors(conn: sqlight.Connection, object_id: Int) -> List(String) {
let d = {
use anchor <- decode.field(0, decode.string)
decode.success(anchor)
}
sqlight.query(
"select anchor from object_anchors where object_id = "
<> int.to_string(object_id)
<> " order by seq",
on: conn,
with: [],
expecting: d,
)
|> result.unwrap([])
}
fn one(conn: sqlight.Connection, sql: String) -> String {
let d = {
use v <- decode.field(0, decode.string)
decode.success(v)
}
case sqlight.query(sql, on: conn, with: [], expecting: d) {
Ok([v, ..]) -> v
_ -> ""
}
}
fn has(conn: sqlight.Connection, name: String) -> Bool {
one(
conn,
"select cast(count(*) as text) from sqlite_master where name = '"
<> name
<> "'",
)
!= "0"
}
fn meta_value(conn: sqlight.Connection, doc_id: Int, key: String) -> String {
one(
conn,
"select value from metadata where doc_id = "
<> int.to_string(doc_id)
<> " and key = '"
<> key
<> "'",
)
}
fn major_of(version: String) -> String {
case string.split_once(version, ".") {
Ok(#(major, _)) -> major
Error(_) -> version
}
}
/// The eight heading levels and their indices.
fn level_name(index: Int) -> String {
case index {
0 -> "A"
1 -> "B"
2 -> "C"
3 -> "D"
4 -> "1"
5 -> "2"
6 -> "3"
7 -> "4"
_ -> ""
}
}
/// The JSON columns, read as JSON.
///
/// Not as a character scan that strips brackets and quotes: that is wrong
/// the moment a value holds an escape, and spine's encoder writes "/" as
/// "\/", so every heading containing a slash comes back with a backslash in
/// it. The D library had exactly that bug and all 36 document-languages
/// differed on heading_ancestors_text because of it.
fn json_strings(value: String) -> List(String) {
case value {
"" -> []
v ->
case json.parse(v, decode.list(of: loose_string())) {
Ok(items) -> items
Error(_) -> []
}
}
}
/// An element that may be a string or a number, which is what these columns
/// hold: children and ancestors are int arrays, table_aligns and
/// heading_ancestors_text string arrays, and table_widths an int array
/// except where the columns divide evenly, when it is [33.3333,...]. One
/// table in the reference collection does that, and without the float
/// branch the widths came back as three empty strings: the fallback turned
/// a value it could not read into a value that looked read.
fn loose_string() -> decode.Decoder(String) {
decode.one_of(decode.string, [
decode.int |> decode.map(int.to_string),
decode.float |> decode.map(float.to_string),
decode.success(""),
])
}
fn json_ints(value: String) -> List(Int) {
value
|> json_strings
|> list.filter(fn(s) { s != "" })
|> list.map(fn(s) { s |> int.parse |> result.unwrap(0) })
}
/// Space separated in the text form: table_widths, table_aligns.
fn json_words(value: String) -> String {
value |> json_strings |> string.join(" ")
}
/// heading_ancestors_text is eight slots, joined with "|" in the text form
/// and a JSON array here. The empty slots are significant: they say which
/// levels the heading sits under.
fn json_joined(value: String) -> String {
case json_strings(value) {
[] -> ""
parts -> string.join(parts, "|")
}
}
/// What the database holds and the model does not.
///
/// The text loader meets every property line and counts those it does not
/// keep, so a reader can say what was read and not understood. This loader
/// asks for columns by name, and would never see the ones it did not ask
/// for: it would report that it had understood everything, which is the
/// silence the count exists to prevent. So it counts them, on the
/// conditions under which the `.ssp` writes the same property
/// (specification section 6.3), and the report is the same from either
/// form, as the D loader's is.
fn count_unread(
conn: sqlight.Connection,
doc_id: Int,
document: Document,
) -> Document {
let id = int.to_string(doc_id)
let counts = [
#("ancestors_collapsed", "coalesce(ancestors_collapsed,'') != ''"),
#("dom_status", "coalesce(dom_status,'') != ''"),
#("dom_status_collapsed", "coalesce(dom_status_collapsed,'') != ''"),
#("heading_lev_collapsed", "heading_lev_collapsed is not null"),
#("parent_lev", "coalesce(parent_lev,0) != 0"),
#("segment_lv4_is", "coalesce(segment_lv4_is,'') != ''"),
#("attrib", "coalesce(attrib,'') != ''"),
]
let property =
list.fold(counts, document.unknown.property, fn(acc, c) {
let n =
count(
conn,
"select count(*) from objects where doc_id = " <> id <> " and " <> c.1,
)
case n > 0 {
True -> dict.insert(acc, c.0, n)
False -> acc
}
})
let property = case has(conn, "object_subtoc") {
False -> property
True -> {
let n =
count(
conn,
"select count(*) from object_subtoc s join objects o
on o.id = s.object_id where o.doc_id = " <> id,
)
case n > 0 {
True -> dict.insert(property, "lev4_subtoc", n)
False -> property
}
}
}
model.Document(
..document,
unknown: model.Unknown(..document.unknown, property: property),
)
}
fn count(conn: sqlight.Connection, sql: String) -> Int {
let d = decode.field(0, decode.int, decode.success)
case sqlight.query(sql, on: conn, with: [], expecting: d) {
Ok([n, ..]) -> n
_ -> 0
}
}
/// Every language the database at `path` holds, in manifest order.
pub fn languages_of_file(path: String) -> Result(List(Language), String) {
use conn <- with_connection("file:" <> path <> "?mode=ro", path)
Ok(languages(conn))
}
/// What the database at `path` carries besides the abstraction, by role
/// and storage: role, compression, count, original bytes, stored bytes.
pub fn carried_of_file(path: String) -> Result(List(List(String)), String) {
use conn <- with_connection("file:" <> path <> "?mode=ro", path)
case has(conn, "files") {
False -> Ok([])
True -> {
let d = {
use role <- decode.field(0, decode.string)
use compression <- decode.field(1, decode.string)
use n <- decode.field(2, decode.int)
use bytes <- decode.field(3, decode.int)
use stored <- decode.field(4, decode.int)
decode.success([
role,
compression,
int.to_string(n),
int.to_string(bytes),
int.to_string(stored),
])
}
sqlight.query(
"select role, compression, count(*), sum(bytes), sum(length(data))
from files group by role, compression order by role",
on: conn,
with: [],
expecting: d,
)
|> result.map_error(fn(e) { path <> ": " <> e.message })
}
}
}
#+END_SRC
**** images
#+NAME: ocda_images
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// An image's bytes, from whichever source the document came from.
////
//// The model *names* images, with digest, byte size and pixel size; it does
//// not hold them. That is right - an abstraction of a document is not a
//// bundle of its assets - but a writer of any format that shows images needs
//// the bytes, so something has to know where they are. This is that
//// something, and it is in the library rather than in a writer because the
//// answer depends on the *input form* and not on the output.
////
//// | `.ocda.db` | the `files` table, role 'image', by name |
//// | `.zip` | the archive entry whose path ends in `/image/<name>` |
//// | `.sisupod` | the same, if the frame can be unwrapped, which on the BEAM it cannot |
//// | `.ssp` | beside it: a pod puts the abstraction in `media/abstraction/` and its images in `media/image/` |
import gleam/bit_array
import gleam/dynamic/decode
import gleam/list
import gleam/result
import gleam/string
import ocda/load
import ocda/zip
import simplifile
import sqlight
/// The bytes, or an error saying why not.
pub fn image_bytes(source: String, name: String) -> Result(BitArray, String) {
case load.source_of(source) {
load.OcdaDb -> from_db(source, name)
load.Pod -> from_archive(source, name)
load.Ssp -> from_beside(source, name)
load.Unknown -> Error(source <> ": not a source this library reads")
}
}
/// Can this source give images at all?
///
/// A writer asks before it decides whether to emit them, because an `<img>`
/// pointing at a file it did not include is worse than no image.
pub fn can_give_images(source: String) -> Bool {
case load.source_of(source) {
load.OcdaDb -> True
load.Pod -> zip_readable(source)
load.Ssp -> image_dir_beside(source) != ""
load.Unknown -> False
}
}
fn zip_readable(path: String) -> Bool {
case simplifile.read_bits(path) {
Error(_) -> False
Ok(bytes) ->
case zip.entries(bytes) {
Ok(_) -> True
Error(_) -> False
}
}
}
fn from_db(path: String, name: String) -> Result(BitArray, String) {
case sqlight.open("file:" <> path <> "?mode=ro") {
Error(e) -> Error(path <> ": " <> e.message)
Ok(conn) -> {
let out =
sqlight.query(
"select data from files where role = 'image' and name = ?1",
on: conn,
with: [sqlight.text(name)],
expecting: blob(),
)
|> result.replace_error(path <> ": could not read " <> name)
let _ = sqlight.close(conn)
case out {
Ok([data, ..]) -> Ok(data)
Ok([]) -> Error(name <> ": not in this database")
Error(e) -> Error(e)
}
}
}
}
/// A blob column, read as bytes rather than as text: an image read as text
/// stops at the first zero byte, and a png's ninth byte is zero.
fn blob() -> decode.Decoder(BitArray) {
use v <- decode.field(0, decode.bit_array)
decode.success(v)
}
fn from_archive(path: String, name: String) -> Result(BitArray, String) {
use bytes <- result.try(
simplifile.read_bits(path)
|> result.replace_error(path <> ": cannot read"),
)
use entries <- result.try(zip.entries(bytes))
case list.find(entries, fn(e) { string.ends_with(e.name, "/image/" <> name) }) {
Error(_) -> Error(name <> ": not in this archive")
Ok(entry) -> zip.read(bytes, entry)
}
}
fn from_beside(path: String, name: String) -> Result(BitArray, String) {
case image_dir_beside(path) {
"" -> Error(name <> ": a .ssp outside a pod has no image directory beside it")
dir ->
simplifile.read_bits(dir <> "/" <> name)
|> result.replace_error(dir <> "/" <> name <> ": cannot read")
}
}
/// `media/abstraction/<x>.ssp` -> `media/image/`
fn image_dir_beside(path: String) -> String {
let parts = string.split(path, on: "/")
let dir = case list.reverse(parts) {
[_file, ..rest] -> string.join(list.reverse(rest), "/")
[] -> ""
}
case string.ends_with(dir, "abstraction") {
False -> ""
True -> {
let parent = case list.reverse(string.split(dir, on: "/")) {
[_, ..rest] -> string.join(list.reverse(rest), "/")
[] -> ""
}
let image_dir = parent <> "/image"
case simplifile.is_directory(image_dir) {
Ok(True) -> image_dir
_ -> ""
}
}
}
}
/// Unused here, kept so that a caller can size a read before making it.
pub fn byte_size(b: BitArray) -> Int {
bit_array.byte_size(b)
}
#+END_SRC
*** compression - zip
#+NAME: ocda_zip
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// Enough of the zip format to find one file in a pod and read it.
////
//// Not a zip library. A pod archive holds a handful of entries, spine writes
//// them **stored** (uncompressed) so that the outer zstd frame does the
//// compressing once over the whole thing, and what is wanted from it here is
//// one named entry.
////
//// Deflate is *refused rather than mishandled*. Erlang's `zlib` could
//// inflate it, but a library that says it read an entry it in fact skipped is
//// worse than one that says it cannot, and spine's own archives do not need
//// it.
import gleam/bit_array
import gleam/int
import gleam/list
import gleam/result
import gleam/string
pub type Entry {
Entry(
name: String,
/// 0 stored, 8 deflate
method: Int,
compressed: Int,
uncompressed: Int,
local_offset: Int,
)
}
const eocd_sig = 0x06054b50
const cd_sig = 0x02014b50
const local_sig = 0x04034b50
/// The entries, from the central directory at the end of the file.
pub fn entries(bytes: BitArray) -> Result(List(Entry), String) {
let size = bit_array.byte_size(bytes)
use _ <- result.try(case size >= 22 {
True -> Ok(Nil)
False -> Error("too short to be a zip archive")
})
use eocd <- result.try(find_eocd(bytes, size - 22, lowest(size)))
use count <- result.try(u16(bytes, eocd + 10))
use offset <- result.try(u32(bytes, eocd + 16))
read_central(bytes, offset, count, [])
}
/// The end of central directory record is last, and may be followed by a
/// comment of up to 65535 bytes, so it is searched for backwards.
fn find_eocd(bytes: BitArray, at: Int, lowest: Int) -> Result(Int, String) {
case at < lowest {
True ->
Error(
"no end of central directory record; it does not look like a zip archive",
)
False ->
case u32(bytes, at) {
Ok(sig) if sig == eocd_sig -> Ok(at)
_ -> find_eocd(bytes, at - 1, lowest)
}
}
}
fn lowest(size: Int) -> Int {
case size > 22 + 65_535 {
True -> size - 22 - 65_535
False -> 0
}
}
fn read_central(
bytes: BitArray,
at: Int,
remaining: Int,
acc: List(Entry),
) -> Result(List(Entry), String) {
case remaining {
0 -> Ok(list.reverse(acc))
_ -> {
use sig <- result.try(u32(bytes, at))
use _ <- result.try(case sig == cd_sig {
True -> Ok(Nil)
False ->
Error(
"central directory entry "
<> int.to_string(list.length(acc))
<> " is malformed",
)
})
use method <- result.try(u16(bytes, at + 10))
use compressed <- result.try(u32(bytes, at + 20))
use uncompressed <- result.try(u32(bytes, at + 24))
use name_len <- result.try(u16(bytes, at + 28))
use extra_len <- result.try(u16(bytes, at + 30))
use cmnt_len <- result.try(u16(bytes, at + 32))
use local_offset <- result.try(u32(bytes, at + 42))
use name <- result.try(text(bytes, at + 46, name_len))
let entry =
Entry(
name: name,
method: method,
compressed: compressed,
uncompressed: uncompressed,
local_offset: local_offset,
)
read_central(
bytes,
at + 46 + name_len + extra_len + cmnt_len,
remaining - 1,
[entry, ..acc],
)
}
}
}
/// One entry's bytes, from its local header.
pub fn read(bytes: BitArray, entry: Entry) -> Result(BitArray, String) {
use sig <- result.try(u32(bytes, entry.local_offset))
use _ <- result.try(case sig == local_sig {
True -> Ok(Nil)
False -> Error(entry.name <> ": local header is malformed")
})
use name_len <- result.try(u16(bytes, entry.local_offset + 26))
use extra_len <- result.try(u16(bytes, entry.local_offset + 28))
use _ <- result.try(case entry.method {
0 -> Ok(Nil)
m ->
Error(
entry.name
<> ": compression method "
<> int.to_string(m)
<> "; this reader takes only stored entries, which is what spine writes",
)
})
let start = entry.local_offset + 30 + name_len + extra_len
case bit_array.slice(bytes, start, entry.compressed) {
Ok(slice) -> Ok(slice)
Error(_) -> Error(entry.name <> ": runs past the end of the archive")
}
}
/// The entries whose names end this way, in archive order. Used to find
/// media/abstraction/<uid>.<lang>.ssp without knowing the uid.
pub fn find_suffix(entries: List(Entry), suffix: String) -> List(Entry) {
list.filter(entries, fn(e) { string.ends_with(e.name, suffix) })
}
fn u16(bytes: BitArray, at: Int) -> Result(Int, String) {
case bit_array.slice(bytes, at, 2) {
Ok(<<v:little-size(16)>>) -> Ok(v)
_ -> Error("read past the end of the archive at " <> int.to_string(at))
}
}
fn u32(bytes: BitArray, at: Int) -> Result(Int, String) {
case bit_array.slice(bytes, at, 4) {
Ok(<<v:little-size(32)>>) -> Ok(v)
_ -> Error("read past the end of the archive at " <> int.to_string(at))
}
}
fn text(bytes: BitArray, at: Int, len: Int) -> Result(String, String) {
case bit_array.slice(bytes, at, len) {
Ok(slice) ->
bit_array.to_string(slice)
|> result.replace_error("an entry name is not valid UTF-8")
Error(_) -> Error("an entry name runs past the end of the archive")
}
}
#+END_SRC
*** dump
#+NAME: ocda_dump
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// The model, written out canonically.
////
//// Not an output format: an *oracle*. Two libraries in two languages
//// implement the same model from the same specification, and the cheap way
//// to ask whether they agree is to have each write the whole loaded
//// document as text and diff the two. Byte for byte identical to the D
//// library's `ocda/dump.d`, which is the whole point of it.
////
//// The rules, which both implementations follow:
////
//// - every line is `<key> <value>`, the value running to end of line,
//// and only one free-form value per line;
//// - a field at its default is *omitted*, so the output says what the
//// document has rather than what the type declares;
//// - dictionaries come in sorted key order, because neither language's
//// map has an order worth relying on;
//// - sections come in the fixed order of the format.
////
//// Anything that reads this to reconstruct a document has misunderstood
//// it. Load the `.ssp` or the `.ocda.db`.
import gleam/dict.{type Dict}
import gleam/int
import gleam/list
import gleam/string
import ocda/model.{type Document, type Object}
pub fn document(doc: Document) -> String {
let lines =
[]
|> kv("version", doc.format_version)
|> kv("source_filename", doc.source_filename)
|> entries("source", doc.source)
|> entries("meta", doc.metadata)
|> entries("make", doc.make)
|> entries("doc_has", doc.doc_has)
|> counts(doc)
|> objects(doc)
lines |> list.reverse |> join
}
/// What the loader met and did not understand, sorted.
///
/// Separate from the document dump: it describes the loader, not the
/// document, and the `.ocda.db` loader has nothing to report where the
/// `.ssp` loader does.
pub fn unknown(doc: Document) -> String {
[]
|> numbered("property", doc.unknown.property)
|> numbered("block", doc.unknown.block)
|> numbered("line", doc.unknown.line)
|> list.reverse
|> join
}
fn join(lines: List(String)) -> String {
case lines {
[] -> ""
_ -> string.join(lines, "\n") <> "\n"
}
}
/// Accumulated newest-first and reversed once, so that nothing appends to
/// the tail of a list that grows to a few hundred thousand lines.
fn kv(acc: List(String), key: String, value: String) -> List(String) {
case value {
"" -> acc
v -> [key <> " " <> v, ..acc]
}
}
fn kn(acc: List(String), key: String, value: Int) -> List(String) {
case value {
0 -> acc
n -> [key <> " " <> int.to_string(n), ..acc]
}
}
fn kb(acc: List(String), key: String, value: Bool) -> List(String) {
case value {
False -> acc
True -> [key <> " 1", ..acc]
}
}
fn entries(
acc: List(String),
prefix: String,
d: Dict(String, String),
) -> List(String) {
d
|> dict.to_list
|> list.sort(fn(a, b) { string.compare(a.0, b.0) })
|> list.fold(acc, fn(lines, pair) {
[prefix <> " " <> pair.0 <> " " <> pair.1, ..lines]
})
}
fn numbered(
acc: List(String),
prefix: String,
d: Dict(String, Int),
) -> List(String) {
d
|> dict.to_list
|> list.sort(fn(a, b) { string.compare(a.0, b.0) })
|> list.fold(acc, fn(lines, pair) {
[prefix <> " " <> pair.0 <> " " <> int.to_string(pair.1), ..lines]
})
}
fn counts(acc: List(String), doc: Document) -> List(String) {
list.fold(model.section_names, acc, fn(lines, name) {
case model.section(doc, name) {
[] -> lines
objects ->
[
"section " <> name <> " " <> int.to_string(list.length(objects)),
..lines
]
}
})
}
fn objects(acc: List(String), doc: Document) -> List(String) {
list.fold(model.section_names, acc, fn(lines, name) {
model.section(doc, name)
|> list.index_fold(lines, fn(l, obj, i) {
object(l, name, i, obj)
})
})
}
fn object(
acc: List(String),
section: String,
index: Int,
obj: Object,
) -> List(String) {
let acc = ["object " <> section <> " " <> int.to_string(index), ..acc]
acc
|> kn("ocn", obj.ocn)
|> kv("is_a", obj.is_a)
|> kv("own_section", obj.own_section)
|> kv("level", obj.heading_level)
|> kv("identifier", obj.identifier)
|> kv("part", obj.part)
|> kv("is_of_type", obj.is_of_type)
|> kv("segment_html_is", obj.segment_html_is)
|> kv("segment_epub", obj.segment_epub)
|> kv("segment_epub_is", obj.segment_epub_is)
|> kn("parent", obj.parent_ocn)
|> kn("last_descendant", obj.last_descendant_ocn)
|> kn("ocn_range_first", obj.ocn_range_first)
|> kn("ocn_range_last", obj.ocn_range_last)
|> kv("children", ints(obj.children))
|> kv("ancestors", ints(obj.ancestors))
|> kb("dummy", obj.dummy_heading)
|> kb("ocn_off", obj.ocn_off)
|> kn("indent_base", obj.indent_base)
|> kn("indent_hang", obj.indent_hang)
|> kb("bullet", obj.bullet)
|> kv("lang", obj.lang)
|> kb("has_links", obj.has_links)
|> kb("has_notes_reg", obj.has_notes_reg)
|> kb("has_notes_star", obj.has_notes_star)
|> kb("has_images", obj.has_images)
|> kv("segment", obj.segment)
|> kv("segment_prev", obj.segment_prev)
|> kv("segment_next", obj.segment_next)
|> kv("anchor", obj.anchor)
|> kv("heading_lev_anchor", obj.heading_lev_anchor)
|> kn("table_cols", obj.table_cols)
|> kv("table_widths", obj.table_widths)
|> kv("table_aligns", obj.table_aligns)
|> kb("table_header", obj.table_header)
|> kv("code_syntax", obj.code_syntax)
|> kb("code_linenumbers", obj.code_linenumbers)
|> kv("heading_ancestors_text", obj.heading_ancestors_text)
|> kv("sha256", obj.sha256)
|> links(obj)
|> anchor_tags(obj)
|> images(obj)
|> text(obj)
}
fn links(acc: List(String), obj: Object) -> List(String) {
list.fold(obj.stow_link, acc, fn(lines, url) { kv(lines, "stow_link", url) })
}
fn anchor_tags(acc: List(String), obj: Object) -> List(String) {
list.fold(obj.anchor_tags, acc, fn(lines, a) { kv(lines, "anchor_tag", a) })
}
fn images(acc: List(String), obj: Object) -> List(String) {
list.fold(obj.images, acc, fn(lines, img) {
// the name last, because a filename may hold a space where none of the
// other fields can
let lines =
kv(
lines,
"image",
img.sha256
<> " "
<> int.to_string(img.bytes)
<> " "
<> int.to_string(img.width)
<> "x"
<> int.to_string(img.height)
<> " "
<> case img.missing {
True -> "1"
False -> "0"
}
<> " "
<> img.name,
)
img.fields
|> dict.to_list
|> list.sort(fn(a, b) { string.compare(a.0, b.0) })
|> list.fold(lines, fn(l, pair) {
kv(l, "image_field", pair.0 <> " " <> pair.1)
})
})
}
/// Text, when there is any.
///
/// An object whose only text line is blank holds "" here, indistinguishable
/// from no text at all, because the model joins the lines into one string.
/// Both libraries lose the same distinction in the same place, which is
/// what makes them comparable; it is recorded rather than hidden.
fn text(acc: List(String), obj: Object) -> List(String) {
case obj.text {
"" -> acc
t -> {
let lines = string.split(t, on: "\n")
let acc = kv(acc, "text", int.to_string(list.length(lines)))
list.fold(lines, acc, fn(l, line) { ["| " <> line, ..l] })
}
}
}
fn ints(xs: List(Int)) -> String {
case xs {
[] -> ""
_ -> xs |> list.map(int.to_string) |> string.join(",")
}
}
#+END_SRC
*** erlang
#+NAME: ocda_erlang_ffi
#+HEADER: :no-expand
#+BEGIN_SRC erlang
%% The one thing ocda-lib asks of Erlang directly: a sha256, which OTP's
%% crypto has and the Gleam standard library does not. Upper case hex, as
%% the database stores it and the D library writes it.
-module(ocda_ffi).
-export([sha256_hex/1]).
sha256_hex(Bin) -> binary:encode_hex(crypto:hash(sha256, Bin)).
#+END_SRC
* read
** main
#+NAME: read
#+HEADER: :no-expand
#+BEGIN_SRC gleam
//// ocda-read, in Gleam: reads the abstraction, in any of the forms the
//// library reads, and says what is in it.
////
//// ocda-read [--tree|--outline|--languages|--files|--report-unknown]
//// <file>.ssp | <file>.ocda.db | <file>.zip [lang]
////
//// The modes the Gleam readers had (the summary, the outline, the unknown
//// report, and the database's languages and files), over the library, so
//// that each reads every form. Their output is the D ocda-read's, byte for
//// byte: two readers in unrelated languages, neither written from the other
//// line by line, agreeing is what says each has read the model and not its
//// own idea of it. A `.sisupod` is the one form the Gleam library cannot
//// open (its zstd frame; see `ocda/load_pod`), and it says so.
import gleam/dict
import gleam/int
import gleam/io
import gleam/list
import gleam/result
import gleam/string
import ocda/inventory.{type Language}
import ocda/load
import ocda/model.{type Document, type Object}
/// The format major this reader knows.
const major_read = "2"
type Options {
Options(
tree: Bool,
languages: Bool,
files: Bool,
report_unknown: Bool,
any_version: Bool,
lang: String,
positional: List(String),
)
}
/// Run with the arguments after the program name; returns the exit status.
pub fn run(args: List(String)) -> Int {
case parse(args, Options(False, False, False, False, False, "", [])) {
Error(message) -> {
io.println_error("ocda-read: " <> message <> "; --help lists the options")
2
}
Ok(Options(positional: [], ..)) -> {
help()
0
}
Ok(options) -> read(options)
}
}
fn parse(args: List(String), o: Options) -> Result(Options, String) {
case args {
[] -> Ok(Options(..o, positional: list.reverse(o.positional)))
["--help", ..] | ["-h", ..] -> Ok(Options(..o, positional: []))
["--tree", ..rest] | ["--outline", ..rest] ->
parse(rest, Options(..o, tree: True))
["--languages", ..rest] -> parse(rest, Options(..o, languages: True))
["--files", ..rest] -> parse(rest, Options(..o, files: True))
["--report-unknown", ..rest] ->
parse(rest, Options(..o, report_unknown: True))
["--any-version", ..rest] -> parse(rest, Options(..o, any_version: True))
["--lang", code, ..rest] -> parse(rest, Options(..o, lang: code))
[flag, ..rest] ->
case string.starts_with(flag, "--lang=") {
True -> parse(rest, Options(..o, lang: string.drop_start(flag, 7)))
False ->
case string.starts_with(flag, "-") {
True ->
case
list.contains(
[
"--html", "--llm-text", "--llm-jsonl", "--images", "--verify",
"--validate",
],
flag,
)
{
True ->
Error(flag <> " is a mode of the D ocda-read, not of this one")
False -> Error("Unrecognized option " <> flag)
}
False ->
parse(rest, Options(..o, positional: [flag, ..o.positional]))
}
}
}
}
fn help() -> Nil {
io.println("ocda-read - reads the document abstraction, in any of its forms")
io.println("")
io.println(
"Usage: ocda-read [options] <file>.ssp|<file>.ocda.db|<file>.zip [lang]",
)
io.println("")
io.println(" --tree the headings, as a tree")
io.println(" --outline the same as --tree")
io.println(" --languages the languages the file holds")
io.println(" --files what a .ocda.db carries besides the abstraction")
io.println(" --report-unknown what was read and not understood")
io.println(" --lang=<code> the language to read (default: the first)")
io.println(" --any-version read a format major this reader does not know")
}
fn read(o: Options) -> Int {
let assert [path, ..more] = o.positional
let lang = case o.lang, more {
"", [given, ..] -> given
l, _ -> l
}
let lang_named = lang != ""
let loaded = {
use held <- result.try(inventory.languages(path))
let lang = case lang, held {
"", [first, ..] -> first.lang
l, _ -> l
}
use _ <- result.try(case
held != [] && !list.any(held, fn(l) { l.lang == lang })
{
True ->
Error(
"no language '"
<> lang
<> "' in "
<> path
<> "; it holds: "
<> string.join(list.map(held, fn(l) { l.lang }), " "),
)
False -> Ok(Nil)
})
use doc <- result.try(load.load(path, lang, o.any_version))
Ok(#(held, lang, doc))
}
case loaded {
Error(message) -> {
io.println_error("Error reading " <> path <> ": " <> message)
2
}
Ok(#(held, lang, doc)) ->
case gate(path, doc, o.any_version) {
False -> 3
True -> {
summary(path, doc, held, lang, lang_named)
case o.languages {
True -> print_languages(held)
False -> Nil
}
case o.files {
True -> print_files(path)
False -> Nil
}
case o.tree {
True -> tree(doc)
False -> Nil
}
case o.report_unknown {
True -> report_unknown(doc)
False -> Nil
}
case o.tree || o.languages || o.files || o.report_unknown {
True -> Nil
False ->
io.println(
"\n(this is the summary: --help lists the modes, each adding its output)",
)
}
0
}
}
}
}
/// The major part, and refuse what is not known.
fn gate(path: String, doc: Document, any_version: Bool) -> Bool {
case doc.format_version, model.version_major(doc) == major_read, any_version {
"", _, _ -> {
io.println_error("warning: " <> path <> " declares no format version")
True
}
_, True, _ -> True
v, False, True -> {
io.println_error(
"warning: "
<> path
<> " is format v"
<> v
<> ", this reader knows v"
<> major_read
<> ".x; reading anyway",
)
True
}
v, False, False -> {
io.println_error(
"error: "
<> path
<> " is format v"
<> v
<> ", this reader knows v"
<> major_read
<> ".x",
)
io.println_error(
" a major version differs: a property may have changed meaning or gone away.",
)
io.println_error(" --any-version reads it regardless.")
False
}
}
}
const sections = [
"head", "toc", "body", "endnotes", "glossary", "bibliography", "bookindex",
"blurb", "tail",
]
/// The sections whose images are counted: every one but the tail, as the D
/// reader counts them.
const image_sections = [
"head", "toc", "body", "endnotes", "glossary", "bibliography", "bookindex",
"blurb",
]
fn summary(
path: String,
doc: Document,
held: List(Language),
lang: String,
lang_named: Bool,
) -> Nil {
io.println("Read: " <> path)
case doc.format_version {
"" -> Nil
v -> io.println(" Format: v" <> v)
}
case dict.get(doc.source, "language") {
Error(_) -> Nil
Ok(language) -> {
let of = case dict.get(doc.source, "languages") {
Ok(ls) -> " of " <> ls
Error(_) -> ""
}
let digest = case dict.get(doc.source, "digest") {
Ok(d) -> ", markup digest " <> string.slice(d, 0, 16) <> "..."
Error(_) -> ""
}
io.println(" Source: " <> language <> of <> digest)
}
}
case list.length(held) > 1 && !lang_named {
True -> io.println(" (reading " <> lang <> "; --lang=<code> for another)")
False -> Nil
}
io.println(" Title: " <> model.meta(doc, "title.main"))
io.println(" Author: " <> model.meta(doc, "creator.author"))
io.println(
" Sections: "
<> string.join(
list.map(sections, fn(s) {
s <> "=" <> int.to_string(list.length(model.section(doc, s)))
}),
" ",
),
)
let records =
list.fold(image_sections, 0, fn(n, s) {
list.fold(model.section(doc, s), n, fn(n, o) {
n + list.length(o.images)
})
})
case records {
0 -> Nil
1 -> io.println(" Images: 1 record")
n -> io.println(" Images: " <> int.to_string(n) <> " records")
}
}
fn print_languages(held: List(Language)) -> Nil {
io.println("")
io.println(" lang source ssp digest")
list.each(held, fn(l) {
let digest = case string.length(l.ssp_digest) > 16 {
True -> string.slice(l.ssp_digest, 0, 16) <> "..."
False -> l.ssp_digest
}
io.println(
" "
<> string.pad_end(l.lang, 7, " ")
<> " "
<> string.pad_end(l.source_filename, 31, " ")
<> " "
<> digest,
)
})
}
fn print_files(path: String) -> Nil {
io.println("")
case inventory.is_carrier(path) {
False ->
io.println(
" carried files: only a .ocda.db carries files; this is "
<> load.source_name(load.source_of(path)),
)
True ->
case inventory.carried(path) {
Error(message) -> io.println_error("error: " <> message)
Ok([]) -> io.println(" carries no files")
Ok(rows) -> {
io.println(" carried files:")
io.println(" role stored n original in the file")
list.each(rows, fn(r) {
io.println(
" "
<> string.pad_end(r.role, 9, " ")
<> " "
<> string.pad_end(r.compression, 7, " ")
<> " "
<> string.pad_end(r.count, 5, " ")
<> " "
<> string.pad_end(r.bytes, 13, " ")
<> " "
<> r.stored,
)
})
}
}
}
}
/// The headings, as a tree: from the document's root heading, down the
/// children each heading lists, as the D reader walks it.
fn tree(doc: Document) -> Nil {
io.println("Document: " <> model.meta(doc, "title.main"))
case model.meta(doc, "title.subtitle") {
"" -> Nil
sub -> io.println(" " <> sub)
}
io.println("Author: " <> model.meta(doc, "creator.author"))
io.println("")
let headings =
model.section(doc, "body")
|> list.filter(fn(o) { o.is_a == "heading" && o.ocn > 0 })
|> list.map(fn(o) { #(o.ocn, o) })
|> dict.from_list
case model.section(doc, "head") {
[root, ..] if root.is_a == "heading" -> {
io.println(heading_line(root, 0))
walk(root, headings, 1)
}
_ -> Nil
}
}
fn walk(parent: Object, headings: dict.Dict(Int, Object), depth: Int) -> Nil {
list.each(parent.children, fn(ocn) {
case dict.get(headings, ocn) {
Ok(child) -> {
io.println(heading_line(child, depth))
walk(child, headings, depth + 1)
}
Error(_) -> Nil
}
})
}
fn heading_line(o: Object, depth: Int) -> String {
let level = case o.heading_level {
"" -> "?"
l -> l
}
let ocn = case o.ocn > 0 {
True -> " [" <> int.to_string(o.ocn) <> "]"
False -> ""
}
string.repeat(" ", depth) <> level <> "~" <> ocn <> " " <> strip_markup(o.text)
}
/// The internal markers a heading's text may carry, removed for display, as
/// the D reader removes them.
fn strip_markup(text: String) -> String {
text
|> string.replace("⑆*", "")
|> string.replace("⑆!", "")
|> string.replace("⑆/", "")
|> string.replace("⑆_", "")
|> string.replace("⑆^", "")
|> string.replace("⑆,", "")
|> string.replace("┨", "")
|> string.replace("┣", "")
|> string.replace("┙", " ")
|> string.replace("┘", "\n")
}
/// Say what was read and not understood.
fn report_unknown(doc: Document) -> Nil {
let u = doc.unknown
case model.any_unknown(u) {
False ->
io.println(
"\nread and understood: every property, block and line was known",
)
True -> {
io.println("\nread and NOT understood:")
section_of_unknown(u.property, " properties ignored (", fn(name, n) {
" ."
<> string.pad_end(name, 26, " ")
<> " "
<> string.pad_start(int.to_string(n), 8, " ")
})
section_of_unknown(u.block, " blocks ignored (", fn(name, n) {
" @"
<> string.pad_end(name, 26, " ")
<> " "
<> string.pad_start(int.to_string(n), 8, " ")
})
case dict.size(u.line) {
0 -> Nil
_ -> {
io.println(" lines of no known shape, by first character:")
dict.to_list(u.line)
|> list.sort(fn(a, b) { string.compare(a.0, b.0) })
|> list.each(fn(e) {
io.println(
" "
<> string.pad_end("\"" <> e.0 <> "\"", 27, " ")
<> " "
<> string.pad_start(int.to_string(e.1), 8, " "),
)
})
}
}
io.println(
" (ignoring these is conforming within a major version; the count is so that it is not silent)",
)
}
}
}
fn section_of_unknown(
counts: dict.Dict(String, Int),
heading: String,
line: fn(String, Int) -> String,
) -> Nil {
case dict.size(counts) {
0 -> Nil
n -> {
io.println(heading <> int.to_string(n) <> " distinct):")
dict.to_list(counts)
|> list.sort(fn(a, b) { string.compare(a.0, b.0) })
|> list.each(fn(e) { io.println(line(e.0, e.1)) })
}
}
}
#+END_SRC
* test
#+NAME: test
#+HEADER: :no-expand
#+BEGIN_SRC gleam
import gleam/dict
import gleam/list
import simplifile
import gleam/string
import gleeunit
import gleeunit/should
import ocda/dump
import ocda/load
import ocda/load_ssp
import ocda/model
pub fn main() {
gleeunit.main()
}
const minimal = "% SiSU Document Abstraction v2.0
% Source: example.sst
@source {
language: en
languages: en
digest: ABC
}
@meta {
title.main: An Example
}
@body {
[1] heading :A the_title
.part: frontmatter
.sha256: DEAD
| An Example
[2] para
.part: body
.parent: 1
| First line
|
| Third line, after a blank one
}
"
pub fn version_test() {
let doc = load_ssp.parse(minimal)
doc.format_version |> should.equal("2.0")
model.version_major(doc) |> should.equal("2")
doc.source_filename |> should.equal("example.sst")
}
pub fn preamble_test() {
let doc = load_ssp.parse(minimal)
model.meta(doc, "title.main") |> should.equal("An Example")
}
pub fn objects_test() {
let doc = load_ssp.parse(minimal)
let body = model.section(doc, "body")
body |> list.length |> should.equal(2)
}
/// The blank line in the middle of an object's text is kept, and so is the
/// count: three lines, not two.
pub fn blank_text_line_test() {
let doc = load_ssp.parse(minimal)
case model.section(doc, "body") {
[_, second] ->
second.text
|> should.equal("First line\n\nThird line, after a blank one")
_ -> should.fail()
}
}
/// A heading's identifier comes from its declaration line; an object whose
/// identifier is simply its ocn has it derived, because the text form does
/// not write what it can work out.
pub fn derived_identifier_test() {
let doc = load_ssp.parse(minimal)
case model.section(doc, "body") {
[first, second] -> {
first.identifier |> should.equal("the_title")
second.identifier |> should.equal("2")
}
_ -> should.fail()
}
}
pub fn source_of_test() {
load.source_of("a/b.ssp") |> should.equal(load.Ssp)
load.source_of("a/b.ocda.db") |> should.equal(load.OcdaDb)
load.source_of("a/b.sst") |> should.equal(load.Unknown)
}
/// The dump omits a field at its default, so a minimal document gives a
/// short dump and every line in it is a fact.
pub fn dump_test() {
let text = dump.document(load_ssp.parse(minimal))
text |> string.contains(contain: "version 2.0") |> should.be_true
text |> string.contains(contain: "meta title.main An Example") |> should.be_true
text |> string.contains(contain: "object body 0") |> should.be_true
text |> string.contains(contain: "level A") |> should.be_true
// a false boolean is not written at all
text |> string.contains(contain: "bullet") |> should.be_false
}
/// A property is read, which the fixture above had to be corrected to show:
/// a property line is `.name: value` at the start of the line, and an
/// indented one is a line of no known shape. The fixture indented them, so
/// every property in it was being counted as malformed and the tests around
/// it passed for the wrong reason.
pub fn property_test() {
let doc = load_ssp.parse(minimal)
case model.section(doc, "body") {
[first, second] -> {
first.part |> should.equal("frontmatter")
first.sha256 |> should.equal("DEAD")
second.parent_ocn |> should.equal(1)
}
_ -> should.fail()
}
// and nothing in the fixture is malformed any more
dict_size(doc.unknown.line) |> should.equal(0)
}
@external(erlang, "maps", "size")
fn dict_size(d: dict.Dict(a, b)) -> Int
/// What a path is, including the two archive forms.
pub fn pod_source_test() {
load.source_of("a/b.sisupod") |> should.equal(load.Pod)
load.source_of("a/b.zip") |> should.equal(load.Pod)
}
/// A zstd-wrapped archive is refused, and the refusal says why rather than
/// claiming the file is malformed. This is the one place the D and Gleam
/// libraries differ in what they accept, and it is a packaging limit: the
/// only zstd on the BEAM is a NIF that fetches zstd in its own build.
pub fn zstd_refusal_test() {
let path = "test/fixture-zstd-frame.sisupod"
let assert Ok(_) = simplifile.write_bits(path, <<0x28, 0xB5, 0x2F, 0xFD, 0>>)
let assert Error(message) = load.load(path, "", False)
message |> string.contains(contain: "zstd") |> should.be_true
message |> string.contains(contain: "zstd -d") |> should.be_true
let _ = simplifile.delete(path)
Nil
}
#+END_SRC
* org-tangles
** ocda lib
#+HEADER: :tangle ../gleam/src/ocda_lib.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_lib>>
#+END_SRC
** ocda
*** model
#+HEADER: :tangle ../gleam/src/ocda/model.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<model>>
#+END_SRC
*** what to load
**** inventory
#+HEADER: :tangle ../gleam/src/ocda/inventory.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_inventory>>
#+END_SRC
**** load
***** load
#+HEADER: :tangle ../gleam/src/ocda/load.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_load>>
#+END_SRC
***** load pod
#+HEADER: :tangle ../gleam/src/ocda/load_pod.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_load_pod>>
#+END_SRC
***** load ssp
#+HEADER: :tangle ../gleam/src/ocda/load_ssp.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_load_ssp>>
#+END_SRC
***** load db
#+HEADER: :tangle ../gleam/src/ocda/load_db.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_load_db>>
#+END_SRC
**** images
#+HEADER: :tangle ../gleam/src/ocda/images.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_images>>
#+END_SRC
*** compression - zip
#+HEADER: :tangle ../gleam/src/ocda/zip.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_zip>>
#+END_SRC
*** dump
#+HEADER: :tangle ../gleam/src/ocda/dump.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<ocda_dump>>
#+END_SRC
*** erlang
#+HEADER: :tangle ../gleam/src/ocda_ffi.erl
#+HEADER: :noweb yes
#+BEGIN_SRC org
%%<<doc_header_including_copyright_and_license>>
<<ocda_erlang_ffi>>
#+END_SRC
** read
*** main
#+HEADER: :tangle ../gleam/src/read/main.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<read>>
#+END_SRC
** test
#+HEADER: :tangle ../gleam/test/ocda_lib_test.gleam
#+HEADER: :noweb yes
#+BEGIN_SRC org
////<<doc_header_including_copyright_and_license>>
<<test>>
#+END_SRC
* config
** nix flake.nix :flake:
#+HEADER: :tangle ../gleam/flake.nix
#+HEADER: :noweb yes
#+BEGIN_SRC nix
{
description = "ocda-lib: the object-centric document abstraction as a Gleam library";
inputs.nixpkgs.url = "<<nixpkgs_unstable>>";
outputs = { self, nixpkgs }:
let
system = "x86_64-linux"; # adjust for aarch64-linux / darwin
pkgs = import nixpkgs { inherit system; };
name = "ocda_lib";
/* rebar3 with the port compiler already in it.
esqlite builds a NIF, and its rebar3 configuration asks for the
`pc` plugin, which rebar3 would otherwise fetch from Hex at build
time: impossible in a sandbox, and the build fails with
"missing_package pc". nixpkgs carries the plugin, so the answer is
a rebar3 that has it before it starts.
*/
rebar3-pc = pkgs.beamPackages.rebar3WithPlugins {
plugins = [ pkgs.beamPackages.pc ];
};
/* The Hex dependencies, as manifest.toml pins them.
.
There is no Gleam builder in nixpkgs and `gleam build` fetches from
Hex, so a sandboxed build cannot reach them. A fixed output
derivation may, because its result is pinned by hash.
.
When a dependency changes, manifest.toml changes and this hash must
change with it: build, take the hash nix reports, put it here.
*/
deps = pkgs.stdenv.mkDerivation {
pname = "${name}-deps";
version = "0.1.0";
src = ./.;
nativeBuildInputs = [ pkgs.gleam pkgs.cacert ];
buildPhase = ''
export HOME=$TMPDIR
gleam deps download
'';
installPhase = ''
mkdir -p $out
cp -r build/packages/* $out/
'';
dontFixup = true;
outputHashMode = "recursive";
outputHashAlgo = "sha256";
outputHash = "sha256-nWU753YRsC28gsaGyy+A3aZaWf15ctULYiUlvsfyB1c=";
};
in {
packages.${system} = {
default = self.packages.${system}.${name};
/* Shipped as an Erlang shipment rather than as an escript, because
sqlite on the BEAM is a NIF: esqlite compiles its own sqlite into
a shared object, and a NIF cannot be loaded from inside an
escript archive, the runtime needing a real file on disk. The
shipment keeps priv/ on disk, so it loads.
*/
${name} = pkgs.stdenv.mkDerivation {
pname = "ocda-lib";
version = "0.1.0";
src = ./.;
nativeBuildInputs = [
pkgs.gleam
pkgs.erlang
rebar3-pc
pkgs.makeWrapper
];
buildPhase = ''
runHook preBuild
export HOME=$TMPDIR
# the dependencies, in place of the fetch gleam would do
mkdir -p build/packages
cp -r ${deps}/* build/packages/
chmod -R u+w build/packages
gleam export erlang-shipment
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/lib $out/bin
cp -r build/erlang-shipment $out/lib/${name}
makeWrapper $out/lib/${name}/entrypoint.sh $out/bin/ocda-lib \
--add-flags run \
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.erlang pkgs.coreutils ]}
# the reader under its own name, as the D flake installs it
makeWrapper $out/lib/${name}/entrypoint.sh $out/bin/ocda-read \
--add-flags "run read" \
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.erlang pkgs.coreutils ]}
runHook postInstall
'';
meta = {
description = "the abstraction as a Gleam library, with its reader, dump and agreement check";
mainProgram = "ocda-lib";
};
};
};
devShells.${system}.default = pkgs.mkShell {
packages = [ pkgs.gleam pkgs.erlang pkgs.rebar3 pkgs.sqlite ];
};
};
}
#+END_SRC
** README.md
#+HEADER: :tangle ../gleam/README.md
#+HEADER: :noweb yes
#+BEGIN_SRC md
# ocda-lib, in Gleam
The abstraction's model and both its loaders, as a Gleam library, with its
reader and the two programs that put it to the question.
| | |
|------------------|-----------------------------------------------------------------------------------------|
| `ocda/model` | the document, the object, the image. Depends on nothing but the standard library |
| `ocda/load_ssp` | text -> model |
| `ocda/load_db` | sqlite -> model |
| `ocda/load` | what a path is, and loading it |
| `ocda/inventory` | what a file holds beyond the one document: its languages, and what a `.ocda.db` carries |
| `ocda/dump` | the model written out canonically, as an oracle |
| `read/main` | `ocda-read`, the reader |
| `ocda_ffi.erl` | a sha256, from OTP's crypto, which the standard library lacks |
## Use
```gleam
import ocda/load
import ocda/model
case load.load(path, "en", False) {
Error(why) -> io.println_error(why)
Ok(doc) -> {
// and from here a writer neither knows nor cares which of the two
// files it was handed
list.each(model.section(doc, "body"), fn(obj) { ... })
}
}
```
## The reader
```sh
nix build
./result/bin/ocda-read [--tree|--outline|--languages|--files|--report-unknown]
<file>.ssp|<file>.ocda.db|<file>.zip [lang]
```
`ocda-lib read`, installed also as `ocda-read`. The modes the Gleam readers
had, over the library, so each reads every form this library reads; the
others are the D reader's. **Its output is the D `ocda-read`'s, byte for
byte**, in every mode both have. In `src/read/`, because Gleam compiles
nothing outside `src/`; a program depending on the library compiles it too,
and does not use it.
A `.sisupod` it refuses, saying why: the zstd frame, below.
## The two programs
```sh
nix build
./result/bin/ocda-lib agree <doc>.ssp <doc>.ocda.db [lang]
./result/bin/ocda-lib dump [--unknown] <file>.ssp|<file>.ocda.db [lang]
```
`agree` asks whether the two loaders give the same model. `dump` writes
the whole model out canonically, and is the stronger check of the two,
because it is **byte for byte what the D library's `ocda-dump` writes**.
So the four questions can all be asked with `diff`:
| | |
|-----------------------------|-----------------------------|
| D: `.ssp` == `.ocda.db` | 36 of 36 document-languages |
| Gleam: `.ssp` == `.ocda.db` | 36 of 36 |
| `.ssp`: D == Gleam | 36 of 36 |
| `.ocda.db`: D == Gleam | 36 of 36 |
## Deliberately a mirror of the D library
Field for field, name for name, including where that is not the most
Gleamish choice:
- `text` is one `String` with the lines joined by newline, not a
`List(String)`. So an object whose only text line is blank is
indistinguishable from an object with no text, *in both languages, in the
same place*. A difference that existed in one and not the other would be
worse than a loss both share, because it would show up in every dump and
mean nothing.
- the properties are typed fields rather than a list of pairs. A writer
wants `obj.parent_ocn`, not a lookup that might miss.
The point is that the two agree. Making them agree is much cheaper when
they are shaped alike, and the shape is the specification's, not either
language's.
## What the agreement found
Four disagreements, none of which a comparison of section counts or of a
handful of fields would have shown. All four are recorded in the D
library's history; the short version:
1. `.identifier` and `.anchor` are omitted by the text form when they can
be worked out (the identifier is the ocn, the anchor is the segment).
Both loaders now derive them. Over one document that is 1,314
identifiers.
2. `make` and `doc_has` are one metadata table in the database,
distinguished by a key prefix. Both loaders unprefix them.
3. The JSON columns must be *parsed*, not scanned: the encoder writes `/`
as `\/` and every heading with a slash in it came back wrong.
4. `translation.ocn_aligned` is in the database and cannot be in a `.ssp`,
which is one language. It is a fact about the file, so neither loader
puts it in the document.
## Build
```sh
nix build # sandboxed, no network
nix develop -c gleam test
```
Shipped as an Erlang shipment rather than an escript, because sqlite on the
BEAM is a NIF and a NIF cannot be loaded from inside an escript archive.
The dependency hash in `flake.nix` pins what `manifest.toml` pins; change
one and the other must change with it.
## Format
Specified in **sisudoc-abstraction-format**: `ocda-model.org` for the model,
`ssp-format-specification.org` and `ocda-db-format-specification.org` for the
two serialisations. At format **2.x**.
#+END_SRC
** gleam.toml
#+HEADER: :tangle ../gleam/gleam.toml
#+HEADER: :noweb yes
#+BEGIN_SRC toml
name = "ocda_lib"
version = "0.1.0"
description = "the object-centric document abstraction as a library: the model, and loaders for its two serialisations"
licences = ["AGPL-3.0-or-later"]
[dependencies]
gleam_stdlib = ">= 1.0.0 and < 2.0.0"
argv = ">= 1.1.0 and < 2.0.0"
simplifile = ">= 2.7.0 and < 3.0.0"
sqlight = ">= 1.0.0 and < 2.0.0"
gleam_json = ">= 3.0.0 and < 4.0.0"
[dev-dependencies]
gleeunit = ">= 1.0.0 and < 2.0.0"
#+END_SRC
* org includes
** project version
#+NAME: spine_version
#+HEADER: :noweb yes
#+BEGIN_SRC emacs-lisp
<<./sisudoc_spine_version_info_and_doc_header_including_copyright_and_license.org:spine_project_version()>>
#+END_SRC
** year
#+NAME: year
#+HEADER: :noweb yes
#+BEGIN_SRC emacs-lisp
<<./sisudoc_spine_version_info_and_doc_header_including_copyright_and_license.org:year()>>
#+END_SRC
** document header including copyright & license
#+NAME: doc_header_including_copyright_and_license
#+HEADER: :noweb yes
#+BEGIN_SRC emacs-lisp
<<./sisudoc_spine_version_info_and_doc_header_including_copyright_and_license.org:spine_doc_header_including_copyright_and_license()>>
#+END_SRC
* nixpkgs source
#+NAME: nixpkgs_unstable
#+HEADER: :noweb yes
#+BEGIN_SRC emacs-lisp
<<./sisudoc_spine_version_info_and_doc_header_including_copyright_and_license.org:nixpkgs_unstable()>>
#+END_SRC
* __END__
|