1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
//! Parser for deb822 style files.
//!
//! This parser can be used to parse files in the deb822 format, while preserving
//! all whitespace and comments. It is based on the [rowan] library, which is a
//! lossless parser library for Rust.
//!
//! Once parsed, the file can be traversed or modified, and then written back to
//! a file.
//!
//! # Example
//!
//! ```rust
//! use deb822_lossless::Deb822;
//! use std::str::FromStr;
//!
//! let input = r###"Package: deb822-lossless
//! ## Comments are preserved
//! Maintainer: Jelmer Vernooij <jelmer@debian.org>
//! Homepage: https://github.com/jelmer/deb822-lossless
//! Section: rust
//!
//! Package: deb822-lossless
//! Architecture: any
//! Description: Lossless parser for deb822 style files.
//! This parser can be used to parse files in the deb822 format, while preserving
//! all whitespace and comments. It is based on the [rowan] library, which is a
//! lossless parser library for Rust.
//! "###;
//!
//! let deb822 = Deb822::from_str(input).unwrap();
//! assert_eq!(deb822.paragraphs().count(), 2);
//! let homepage = deb822.paragraphs().nth(0).unwrap().get("Homepage");
//! assert_eq!(homepage.as_deref(), Some("https://github.com/jelmer/deb822-lossless"));
//! ```
use crate::{
lex::lex,
lex::SyntaxKind::{self, *},
Indentation,
};
use rowan::ast::AstNode;
use std::path::Path;
use std::str::FromStr;
/// A positioned parse error containing location information.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PositionedParseError {
/// The error message
pub message: String,
/// The text range where the error occurred
pub range: rowan::TextRange,
/// Optional error code for categorization
pub code: Option<String>,
}
impl std::fmt::Display for PositionedParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for PositionedParseError {}
/// List of encountered syntax errors.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParseError(pub Vec<String>);
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for err in &self.0 {
writeln!(f, "{}", err)?;
}
Ok(())
}
}
impl std::error::Error for ParseError {}
/// Error parsing deb822 control files
#[derive(Debug)]
pub enum Error {
/// A syntax error was encountered while parsing the file.
ParseError(ParseError),
/// An I/O error was encountered while reading the file.
IoError(std::io::Error),
/// An invalid value was provided (e.g., empty continuation lines).
InvalidValue(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self {
Error::ParseError(err) => write!(f, "{}", err),
Error::IoError(err) => write!(f, "{}", err),
Error::InvalidValue(msg) => write!(f, "Invalid value: {}", msg),
}
}
}
impl From<ParseError> for Error {
fn from(err: ParseError) -> Self {
Self::ParseError(err)
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
impl std::error::Error for Error {}
/// Second, implementing the `Language` trait teaches rowan to convert between
/// these two SyntaxKind types, allowing for a nicer SyntaxNode API where
/// "kinds" are values from our `enum SyntaxKind`, instead of plain u16 values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Lang {}
impl rowan::Language for Lang {
type Kind = SyntaxKind;
fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) }
}
fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
kind.into()
}
}
/// GreenNode is an immutable tree, which is cheap to change,
/// but doesn't contain offsets and parent pointers.
use rowan::GreenNode;
/// You can construct GreenNodes by hand, but a builder
/// is helpful for top-down parsers: it maintains a stack
/// of currently in-progress nodes
use rowan::GreenNodeBuilder;
/// The parse results are stored as a "green tree".
/// We'll discuss working with the results later
pub(crate) struct Parse {
pub(crate) green_node: GreenNode,
#[allow(unused)]
pub(crate) errors: Vec<String>,
pub(crate) positioned_errors: Vec<PositionedParseError>,
}
pub(crate) fn parse(text: &str) -> Parse {
struct Parser<'a> {
/// input tokens, including whitespace,
/// in *reverse* order.
tokens: Vec<(SyntaxKind, &'a str)>,
/// the in-progress tree.
builder: GreenNodeBuilder<'static>,
/// the list of syntax errors we've accumulated
/// so far.
errors: Vec<String>,
/// positioned errors with location information
positioned_errors: Vec<PositionedParseError>,
/// All tokens with their positions in forward order for position tracking
token_positions: Vec<(SyntaxKind, rowan::TextSize, rowan::TextSize)>,
/// current token index (counting from the end since tokens are in reverse)
current_token_index: usize,
}
impl<'a> Parser<'a> {
/// Skip to next paragraph boundary for error recovery
fn skip_to_paragraph_boundary(&mut self) {
while self.current().is_some() {
match self.current() {
Some(NEWLINE) => {
self.bump();
// Check if next line starts a new paragraph (key at start of line)
if self.at_paragraph_start() {
break;
}
}
_ => {
self.bump();
}
}
}
}
/// Check if we're at the start of a new paragraph
fn at_paragraph_start(&self) -> bool {
match self.current() {
Some(KEY) => true,
Some(COMMENT) => true,
None => true, // EOF is a valid paragraph boundary
_ => false,
}
}
/// Attempt to recover from entry parsing errors
fn recover_entry(&mut self) {
// Skip to end of current line
while self.current().is_some() && self.current() != Some(NEWLINE) {
self.bump();
}
// Consume the newline if present
if self.current() == Some(NEWLINE) {
self.bump();
}
}
fn parse_entry(&mut self) {
// Handle leading comments
while self.current() == Some(COMMENT) {
self.bump();
match self.current() {
Some(NEWLINE) => {
self.bump();
}
None => {
return;
}
Some(g) => {
self.builder.start_node(ERROR.into());
self.add_positioned_error(
format!("expected newline after comment, got {g:?}"),
Some("unexpected_token_after_comment".to_string()),
);
self.bump();
self.builder.finish_node();
self.recover_entry();
return;
}
}
}
self.builder.start_node(ENTRY.into());
let mut entry_has_errors = false;
// Parse the key
if self.current() == Some(KEY) {
self.bump();
self.skip_ws();
} else {
entry_has_errors = true;
self.builder.start_node(ERROR.into());
// Enhanced error recovery for malformed keys
match self.current() {
Some(VALUE) | Some(WHITESPACE) => {
self.add_positioned_error(
"field name cannot start with whitespace or special characters"
.to_string(),
Some("invalid_field_name".to_string()),
);
// Try to consume what might be an intended key
while self.current() == Some(VALUE) || self.current() == Some(WHITESPACE) {
self.bump();
}
}
Some(COLON) => {
self.add_positioned_error(
"field name missing before colon".to_string(),
Some("missing_field_name".to_string()),
);
}
Some(NEWLINE) => {
self.add_positioned_error(
"empty line where field expected".to_string(),
Some("empty_field_line".to_string()),
);
self.builder.finish_node();
self.builder.finish_node();
return;
}
_ => {
self.add_positioned_error(
format!("expected field name, got {:?}", self.current()),
Some("missing_key".to_string()),
);
if self.current().is_some() {
self.bump();
}
}
}
self.builder.finish_node();
}
// Parse the colon
if self.current() == Some(COLON) {
self.bump();
self.skip_ws();
} else {
entry_has_errors = true;
self.builder.start_node(ERROR.into());
// Enhanced error recovery for missing colon
match self.current() {
Some(VALUE) => {
self.add_positioned_error(
"missing colon ':' after field name".to_string(),
Some("missing_colon".to_string()),
);
// Don't consume the value, let it be parsed as the field value
}
Some(NEWLINE) => {
self.add_positioned_error(
"field name without value (missing colon and value)".to_string(),
Some("incomplete_field".to_string()),
);
self.builder.finish_node();
self.builder.finish_node();
return;
}
Some(KEY) => {
self.add_positioned_error(
"field name followed by another field name (missing colon and value)"
.to_string(),
Some("consecutive_field_names".to_string()),
);
// Don't consume the next key, let it be parsed as a new entry
self.builder.finish_node();
self.builder.finish_node();
return;
}
_ => {
self.add_positioned_error(
format!("expected colon ':', got {:?}", self.current()),
Some("missing_colon".to_string()),
);
if self.current().is_some() {
self.bump();
}
}
}
self.builder.finish_node();
}
// Parse the value (potentially multi-line)
loop {
while self.current() == Some(WHITESPACE) || self.current() == Some(VALUE) {
self.bump();
}
match self.current() {
None => {
break;
}
Some(NEWLINE) => {
self.bump();
}
Some(KEY) => {
// We've hit another field, this entry is complete
break;
}
Some(g) => {
self.builder.start_node(ERROR.into());
self.add_positioned_error(
format!("unexpected token in field value: {g:?}"),
Some("unexpected_value_token".to_string()),
);
self.bump();
self.builder.finish_node();
}
}
// Check for continuation lines or inline comments
if self.current() == Some(INDENT) {
self.bump();
self.skip_ws();
// After indent and whitespace, we must have actual content (VALUE token)
// An empty continuation line (indent followed immediately by newline or EOF)
// is not valid according to Debian Policy
if self.current() == Some(NEWLINE) || self.current().is_none() {
self.builder.start_node(ERROR.into());
self.add_positioned_error(
"empty continuation line (line with only whitespace)".to_string(),
Some("empty_continuation_line".to_string()),
);
self.builder.finish_node();
break;
}
} else if self.current() == Some(COMMENT) {
// Comment line within a multi-line field value (e.g. commented-out
// continuation lines in Build-Depends). Consume the comment and
// continue looking for more continuation lines.
self.bump();
} else {
break;
}
}
self.builder.finish_node();
// If the entry had errors, we might want to recover
if entry_has_errors && !self.at_paragraph_start() && self.current().is_some() {
self.recover_entry();
}
}
fn parse_paragraph(&mut self) {
self.builder.start_node(PARAGRAPH.into());
let mut consecutive_errors = 0;
const MAX_CONSECUTIVE_ERRORS: usize = 5;
while self.current() != Some(NEWLINE) && self.current().is_some() {
let error_count_before = self.positioned_errors.len();
// Check if we're at a valid entry start
if self.current() == Some(KEY) || self.current() == Some(COMMENT) {
self.parse_entry();
// Reset consecutive error count if we successfully parsed something
if self.positioned_errors.len() == error_count_before {
consecutive_errors = 0;
} else {
consecutive_errors += 1;
}
} else {
// We're not at a valid entry start, this is an error
consecutive_errors += 1;
self.builder.start_node(ERROR.into());
match self.current() {
Some(VALUE) => {
self.add_positioned_error(
"orphaned text without field name".to_string(),
Some("orphaned_text".to_string()),
);
// Consume the orphaned text
while self.current() == Some(VALUE)
|| self.current() == Some(WHITESPACE)
{
self.bump();
}
}
Some(COLON) => {
self.add_positioned_error(
"orphaned colon without field name".to_string(),
Some("orphaned_colon".to_string()),
);
self.bump();
}
Some(INDENT) => {
self.add_positioned_error(
"unexpected indentation without field".to_string(),
Some("unexpected_indent".to_string()),
);
self.bump();
}
_ => {
self.add_positioned_error(
format!(
"unexpected token at paragraph level: {:?}",
self.current()
),
Some("unexpected_paragraph_token".to_string()),
);
self.bump();
}
}
self.builder.finish_node();
}
// If we have too many consecutive errors, skip to paragraph boundary
if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
self.add_positioned_error(
"too many consecutive parse errors, skipping to next paragraph".to_string(),
Some("parse_recovery".to_string()),
);
self.skip_to_paragraph_boundary();
break;
}
}
self.builder.finish_node();
}
fn parse(mut self) -> Parse {
// Make sure that the root node covers all source
self.builder.start_node(ROOT.into());
while self.current().is_some() {
self.skip_ws_and_newlines();
if self.current().is_some() {
self.parse_paragraph();
}
}
// Don't forget to eat *trailing* whitespace
self.skip_ws_and_newlines();
// Close the root node.
self.builder.finish_node();
// Turn the builder into a GreenNode
Parse {
green_node: self.builder.finish(),
errors: self.errors,
positioned_errors: self.positioned_errors,
}
}
/// Advance one token, adding it to the current branch of the tree builder.
fn bump(&mut self) {
let (kind, text) = self.tokens.pop().unwrap();
self.builder.token(kind.into(), text);
self.current_token_index += 1;
}
/// Peek at the first unprocessed token
fn current(&self) -> Option<SyntaxKind> {
self.tokens.last().map(|(kind, _)| *kind)
}
/// Add a positioned error at the current position
fn add_positioned_error(&mut self, message: String, code: Option<String>) {
let range = if self.current_token_index < self.token_positions.len() {
let (_, start, end) = self.token_positions[self.current_token_index];
rowan::TextRange::new(start, end)
} else {
// Default to end of text if no current token
let end = self
.token_positions
.last()
.map(|(_, _, end)| *end)
.unwrap_or_else(|| rowan::TextSize::from(0));
rowan::TextRange::new(end, end)
};
self.positioned_errors.push(PositionedParseError {
message: message.clone(),
range,
code,
});
self.errors.push(message);
}
fn skip_ws(&mut self) {
while self.current() == Some(WHITESPACE) || self.current() == Some(COMMENT) {
self.bump()
}
}
fn skip_ws_and_newlines(&mut self) {
while self.current() == Some(WHITESPACE)
|| self.current() == Some(COMMENT)
|| self.current() == Some(NEWLINE)
{
self.builder.start_node(EMPTY_LINE.into());
while self.current() != Some(NEWLINE) && self.current().is_some() {
self.bump();
}
if self.current() == Some(NEWLINE) {
self.bump();
}
self.builder.finish_node();
}
}
}
let mut tokens = lex(text).collect::<Vec<_>>();
// Build token positions in forward order
let mut token_positions = Vec::new();
let mut position = rowan::TextSize::from(0);
for (kind, text) in &tokens {
let start = position;
let end = start + rowan::TextSize::of(*text);
token_positions.push((*kind, start, end));
position = end;
}
// Reverse tokens for parsing (but keep positions in forward order)
tokens.reverse();
let current_token_index = 0;
Parser {
tokens,
builder: GreenNodeBuilder::new(),
errors: Vec::new(),
positioned_errors: Vec::new(),
token_positions,
current_token_index,
}
.parse()
}
/// To work with the parse results we need a view into the
/// green tree - the Syntax tree.
/// It is also immutable, like a GreenNode,
/// but it contains parent pointers, offsets, and
/// has identity semantics.
type SyntaxNode = rowan::SyntaxNode<Lang>;
#[allow(unused)]
type SyntaxToken = rowan::SyntaxToken<Lang>;
#[allow(unused)]
type SyntaxElement = rowan::NodeOrToken<SyntaxNode, SyntaxToken>;
impl Parse {
#[cfg(test)]
fn syntax(&self) -> SyntaxNode {
SyntaxNode::new_root(self.green_node.clone())
}
fn root_mut(&self) -> Deb822 {
Deb822::cast(SyntaxNode::new_root_mut(self.green_node.clone())).unwrap()
}
}
/// Structural equality on the green nodes of two syntax trees, with an
/// O(1) pointer-identity fast path.
///
/// Returns true iff the two green trees are value-equal. When the underlying
/// `GreenNodeData` happens to share an address (typical after `snapshot()`
/// without intervening mutations) the comparison short-circuits in O(1);
/// otherwise it falls through to rowan's structural `PartialEq` on
/// `GreenNodeData`, which is O(n) in the worst case.
fn green_eq(a: &SyntaxNode, b: &SyntaxNode) -> bool {
let a_green = a.green();
let b_green = b.green();
let a_ref: &rowan::GreenNodeData = &a_green;
let b_ref: &rowan::GreenNodeData = &b_green;
std::ptr::eq(a_ref as *const _, b_ref as *const _) || a_ref == b_ref
}
/// Calculate line and column (both 0-indexed) for the given offset in the tree.
/// Column is measured in bytes from the start of the line.
fn line_col_at_offset(node: &SyntaxNode, offset: rowan::TextSize) -> (usize, usize) {
let root = node.ancestors().last().unwrap_or_else(|| node.clone());
let mut line = 0;
let mut last_newline_offset = rowan::TextSize::from(0);
for element in root.preorder_with_tokens() {
if let rowan::WalkEvent::Enter(rowan::NodeOrToken::Token(token)) = element {
if token.text_range().start() >= offset {
break;
}
// Count newlines and track position of last one
for (idx, _) in token.text().match_indices('\n') {
line += 1;
last_newline_offset =
token.text_range().start() + rowan::TextSize::from((idx + 1) as u32);
}
}
}
let column: usize = (offset - last_newline_offset).into();
(line, column)
}
macro_rules! ast_node {
($ast:ident, $kind:ident) => {
#[doc = "An AST node representing a `"]
#[doc = stringify!($ast)]
#[doc = "`."]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct $ast(SyntaxNode);
impl $ast {
#[allow(unused)]
fn cast(node: SyntaxNode) -> Option<Self> {
if node.kind() == $kind {
Some(Self(node))
} else {
None
}
}
/// Get the line number (0-indexed) where this node starts.
pub fn line(&self) -> usize {
line_col_at_offset(&self.0, self.0.text_range().start()).0
}
/// Get the column number (0-indexed, in bytes) where this node starts.
pub fn column(&self) -> usize {
line_col_at_offset(&self.0, self.0.text_range().start()).1
}
/// Get both line and column (0-indexed) where this node starts.
/// Returns (line, column) where column is measured in bytes from the start of the line.
pub fn line_col(&self) -> (usize, usize) {
line_col_at_offset(&self.0, self.0.text_range().start())
}
}
impl AstNode for $ast {
type Language = Lang;
fn can_cast(kind: SyntaxKind) -> bool {
kind == $kind
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::cast(syntax)
}
fn syntax(&self) -> &SyntaxNode {
&self.0
}
}
impl std::fmt::Display for $ast {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0.text())
}
}
};
}
ast_node!(Deb822, ROOT);
ast_node!(Paragraph, PARAGRAPH);
ast_node!(Entry, ENTRY);
impl Default for Deb822 {
fn default() -> Self {
Self::new()
}
}
impl Deb822 {
/// Capture an independent snapshot of the current state.
///
/// The returned value shares the underlying immutable [`rowan::GreenNode`]
/// data with `self` at the time of the call, but lives in its own mutable
/// tree: subsequent mutations to `self` do not propagate to the snapshot,
/// and vice versa. Pair with [`Self::tree_eq`] to detect whether
/// mutations have happened since the snapshot was taken.
///
/// # Example
/// ```
/// use deb822_lossless::Deb822;
///
/// let text = "Package: foo\n";
/// let deb822: Deb822 = text.parse().unwrap();
/// let snap = deb822.snapshot();
///
/// let mut para = deb822.paragraphs().next().unwrap();
/// para.set("Package", "modified");
///
/// let snap_para = snap.paragraphs().next().unwrap();
/// assert_eq!(snap_para.get("Package").as_deref(), Some("foo"));
/// ```
pub fn snapshot(&self) -> Self {
Deb822(SyntaxNode::new_root_mut(self.0.green().into_owned()))
}
/// O(1) check: returns true iff `self` and `other` point to the same
/// underlying syntax tree instance.
///
/// This is a pointer-identity check (not a value comparison). It is
/// useful with [`Self::snapshot`] to detect whether `self` has been
/// mutated since the snapshot was taken: every mutation produces a new
/// green tree, so `original.tree_eq(&snapshot)` flips from `true` to
/// `false` on the first mutation. Two independently-parsed trees with
/// identical contents are *not* `tree_eq`. For value equality, use
/// [`PartialEq`].
pub fn tree_eq(&self, other: &Self) -> bool {
green_eq(&self.0, &other.0)
}
/// Create a new empty deb822 file.
pub fn new() -> Deb822 {
let mut builder = GreenNodeBuilder::new();
builder.start_node(ROOT.into());
builder.finish_node();
Deb822(SyntaxNode::new_root_mut(builder.finish()))
}
/// Parse deb822 text, returning a Parse result
pub fn parse(text: &str) -> crate::Parse<Deb822> {
crate::Parse::parse_deb822(text)
}
/// Provide a formatter that can handle indentation and trailing separators
///
/// # Arguments
/// * `control` - The control file to format
/// * `indentation` - The indentation to use
/// * `immediate_empty_line` - Whether the value should always start with an empty line. If true,
/// then the result becomes something like "Field:\n value". This parameter
/// only applies to the values that will be formatted over more than one line.
/// * `max_line_length_one_liner` - If set, then this is the max length of the value
/// if it is crammed into a "one-liner" value. If the value(s) fit into
/// one line, this parameter will overrule immediate_empty_line.
/// * `sort_paragraphs` - If set, then this function will sort the paragraphs according to the
/// given function.
/// * `sort_entries` - If set, then this function will sort the entries according to the
/// given function.
#[must_use]
pub fn wrap_and_sort(
&self,
sort_paragraphs: Option<&dyn Fn(&Paragraph, &Paragraph) -> std::cmp::Ordering>,
wrap_and_sort_paragraph: Option<&dyn Fn(&Paragraph) -> Paragraph>,
) -> Deb822 {
let mut builder = GreenNodeBuilder::new();
builder.start_node(ROOT.into());
let mut current = vec![];
let mut paragraphs = vec![];
for c in self.0.children_with_tokens() {
match c.kind() {
PARAGRAPH => {
paragraphs.push((
current,
Paragraph::cast(c.as_node().unwrap().clone()).unwrap(),
));
current = vec![];
}
COMMENT | ERROR => {
current.push(c);
}
EMPTY_LINE => {
current.extend(
c.as_node()
.unwrap()
.children_with_tokens()
.skip_while(|c| matches!(c.kind(), EMPTY_LINE | NEWLINE | WHITESPACE)),
);
}
_ => {}
}
}
if let Some(sort_paragraph) = sort_paragraphs {
paragraphs.sort_by(|a, b| {
let a_key = &a.1;
let b_key = &b.1;
sort_paragraph(a_key, b_key)
});
}
for (i, paragraph) in paragraphs.into_iter().enumerate() {
if i > 0 {
builder.start_node(EMPTY_LINE.into());
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
}
for c in paragraph.0.into_iter() {
builder.token(c.kind().into(), c.as_token().unwrap().text());
}
let new_paragraph = if let Some(ref ws) = wrap_and_sort_paragraph {
ws(¶graph.1)
} else {
paragraph.1
};
inject(&mut builder, new_paragraph.0);
}
for c in current {
builder.token(c.kind().into(), c.as_token().unwrap().text());
}
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
/// Normalize the spacing around field separators (colons) for all entries in all paragraphs in place.
///
/// This ensures that there is exactly one space after the colon and before the value
/// for each field in every paragraph. This is a lossless operation that preserves the
/// field names, values, and comments, but normalizes the whitespace formatting.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// use std::str::FromStr;
///
/// let input = "Field1: value1\nField2:value2\n\nField3: value3\n";
/// let mut deb822 = Deb822::from_str(input).unwrap();
///
/// deb822.normalize_field_spacing();
/// assert_eq!(deb822.to_string(), "Field1: value1\nField2: value2\n\nField3: value3\n");
/// ```
pub fn normalize_field_spacing(&mut self) -> bool {
let mut any_changed = false;
// Collect paragraphs to avoid borrowing issues
let mut paragraphs: Vec<_> = self.paragraphs().collect();
// Normalize each paragraph
for para in &mut paragraphs {
if para.normalize_field_spacing() {
any_changed = true;
}
}
any_changed
}
/// Returns an iterator over all paragraphs in the file.
pub fn paragraphs(&self) -> impl Iterator<Item = Paragraph> {
self.0.children().filter_map(Paragraph::cast)
}
/// Returns paragraphs that intersect with the given text range.
///
/// A paragraph is included if its text range overlaps with the provided range.
///
/// # Arguments
///
/// * `range` - The text range to query
///
/// # Returns
///
/// An iterator over paragraphs that intersect with the range
///
/// # Examples
///
/// ```
/// use deb822_lossless::{Deb822, TextRange};
///
/// let input = "Package: foo\n\nPackage: bar\n\nPackage: baz\n";
/// let deb822 = Deb822::parse(input).tree();
///
/// // Query paragraphs in the first half of the document
/// let range = TextRange::new(0.into(), 20.into());
/// let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
/// assert!(paras.len() >= 1);
/// ```
pub fn paragraphs_in_range(
&self,
range: rowan::TextRange,
) -> impl Iterator<Item = Paragraph> + '_ {
self.paragraphs().filter(move |p| {
let para_range = p.text_range();
// Check if ranges overlap: para starts before range ends AND para ends after range starts
para_range.start() < range.end() && para_range.end() > range.start()
})
}
/// Find the paragraph that contains the given text offset.
///
/// # Arguments
///
/// * `offset` - The text offset to query
///
/// # Returns
///
/// The paragraph containing the offset, or None if no paragraph contains it
///
/// # Examples
///
/// ```
/// use deb822_lossless::{Deb822, TextSize};
///
/// let input = "Package: foo\n\nPackage: bar\n";
/// let deb822 = Deb822::parse(input).tree();
///
/// // Find paragraph at offset 5 (within first paragraph)
/// let para = deb822.paragraph_at_position(TextSize::from(5));
/// assert!(para.is_some());
/// ```
pub fn paragraph_at_position(&self, offset: rowan::TextSize) -> Option<Paragraph> {
self.paragraphs().find(|p| {
let range = p.text_range();
range.contains(offset)
})
}
/// Find the paragraph at the given line number (0-indexed).
///
/// # Arguments
///
/// * `line` - The line number to query (0-indexed)
///
/// # Returns
///
/// The paragraph at the given line, or None if no paragraph is at that line
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
///
/// let input = "Package: foo\nVersion: 1.0\n\nPackage: bar\n";
/// let deb822 = Deb822::parse(input).tree();
///
/// // Find paragraph at line 0
/// let para = deb822.paragraph_at_line(0);
/// assert!(para.is_some());
/// ```
pub fn paragraph_at_line(&self, line: usize) -> Option<Paragraph> {
self.paragraphs().find(|p| {
let start_line = p.line();
let range = p.text_range();
let text_str = self.0.text().to_string();
let text_before_end = &text_str[..range.end().into()];
let end_line = text_before_end.lines().count().saturating_sub(1);
line >= start_line && line <= end_line
})
}
/// Find the entry at the given line and column position.
///
/// # Arguments
///
/// * `line` - The line number (0-indexed)
/// * `col` - The column number (0-indexed)
///
/// # Returns
///
/// The entry at the given position, or None if no entry is at that position
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
///
/// let input = "Package: foo\nVersion: 1.0\n";
/// let deb822 = Deb822::parse(input).tree();
///
/// // Find entry at line 0, column 0
/// let entry = deb822.entry_at_line_col(0, 0);
/// assert!(entry.is_some());
/// ```
pub fn entry_at_line_col(&self, line: usize, col: usize) -> Option<Entry> {
// Convert line/col to text offset
let text_str = self.0.text().to_string();
let offset: usize = text_str.lines().take(line).map(|l| l.len() + 1).sum();
let position = rowan::TextSize::from((offset + col) as u32);
// Find the entry that contains this position
for para in self.paragraphs() {
for entry in para.entries() {
let range = entry.text_range();
if range.contains(position) {
return Some(entry);
}
}
}
None
}
/// Converts the perceptual paragraph index to the node index.
fn convert_index(&self, index: usize) -> Option<usize> {
let mut current_pos = 0usize;
if index == 0 {
return Some(0);
}
for (i, node) in self.0.children_with_tokens().enumerate() {
if node.kind() == PARAGRAPH {
if current_pos == index {
return Some(i);
}
current_pos += 1;
}
}
None
}
/// Delete trailing empty lines after specified node and before any non-empty line nodes.
fn delete_trailing_space(&self, start: usize) {
for (i, node) in self.0.children_with_tokens().enumerate() {
if i < start {
continue;
}
if node.kind() != EMPTY_LINE {
return;
}
// this is not a typo, the index will shift by one after deleting the node
// so instead of deleting using `i`, we use `start` as the start index
self.0.splice_children(start..start + 1, []);
}
}
/// Shared internal function to insert a new paragraph into the file.
fn insert_empty_paragraph(&mut self, index: Option<usize>) -> Paragraph {
let paragraph = Paragraph::new();
let mut to_insert = vec![];
if self.0.children().count() > 0 {
let mut builder = GreenNodeBuilder::new();
builder.start_node(EMPTY_LINE.into());
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
to_insert.push(SyntaxNode::new_root_mut(builder.finish()).into());
}
to_insert.push(paragraph.0.clone().into());
let insertion_point = match index {
Some(i) => {
if to_insert.len() > 1 {
to_insert.swap(0, 1);
}
i
}
None => self.0.children().count(),
};
self.0
.splice_children(insertion_point..insertion_point, to_insert);
paragraph
}
/// Insert a new empty paragraph into the file after specified index.
///
/// # Examples
///
/// ```
/// use deb822_lossless::{Deb822, Paragraph};
/// let mut d: Deb822 = vec![
/// vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
/// vec![("A", "B"), ("C", "D")].into_iter().collect(),
/// ]
/// .into_iter()
/// .collect();
/// let mut p = d.insert_paragraph(0);
/// p.set("Foo", "Baz");
/// assert_eq!(d.to_string(), "Foo: Baz\n\nFoo: Bar\nBaz: Qux\n\nA: B\nC: D\n");
/// let mut another = d.insert_paragraph(1);
/// another.set("Y", "Z");
/// assert_eq!(d.to_string(), "Foo: Baz\n\nY: Z\n\nFoo: Bar\nBaz: Qux\n\nA: B\nC: D\n");
/// ```
pub fn insert_paragraph(&mut self, index: usize) -> Paragraph {
self.insert_empty_paragraph(self.convert_index(index))
}
/// Remove the paragraph at the specified index from the file.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// let mut d: Deb822 = vec![
/// vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
/// vec![("A", "B"), ("C", "D")].into_iter().collect(),
/// ]
/// .into_iter()
/// .collect();
/// d.remove_paragraph(0);
/// assert_eq!(d.to_string(), "A: B\nC: D\n");
/// d.remove_paragraph(0);
/// assert_eq!(d.to_string(), "");
/// ```
pub fn remove_paragraph(&mut self, index: usize) {
if let Some(index) = self.convert_index(index) {
self.0.splice_children(index..index + 1, []);
self.delete_trailing_space(index);
}
}
/// Move a paragraph from one index to another.
///
/// This moves the paragraph at `from_index` to `to_index`, shifting other paragraphs as needed.
/// If `from_index` equals `to_index`, no operation is performed.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// let mut d: Deb822 = vec![
/// vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
/// vec![("A", "B"), ("C", "D")].into_iter().collect(),
/// vec![("X", "Y"), ("Z", "W")].into_iter().collect(),
/// ]
/// .into_iter()
/// .collect();
/// d.move_paragraph(0, 2);
/// assert_eq!(d.to_string(), "A: B\nC: D\n\nX: Y\nZ: W\n\nFoo: Bar\nBaz: Qux\n");
/// ```
pub fn move_paragraph(&mut self, from_index: usize, to_index: usize) {
if from_index == to_index {
return;
}
// Get the paragraph count to validate indices
let paragraph_count = self.paragraphs().count();
if from_index >= paragraph_count || to_index >= paragraph_count {
return;
}
// Clone the paragraph node we want to move
let paragraph_to_move = self.paragraphs().nth(from_index).unwrap().0.clone();
// Remove the paragraph from its original position
let from_physical = self.convert_index(from_index).unwrap();
// Determine the range to remove (paragraph and possibly preceding EMPTY_LINE)
let mut start_idx = from_physical;
if from_physical > 0 {
if let Some(prev_node) = self.0.children_with_tokens().nth(from_physical - 1) {
if prev_node.kind() == EMPTY_LINE {
start_idx = from_physical - 1;
}
}
}
// Remove the paragraph and any preceding EMPTY_LINE
self.0.splice_children(start_idx..from_physical + 1, []);
self.delete_trailing_space(start_idx);
// Calculate the physical insertion point
// After removal, we need to determine where to insert
// The semantics are: the moved paragraph ends up at logical index to_index in the final result
let insert_at = if to_index > from_index {
// Moving forward: after removal, to_index-1 paragraphs should be before the moved one
// So we insert after paragraph at index (to_index - 1)
let target_idx = to_index - 1;
if let Some(target_physical) = self.convert_index(target_idx) {
target_physical + 1
} else {
// If convert_index returns None, insert at the end
self.0.children().count()
}
} else {
// Moving backward: after removal, to_index paragraphs should be before the moved one
// So we insert at paragraph index to_index
if let Some(target_physical) = self.convert_index(to_index) {
target_physical
} else {
self.0.children().count()
}
};
// Build the nodes to insert
let mut to_insert = vec![];
// Determine if we need to add an EMPTY_LINE before the paragraph
let needs_empty_line_before = if insert_at == 0 {
// At the beginning - no empty line before
false
} else if insert_at > 0 {
// Check if there's already an EMPTY_LINE at the insertion point
if let Some(node_at_insert) = self.0.children_with_tokens().nth(insert_at - 1) {
node_at_insert.kind() != EMPTY_LINE
} else {
false
}
} else {
false
};
if needs_empty_line_before {
let mut builder = GreenNodeBuilder::new();
builder.start_node(EMPTY_LINE.into());
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
to_insert.push(SyntaxNode::new_root_mut(builder.finish()).into());
}
to_insert.push(paragraph_to_move.into());
// Determine if we need to add an EMPTY_LINE after the paragraph
let needs_empty_line_after = if insert_at < self.0.children().count() {
// There are nodes after - check if next node is EMPTY_LINE
if let Some(node_after) = self.0.children_with_tokens().nth(insert_at) {
node_after.kind() != EMPTY_LINE
} else {
false
}
} else {
false
};
if needs_empty_line_after {
let mut builder = GreenNodeBuilder::new();
builder.start_node(EMPTY_LINE.into());
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
to_insert.push(SyntaxNode::new_root_mut(builder.finish()).into());
}
// Insert at the new position
self.0.splice_children(insert_at..insert_at, to_insert);
}
/// Add a new empty paragraph to the end of the file.
pub fn add_paragraph(&mut self) -> Paragraph {
self.insert_empty_paragraph(None)
}
/// Swap two paragraphs by their indices.
///
/// This method swaps the positions of two paragraphs while preserving their
/// content, formatting, whitespace, and comments. The paragraphs at positions
/// `index1` and `index2` will exchange places.
///
/// # Arguments
///
/// * `index1` - The index of the first paragraph to swap
/// * `index2` - The index of the second paragraph to swap
///
/// # Panics
///
/// Panics if either `index1` or `index2` is out of bounds.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// let mut d: Deb822 = vec![
/// vec![("Foo", "Bar")].into_iter().collect(),
/// vec![("A", "B")].into_iter().collect(),
/// vec![("X", "Y")].into_iter().collect(),
/// ]
/// .into_iter()
/// .collect();
/// d.swap_paragraphs(0, 2);
/// assert_eq!(d.to_string(), "X: Y\n\nA: B\n\nFoo: Bar\n");
/// ```
pub fn swap_paragraphs(&mut self, index1: usize, index2: usize) {
if index1 == index2 {
return;
}
// Collect all children
let mut children: Vec<_> = self.0.children().map(|n| n.clone().into()).collect();
// Find the child indices for paragraphs
let mut para_child_indices = vec![];
for (child_idx, child) in self.0.children().enumerate() {
if child.kind() == PARAGRAPH {
para_child_indices.push(child_idx);
}
}
// Validate paragraph indices
if index1 >= para_child_indices.len() {
panic!("index1 {} out of bounds", index1);
}
if index2 >= para_child_indices.len() {
panic!("index2 {} out of bounds", index2);
}
let child_idx1 = para_child_indices[index1];
let child_idx2 = para_child_indices[index2];
// Swap the children in the vector
children.swap(child_idx1, child_idx2);
// Replace all children
let num_children = children.len();
self.0.splice_children(0..num_children, children);
}
/// Read a deb822 file from the given path.
pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
let text = std::fs::read_to_string(path)?;
Ok(Self::from_str(&text)?)
}
/// Read a deb822 file from the given path, ignoring any syntax errors.
pub fn from_file_relaxed(
path: impl AsRef<Path>,
) -> Result<(Self, Vec<String>), std::io::Error> {
let text = std::fs::read_to_string(path)?;
Ok(Self::from_str_relaxed(&text))
}
/// Parse a deb822 file from a string, allowing syntax errors.
pub fn from_str_relaxed(s: &str) -> (Self, Vec<String>) {
let parsed = parse(s);
(parsed.root_mut(), parsed.errors)
}
/// Read a deb822 file from a Read object.
pub fn read<R: std::io::Read>(mut r: R) -> Result<Self, Error> {
let mut buf = String::new();
r.read_to_string(&mut buf)?;
Ok(Self::from_str(&buf)?)
}
/// Read a deb822 file from a Read object, allowing syntax errors.
pub fn read_relaxed<R: std::io::Read>(mut r: R) -> Result<(Self, Vec<String>), std::io::Error> {
let mut buf = String::new();
r.read_to_string(&mut buf)?;
Ok(Self::from_str_relaxed(&buf))
}
}
fn inject(builder: &mut GreenNodeBuilder, node: SyntaxNode) {
builder.start_node(node.kind().into());
for child in node.children_with_tokens() {
match child {
rowan::NodeOrToken::Node(child) => {
inject(builder, child);
}
rowan::NodeOrToken::Token(token) => {
builder.token(token.kind().into(), token.text());
}
}
}
builder.finish_node();
}
impl FromIterator<Paragraph> for Deb822 {
fn from_iter<T: IntoIterator<Item = Paragraph>>(iter: T) -> Self {
let mut builder = GreenNodeBuilder::new();
builder.start_node(ROOT.into());
for (i, paragraph) in iter.into_iter().enumerate() {
if i > 0 {
builder.start_node(EMPTY_LINE.into());
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
}
inject(&mut builder, paragraph.0);
}
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
}
impl From<Vec<(String, String)>> for Paragraph {
fn from(v: Vec<(String, String)>) -> Self {
v.into_iter().collect()
}
}
impl From<Vec<(&str, &str)>> for Paragraph {
fn from(v: Vec<(&str, &str)>) -> Self {
v.into_iter().collect()
}
}
impl FromIterator<(String, String)> for Paragraph {
fn from_iter<T: IntoIterator<Item = (String, String)>>(iter: T) -> Self {
let mut builder = GreenNodeBuilder::new();
builder.start_node(PARAGRAPH.into());
for (key, value) in iter {
builder.start_node(ENTRY.into());
builder.token(KEY.into(), &key);
builder.token(COLON.into(), ":");
builder.token(WHITESPACE.into(), " ");
for (i, line) in value.split('\n').enumerate() {
if i > 0 {
builder.token(INDENT.into(), " ");
}
builder.token(VALUE.into(), line);
builder.token(NEWLINE.into(), "\n");
}
builder.finish_node();
}
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
}
impl<'a> FromIterator<(&'a str, &'a str)> for Paragraph {
fn from_iter<T: IntoIterator<Item = (&'a str, &'a str)>>(iter: T) -> Self {
let mut builder = GreenNodeBuilder::new();
builder.start_node(PARAGRAPH.into());
for (key, value) in iter {
builder.start_node(ENTRY.into());
builder.token(KEY.into(), key);
builder.token(COLON.into(), ":");
builder.token(WHITESPACE.into(), " ");
for (i, line) in value.split('\n').enumerate() {
if i > 0 {
builder.token(INDENT.into(), " ");
}
builder.token(VALUE.into(), line);
builder.token(NEWLINE.into(), "\n");
}
builder.finish_node();
}
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
}
/// Detected indentation pattern for multi-line field values
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndentPattern {
/// All fields use a fixed number of spaces for indentation
Fixed(usize),
/// Each field's indentation matches its field name length + 2 (for ": ")
FieldNameLength,
}
impl IndentPattern {
/// Convert the pattern to a concrete indentation string for a given field name
fn to_string(&self, field_name: &str) -> String {
match self {
IndentPattern::Fixed(spaces) => " ".repeat(*spaces),
IndentPattern::FieldNameLength => " ".repeat(field_name.len() + 2),
}
}
}
impl Paragraph {
/// Create a new empty paragraph.
pub fn new() -> Paragraph {
let mut builder = GreenNodeBuilder::new();
builder.start_node(PARAGRAPH.into());
builder.finish_node();
Paragraph(SyntaxNode::new_root_mut(builder.finish()))
}
/// Capture an independent snapshot of this paragraph.
///
/// See [`Deb822::snapshot`] for details.
pub fn snapshot(&self) -> Self {
Paragraph(SyntaxNode::new_root_mut(self.0.green().into_owned()))
}
/// O(1) check: returns true iff `self` and `snapshot` reference the same
/// syntax-tree state. See [`Deb822::tree_eq`].
pub fn tree_eq(&self, other: &Self) -> bool {
green_eq(&self.0, &other.0)
}
/// Returns the text range covered by this paragraph.
pub fn text_range(&self) -> rowan::TextRange {
self.0.text_range()
}
/// Returns entries that intersect with the given text range.
///
/// An entry is included if its text range overlaps with the provided range.
///
/// # Arguments
///
/// * `range` - The text range to query
///
/// # Returns
///
/// An iterator over entries that intersect with the range
///
/// # Examples
///
/// ```
/// use deb822_lossless::{Deb822, TextRange};
///
/// let input = "Package: foo\nVersion: 1.0\nArchitecture: amd64\n";
/// let deb822 = Deb822::parse(input).tree();
/// let para = deb822.paragraphs().next().unwrap();
///
/// // Query entries in a specific range
/// let range = TextRange::new(0.into(), 15.into());
/// let entries: Vec<_> = para.entries_in_range(range).collect();
/// assert!(entries.len() >= 1);
/// ```
pub fn entries_in_range(&self, range: rowan::TextRange) -> impl Iterator<Item = Entry> + '_ {
self.entries().filter(move |e| {
let entry_range = e.text_range();
// Check if ranges overlap
entry_range.start() < range.end() && entry_range.end() > range.start()
})
}
/// Find the entry that contains the given text offset.
///
/// # Arguments
///
/// * `offset` - The text offset to query
///
/// # Returns
///
/// The entry containing the offset, or None if no entry contains it
///
/// # Examples
///
/// ```
/// use deb822_lossless::{Deb822, TextSize};
///
/// let input = "Package: foo\nVersion: 1.0\n";
/// let deb822 = Deb822::parse(input).tree();
/// let para = deb822.paragraphs().next().unwrap();
///
/// // Find entry at offset 5 (within "Package: foo")
/// let entry = para.entry_at_position(TextSize::from(5));
/// assert!(entry.is_some());
/// ```
pub fn entry_at_position(&self, offset: rowan::TextSize) -> Option<Entry> {
self.entries().find(|e| {
let range = e.text_range();
range.contains(offset)
})
}
/// Reformat this paragraph
///
/// # Arguments
/// * `indentation` - The indentation to use
/// * `immediate_empty_line` - Whether multi-line values should always start with an empty line
/// * `max_line_length_one_liner` - If set, then this is the max length of the value if it is
/// crammed into a "one-liner" value
/// * `sort_entries` - If set, then this function will sort the entries according to the given
/// function
/// * `format_value` - If set, then this function will format the value according to the given
/// function
#[must_use]
pub fn wrap_and_sort(
&self,
indentation: Indentation,
immediate_empty_line: bool,
max_line_length_one_liner: Option<usize>,
sort_entries: Option<&dyn Fn(&Entry, &Entry) -> std::cmp::Ordering>,
format_value: Option<&dyn Fn(&str, &str) -> String>,
) -> Paragraph {
let mut builder = GreenNodeBuilder::new();
let mut current = vec![];
let mut entries = vec![];
builder.start_node(PARAGRAPH.into());
for c in self.0.children_with_tokens() {
match c.kind() {
ENTRY => {
entries.push((current, Entry::cast(c.as_node().unwrap().clone()).unwrap()));
current = vec![];
}
ERROR | COMMENT => {
current.push(c);
}
_ => {}
}
}
if let Some(sort_entry) = sort_entries {
entries.sort_by(|a, b| {
let a_key = &a.1;
let b_key = &b.1;
sort_entry(a_key, b_key)
});
}
for (pre, entry) in entries.into_iter() {
for c in pre.into_iter() {
builder.token(c.kind().into(), c.as_token().unwrap().text());
}
inject(
&mut builder,
entry
.wrap_and_sort(
indentation,
immediate_empty_line,
max_line_length_one_liner,
format_value,
)
.0,
);
}
for c in current {
builder.token(c.kind().into(), c.as_token().unwrap().text());
}
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
/// Normalize the spacing around field separators (colons) for all entries in place.
///
/// This ensures that there is exactly one space after the colon and before the value
/// for each field in the paragraph. This is a lossless operation that preserves the
/// field names, values, and comments, but normalizes the whitespace formatting.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// use std::str::FromStr;
///
/// let input = "Field1: value1\nField2:value2\n";
/// let mut deb822 = Deb822::from_str(input).unwrap();
/// let mut para = deb822.paragraphs().next().unwrap();
///
/// para.normalize_field_spacing();
/// assert_eq!(para.to_string(), "Field1: value1\nField2: value2\n");
/// ```
pub fn normalize_field_spacing(&mut self) -> bool {
let mut any_changed = false;
// Collect entries to avoid borrowing issues
let mut entries: Vec<_> = self.entries().collect();
// Normalize each entry
for entry in &mut entries {
if entry.normalize_field_spacing() {
any_changed = true;
}
}
any_changed
}
/// Returns the value of the given key in the paragraph.
///
/// Field names are compared case-insensitively.
pub fn get(&self, key: &str) -> Option<String> {
self.entries()
.find(|e| {
e.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
})
.map(|e| e.value())
}
/// Returns the value of the given key, including any comment lines embedded
/// within multi-line values.
///
/// This is like [`get()`](Self::get) but also includes `#`-prefixed comment lines
/// that appear between continuation lines.
///
/// Field names are compared case-insensitively.
pub fn get_with_comments(&self, key: &str) -> Option<String> {
self.entries()
.find(|e| {
e.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
})
.map(|e| e.value_with_comments())
}
/// Returns the entry for the given key in the paragraph.
///
/// Field names are compared case-insensitively.
pub fn get_entry(&self, key: &str) -> Option<Entry> {
self.entries().find(|e| {
e.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
})
}
/// Returns the value of the given key with a specific indentation pattern applied.
///
/// This returns the field value reformatted as if it were written with the specified
/// indentation pattern. For single-line values, this is the same as `get()`.
/// For multi-line values, the continuation lines are prefixed with indentation
/// calculated from the indent pattern.
///
/// Field names are compared case-insensitively.
///
/// # Arguments
/// * `key` - The field name to retrieve
/// * `indent_pattern` - The indentation pattern to apply
///
/// # Example
/// ```
/// use deb822_lossless::{Deb822, IndentPattern};
/// use std::str::FromStr;
///
/// let input = "Field: First\n Second\n Third\n";
/// let deb = Deb822::from_str(input).unwrap();
/// let para = deb.paragraphs().next().unwrap();
///
/// // Get with fixed 2-space indentation - strips 2 spaces from each line
/// let value = para.get_with_indent("Field", &IndentPattern::Fixed(2)).unwrap();
/// assert_eq!(value, "First\n Second\n Third");
/// ```
pub fn get_with_indent(&self, key: &str, indent_pattern: &IndentPattern) -> Option<String> {
use crate::lex::SyntaxKind::{INDENT, VALUE};
self.entries()
.find(|e| {
e.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
})
.and_then(|e| {
let field_key = e.key()?;
let expected_indent = indent_pattern.to_string(&field_key);
let expected_len = expected_indent.len();
let mut result = String::new();
let mut first = true;
let mut last_indent: Option<String> = None;
for token in e.0.children_with_tokens().filter_map(|it| it.into_token()) {
match token.kind() {
INDENT => {
last_indent = Some(token.text().to_string());
}
VALUE => {
if !first {
result.push('\n');
// Add any indentation beyond the expected amount
if let Some(ref indent_text) = last_indent {
if indent_text.len() > expected_len {
result.push_str(&indent_text[expected_len..]);
}
}
}
result.push_str(token.text());
first = false;
last_indent = None;
}
_ => {}
}
}
Some(result)
})
}
/// Get a multi-line field value with single-space indentation stripped.
///
/// This is a convenience wrapper around `get_with_indent()` that uses
/// `IndentPattern::Fixed(1)`, which is the standard indentation for
/// multi-line fields in Debian control files.
///
/// # Arguments
///
/// * `key` - The field name (case-insensitive)
///
/// # Returns
///
/// The field value with single-space indentation stripped from continuation lines,
/// or `None` if the field doesn't exist.
///
/// # Example
///
/// ```
/// use deb822_lossless::Deb822;
///
/// let text = "Description: Short description\n Additional line\n";
/// let deb822 = Deb822::parse(text).tree();
/// let para = deb822.paragraphs().next().unwrap();
/// let value = para.get_multiline("Description").unwrap();
/// assert_eq!(value, "Short description\nAdditional line");
/// ```
pub fn get_multiline(&self, key: &str) -> Option<String> {
self.get_with_indent(key, &IndentPattern::Fixed(1))
}
/// Set a multi-line field value with single-space indentation.
///
/// This is a convenience wrapper around `try_set_with_forced_indent()` that uses
/// `IndentPattern::Fixed(1)`, which is the standard indentation for
/// multi-line fields in Debian control files.
///
/// # Arguments
///
/// * `key` - The field name
/// * `value` - The field value (will be formatted with single-space indentation)
/// * `field_order` - Optional field ordering specification
///
/// # Returns
///
/// `Ok(())` if successful, or an `Error` if the value is invalid.
///
/// # Example
///
/// ```
/// use deb822_lossless::Paragraph;
///
/// let mut para = Paragraph::new();
/// para.set_multiline("Description", "Short description\nAdditional line", None).unwrap();
/// assert_eq!(para.get_multiline("Description").unwrap(), "Short description\nAdditional line");
/// ```
pub fn set_multiline(
&mut self,
key: &str,
value: &str,
field_order: Option<&[&str]>,
) -> Result<(), Error> {
self.try_set_with_forced_indent(key, value, &IndentPattern::Fixed(1), field_order)
}
/// Returns whether the paragraph contains the given key.
pub fn contains_key(&self, key: &str) -> bool {
self.get(key).is_some()
}
/// Returns an iterator over all entries in the paragraph.
pub fn entries(&self) -> impl Iterator<Item = Entry> + '_ {
self.0.children().filter_map(Entry::cast)
}
/// Returns an iterator over all items in the paragraph.
pub fn items(&self) -> impl Iterator<Item = (String, String)> + '_ {
self.entries()
.filter_map(|e| e.key().map(|k| (k, e.value())))
}
/// Returns an iterator over all values for the given key in the paragraph.
///
/// Field names are compared case-insensitively.
pub fn get_all<'a>(&'a self, key: &'a str) -> impl Iterator<Item = String> + 'a {
self.items().filter_map(move |(k, v)| {
if k.eq_ignore_ascii_case(key) {
Some(v)
} else {
None
}
})
}
/// Returns an iterator over all keys in the paragraph.
pub fn keys(&self) -> impl Iterator<Item = String> + '_ {
self.entries().filter_map(|e| e.key())
}
/// Remove the given field from the paragraph.
///
/// Field names are compared case-insensitively.
pub fn remove(&mut self, key: &str) {
for mut entry in self.entries() {
if entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
{
entry.detach();
}
}
}
/// Insert a new field
pub fn insert(&mut self, key: &str, value: &str) {
let entry = Entry::new(key, value);
let count = self.0.children_with_tokens().count();
self.0.splice_children(count..count, vec![entry.0.into()]);
}
/// Insert a comment line before this paragraph.
///
/// The comment should not include the leading '#' character or newline,
/// these will be added automatically.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// let mut d: Deb822 = vec![
/// vec![("Foo", "Bar")].into_iter().collect(),
/// ]
/// .into_iter()
/// .collect();
/// let mut para = d.paragraphs().next().unwrap();
/// para.insert_comment_before("This is a comment");
/// assert_eq!(d.to_string(), "# This is a comment\nFoo: Bar\n");
/// ```
pub fn insert_comment_before(&mut self, comment: &str) {
use rowan::GreenNodeBuilder;
// Create an EMPTY_LINE node containing the comment tokens
// This matches the structure used elsewhere in the parser
let mut builder = GreenNodeBuilder::new();
builder.start_node(EMPTY_LINE.into());
builder.token(COMMENT.into(), &format!("# {}", comment));
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
let green = builder.finish();
// Convert to syntax node and insert before this paragraph
let comment_node = SyntaxNode::new_root_mut(green);
let index = self.0.index();
let parent = self.0.parent().expect("Paragraph must have a parent");
parent.splice_children(index..index, vec![comment_node.into()]);
}
/// Detect the indentation pattern used in this paragraph.
///
/// This method analyzes existing multi-line fields to determine if they use:
/// 1. A fixed indentation (all fields use the same number of spaces)
/// 2. Field-name-length-based indentation (indent matches field name + ": ")
///
/// If no pattern can be detected, defaults to field name length + 2.
fn detect_indent_pattern(&self) -> IndentPattern {
// Collect indentation data from existing multi-line fields
let indent_data: Vec<(String, usize)> = self
.entries()
.filter_map(|entry| {
let field_key = entry.key()?;
let indent = entry.get_indent()?;
Some((field_key, indent.len()))
})
.collect();
if indent_data.is_empty() {
// No existing multi-line fields, default to field name length
return IndentPattern::FieldNameLength;
}
// Check if all fields use the same fixed indentation
let first_indent_len = indent_data[0].1;
let all_same = indent_data.iter().all(|(_, len)| *len == first_indent_len);
if all_same {
// All fields use the same indentation - use that
return IndentPattern::Fixed(first_indent_len);
}
// Check if fields use field-name-length-based indentation
let all_match_field_length = indent_data
.iter()
.all(|(field_key, indent_len)| *indent_len == field_key.len() + 2);
if all_match_field_length {
// Fields use field-name-length-based indentation
return IndentPattern::FieldNameLength;
}
// Can't detect a clear pattern, default to field name length + 2
IndentPattern::FieldNameLength
}
/// Try to set a field in the paragraph, inserting at the appropriate location if new.
///
/// # Errors
/// Returns an error if the value contains empty continuation lines (lines with only whitespace)
pub fn try_set(&mut self, key: &str, value: &str) -> Result<(), Error> {
self.try_set_with_indent_pattern(key, value, None, None)
}
/// Set a field in the paragraph, inserting at the appropriate location if new
///
/// # Panics
/// Panics if the value contains empty continuation lines (lines with only whitespace)
pub fn set(&mut self, key: &str, value: &str) {
self.try_set(key, value)
.expect("Invalid value: empty continuation line")
}
/// Set a field using a specific field ordering
pub fn set_with_field_order(&mut self, key: &str, value: &str, field_order: &[&str]) {
self.try_set_with_indent_pattern(key, value, None, Some(field_order))
.expect("Invalid value: empty continuation line")
}
/// Try to set a field with optional default indentation pattern and field ordering.
///
/// This method allows setting a field while optionally specifying a default indentation pattern
/// to use when the field doesn't already have multi-line indentation to preserve.
/// If the field already exists and is multi-line, its existing indentation is preserved.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value
/// * `default_indent_pattern` - Optional default indentation pattern to use for new fields or
/// fields without existing multi-line indentation. If None, will preserve existing field's
/// indentation or auto-detect from other fields
/// * `field_order` - Optional field ordering for positioning the field. If None, inserts at end
///
/// # Errors
/// Returns an error if the value contains empty continuation lines (lines with only whitespace)
pub fn try_set_with_indent_pattern(
&mut self,
key: &str,
value: &str,
default_indent_pattern: Option<&IndentPattern>,
field_order: Option<&[&str]>,
) -> Result<(), Error> {
// Check if the field already exists and extract its formatting (case-insensitive)
let existing_entry = self.entries().find(|entry| {
entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
});
// Determine indentation to use
let indent = existing_entry
.as_ref()
.and_then(|entry| entry.get_indent())
.unwrap_or_else(|| {
// No existing indentation, use default pattern or auto-detect
if let Some(pattern) = default_indent_pattern {
pattern.to_string(key)
} else {
self.detect_indent_pattern().to_string(key)
}
});
let post_colon_ws = existing_entry
.as_ref()
.and_then(|entry| entry.get_post_colon_whitespace())
.unwrap_or_else(|| " ".to_string());
// When replacing an existing field, preserve the original case of the field name
let actual_key = existing_entry
.as_ref()
.and_then(|e| e.key())
.unwrap_or_else(|| key.to_string());
let new_entry = Entry::try_with_formatting(&actual_key, value, &post_colon_ws, &indent)?;
// Check if the field already exists and replace it (case-insensitive)
for entry in self.entries() {
if entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
{
self.0.splice_children(
entry.0.index()..entry.0.index() + 1,
vec![new_entry.0.into()],
);
return Ok(());
}
}
// Insert new field
if let Some(order) = field_order {
let insertion_index = self.find_insertion_index(key, order);
self.0
.splice_children(insertion_index..insertion_index, vec![new_entry.0.into()]);
} else {
// Insert at the end if no field order specified
let insertion_index = self.0.children_with_tokens().count();
self.0
.splice_children(insertion_index..insertion_index, vec![new_entry.0.into()]);
}
Ok(())
}
/// Set a field with optional default indentation pattern and field ordering.
///
/// This method allows setting a field while optionally specifying a default indentation pattern
/// to use when the field doesn't already have multi-line indentation to preserve.
/// If the field already exists and is multi-line, its existing indentation is preserved.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value
/// * `default_indent_pattern` - Optional default indentation pattern to use for new fields or
/// fields without existing multi-line indentation. If None, will preserve existing field's
/// indentation or auto-detect from other fields
/// * `field_order` - Optional field ordering for positioning the field. If None, inserts at end
///
/// # Panics
/// Panics if the value contains empty continuation lines (lines with only whitespace)
pub fn set_with_indent_pattern(
&mut self,
key: &str,
value: &str,
default_indent_pattern: Option<&IndentPattern>,
field_order: Option<&[&str]>,
) {
self.try_set_with_indent_pattern(key, value, default_indent_pattern, field_order)
.expect("Invalid value: empty continuation line")
}
/// Try to set a field, forcing a specific indentation pattern regardless of existing indentation.
///
/// Unlike `try_set_with_indent_pattern`, this method does NOT preserve existing field indentation.
/// It always applies the specified indentation pattern to the field.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value
/// * `indent_pattern` - The indentation pattern to use for this field
/// * `field_order` - Optional field ordering for positioning the field. If None, inserts at end
///
/// # Errors
/// Returns an error if the value contains empty continuation lines (lines with only whitespace)
pub fn try_set_with_forced_indent(
&mut self,
key: &str,
value: &str,
indent_pattern: &IndentPattern,
field_order: Option<&[&str]>,
) -> Result<(), Error> {
// Check if the field already exists (case-insensitive)
let existing_entry = self.entries().find(|entry| {
entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
});
// Get post-colon whitespace from existing field, or default to single space
let post_colon_ws = existing_entry
.as_ref()
.and_then(|entry| entry.get_post_colon_whitespace())
.unwrap_or_else(|| " ".to_string());
// When replacing an existing field, preserve the original case of the field name
let actual_key = existing_entry
.as_ref()
.and_then(|e| e.key())
.unwrap_or_else(|| key.to_string());
// Force the indentation pattern
let indent = indent_pattern.to_string(&actual_key);
let new_entry = Entry::try_with_formatting(&actual_key, value, &post_colon_ws, &indent)?;
// Check if the field already exists and replace it (case-insensitive)
for entry in self.entries() {
if entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
{
self.0.splice_children(
entry.0.index()..entry.0.index() + 1,
vec![new_entry.0.into()],
);
return Ok(());
}
}
// Insert new field
if let Some(order) = field_order {
let insertion_index = self.find_insertion_index(key, order);
self.0
.splice_children(insertion_index..insertion_index, vec![new_entry.0.into()]);
} else {
// Insert at the end if no field order specified
let insertion_index = self.0.children_with_tokens().count();
self.0
.splice_children(insertion_index..insertion_index, vec![new_entry.0.into()]);
}
Ok(())
}
/// Set a field, forcing a specific indentation pattern regardless of existing indentation.
///
/// Unlike `set_with_indent_pattern`, this method does NOT preserve existing field indentation.
/// It always applies the specified indentation pattern to the field.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value
/// * `indent_pattern` - The indentation pattern to use for this field
/// * `field_order` - Optional field ordering for positioning the field. If None, inserts at end
///
/// # Panics
/// Panics if the value contains empty continuation lines (lines with only whitespace)
pub fn set_with_forced_indent(
&mut self,
key: &str,
value: &str,
indent_pattern: &IndentPattern,
field_order: Option<&[&str]>,
) {
self.try_set_with_forced_indent(key, value, indent_pattern, field_order)
.expect("Invalid value: empty continuation line")
}
/// Change the indentation of an existing field without modifying its value.
///
/// This method finds an existing field and reapplies it with a new indentation pattern,
/// preserving the field's current value.
///
/// # Arguments
/// * `key` - The field name to update
/// * `indent_pattern` - The new indentation pattern to apply
///
/// # Returns
/// Returns `Ok(true)` if the field was found and updated, `Ok(false)` if the field doesn't exist,
/// or `Err` if there was an error (e.g., invalid value with empty continuation lines)
///
/// # Errors
/// Returns an error if the field value contains empty continuation lines (lines with only whitespace)
pub fn change_field_indent(
&mut self,
key: &str,
indent_pattern: &IndentPattern,
) -> Result<bool, Error> {
// Check if the field exists (case-insensitive)
let existing_entry = self.entries().find(|entry| {
entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(key))
});
if let Some(entry) = existing_entry {
let value = entry.value();
let actual_key = entry.key().unwrap_or_else(|| key.to_string());
// Get post-colon whitespace from existing field
let post_colon_ws = entry
.get_post_colon_whitespace()
.unwrap_or_else(|| " ".to_string());
// Apply the new indentation pattern
let indent = indent_pattern.to_string(&actual_key);
let new_entry =
Entry::try_with_formatting(&actual_key, &value, &post_colon_ws, &indent)?;
// Replace the existing entry
self.0.splice_children(
entry.0.index()..entry.0.index() + 1,
vec![new_entry.0.into()],
);
Ok(true)
} else {
Ok(false)
}
}
/// Find the appropriate insertion index for a new field based on field ordering
fn find_insertion_index(&self, key: &str, field_order: &[&str]) -> usize {
// Find position of the new field in the canonical order (case-insensitive)
let new_field_position = field_order
.iter()
.position(|&field| field.eq_ignore_ascii_case(key));
let mut insertion_index = self.0.children_with_tokens().count();
// Find the right position based on canonical field order
for (i, child) in self.0.children_with_tokens().enumerate() {
if let Some(node) = child.as_node() {
if let Some(entry) = Entry::cast(node.clone()) {
if let Some(existing_key) = entry.key() {
let existing_position = field_order
.iter()
.position(|&field| field.eq_ignore_ascii_case(&existing_key));
match (new_field_position, existing_position) {
// Both fields are in the canonical order
(Some(new_pos), Some(existing_pos)) => {
if new_pos < existing_pos {
insertion_index = i;
break;
}
}
// New field is in canonical order, existing is not
(Some(_), None) => {
// Continue looking - unknown fields go after known ones
}
// New field is not in canonical order, existing is
(None, Some(_)) => {
// Continue until we find all known fields
}
// Neither field is in canonical order, maintain alphabetical
(None, None) => {
if key < existing_key.as_str() {
insertion_index = i;
break;
}
}
}
}
}
}
}
// If we have a position in canonical order but haven't found where to insert yet,
// we need to insert after all known fields that come before it
if new_field_position.is_some() && insertion_index == self.0.children_with_tokens().count()
{
// Look for the position after the last known field that comes before our field
let children: Vec<_> = self.0.children_with_tokens().enumerate().collect();
for (i, child) in children.into_iter().rev() {
if let Some(node) = child.as_node() {
if let Some(entry) = Entry::cast(node.clone()) {
if let Some(existing_key) = entry.key() {
if field_order
.iter()
.any(|&f| f.eq_ignore_ascii_case(&existing_key))
{
// Found a known field, insert after it
insertion_index = i + 1;
break;
}
}
}
}
}
}
insertion_index
}
/// Rename the given field in the paragraph.
///
/// Field names are compared case-insensitively. The entry's existing
/// formatting (post-colon whitespace, continuation-line indentation) is
/// preserved — only the key token is replaced.
pub fn rename(&mut self, old_key: &str, new_key: &str) -> bool {
for entry in self.entries() {
if entry
.key()
.as_deref()
.is_some_and(|k| k.eq_ignore_ascii_case(old_key))
{
let key_index = entry
.0
.children_with_tokens()
.position(|it| it.as_token().is_some_and(|t| t.kind() == KEY));
if let Some(key_index) = key_index {
let new_token =
rowan::NodeOrToken::Token(rowan::GreenToken::new(KEY.into(), new_key));
let new_green = entry
.0
.green()
.splice_children(key_index..key_index + 1, vec![new_token]);
let parent = entry.0.parent().expect("Entry must have a parent");
parent.splice_children(
entry.0.index()..entry.0.index() + 1,
vec![SyntaxNode::new_root_mut(new_green).into()],
);
return true;
}
}
}
false
}
}
impl Default for Paragraph {
fn default() -> Self {
Self::new()
}
}
impl std::str::FromStr for Paragraph {
type Err = ParseError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let deb822 = Deb822::from_str(text)?;
let mut paragraphs = deb822.paragraphs();
paragraphs
.next()
.ok_or_else(|| ParseError(vec!["no paragraphs".to_string()]))
}
}
#[cfg(feature = "python-debian")]
impl<'py> pyo3::IntoPyObject<'py> for Paragraph {
type Target = pyo3::PyAny;
type Output = pyo3::Bound<'py, Self::Target>;
type Error = pyo3::PyErr;
fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
use pyo3::prelude::*;
let d = pyo3::types::PyDict::new(py);
for (k, v) in self.items() {
d.set_item(k, v)?;
}
let m = py.import("debian.deb822")?;
let cls = m.getattr("Deb822")?;
cls.call1((d,))
}
}
#[cfg(feature = "python-debian")]
impl<'py> pyo3::IntoPyObject<'py> for &Paragraph {
type Target = pyo3::PyAny;
type Output = pyo3::Bound<'py, Self::Target>;
type Error = pyo3::PyErr;
fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
use pyo3::prelude::*;
let d = pyo3::types::PyDict::new(py);
for (k, v) in self.items() {
d.set_item(k, v)?;
}
let m = py.import("debian.deb822")?;
let cls = m.getattr("Deb822")?;
cls.call1((d,))
}
}
#[cfg(feature = "python-debian")]
impl<'py> pyo3::FromPyObject<'_, 'py> for Paragraph {
type Error = pyo3::PyErr;
fn extract(obj: pyo3::Borrowed<'_, 'py, pyo3::PyAny>) -> Result<Self, Self::Error> {
use pyo3::types::PyAnyMethods;
let d = obj.call_method0("__str__")?.extract::<String>()?;
Paragraph::from_str(&d)
.map_err(|e| pyo3::exceptions::PyValueError::new_err((e.to_string(),)))
}
}
impl Entry {
/// Capture an independent snapshot of this entry.
///
/// See [`Deb822::snapshot`] for details.
pub fn snapshot(&self) -> Self {
Entry(SyntaxNode::new_root_mut(self.0.green().into_owned()))
}
/// O(1) check: returns true iff `self` and `snapshot` reference the same
/// syntax-tree state. See [`Deb822::tree_eq`].
pub fn tree_eq(&self, other: &Self) -> bool {
green_eq(&self.0, &other.0)
}
/// Returns the text range of this entry in the source text.
pub fn text_range(&self) -> rowan::TextRange {
self.0.text_range()
}
/// Returns the text range of the key (field name) in this entry.
pub fn key_range(&self) -> Option<rowan::TextRange> {
self.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == KEY)
.map(|it| it.text_range())
}
/// Returns the text range of the colon separator in this entry.
pub fn colon_range(&self) -> Option<rowan::TextRange> {
self.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == COLON)
.map(|it| it.text_range())
}
/// Returns the text range of the value portion (excluding the key and colon) in this entry.
/// This includes all VALUE tokens and any continuation lines.
pub fn value_range(&self) -> Option<rowan::TextRange> {
let value_tokens: Vec<_> = self
.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.filter(|it| it.kind() == VALUE)
.collect();
if value_tokens.is_empty() {
return None;
}
let first = value_tokens.first().unwrap();
let last = value_tokens.last().unwrap();
Some(rowan::TextRange::new(
first.text_range().start(),
last.text_range().end(),
))
}
/// Returns the text ranges of all individual value lines in this entry.
/// Multi-line values will return multiple ranges.
pub fn value_line_ranges(&self) -> Vec<rowan::TextRange> {
self.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.filter(|it| it.kind() == VALUE)
.map(|it| it.text_range())
.collect()
}
/// Create a new entry with the given key and value.
pub fn new(key: &str, value: &str) -> Entry {
Self::with_indentation(key, value, " ")
}
/// Create a new entry with the given key, value, and custom indentation for continuation lines.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value (may contain '\n' for multi-line values)
/// * `indent` - The indentation string to use for continuation lines
pub fn with_indentation(key: &str, value: &str, indent: &str) -> Entry {
Entry::with_formatting(key, value, " ", indent)
}
/// Try to create a new entry with specific formatting, validating the value.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value (may contain '\n' for multi-line values)
/// * `post_colon_ws` - The whitespace after the colon (e.g., " " or "\n ")
/// * `indent` - The indentation string to use for continuation lines
///
/// # Errors
/// Returns an error if the value contains empty continuation lines (lines with only whitespace)
pub fn try_with_formatting(
key: &str,
value: &str,
post_colon_ws: &str,
indent: &str,
) -> Result<Entry, Error> {
let mut builder = GreenNodeBuilder::new();
builder.start_node(ENTRY.into());
builder.token(KEY.into(), key);
builder.token(COLON.into(), ":");
// Add the post-colon whitespace token by token
let mut i = 0;
while i < post_colon_ws.len() {
if post_colon_ws[i..].starts_with('\n') {
builder.token(NEWLINE.into(), "\n");
i += 1;
} else {
// Collect consecutive non-newline chars as WHITESPACE
let start = i;
while i < post_colon_ws.len() && !post_colon_ws[i..].starts_with('\n') {
i += post_colon_ws[i..].chars().next().unwrap().len_utf8();
}
builder.token(WHITESPACE.into(), &post_colon_ws[start..i]);
}
}
for (line_idx, line) in value.split('\n').enumerate() {
if line_idx > 0 {
// Validate that continuation lines are not empty or whitespace-only
// According to Debian Policy, continuation lines must have content
if line.trim().is_empty() {
return Err(Error::InvalidValue(format!(
"empty continuation line (line with only whitespace) at line {}",
line_idx + 1
)));
}
builder.token(INDENT.into(), indent);
}
builder.token(VALUE.into(), line);
builder.token(NEWLINE.into(), "\n");
}
builder.finish_node();
Ok(Entry(SyntaxNode::new_root_mut(builder.finish())))
}
/// Create a new entry with specific formatting for post-colon whitespace and indentation.
///
/// # Arguments
/// * `key` - The field name
/// * `value` - The field value (may contain '\n' for multi-line values)
/// * `post_colon_ws` - The whitespace after the colon (e.g., " " or "\n ")
/// * `indent` - The indentation string to use for continuation lines
///
/// # Panics
/// Panics if the value contains empty continuation lines (lines with only whitespace)
pub fn with_formatting(key: &str, value: &str, post_colon_ws: &str, indent: &str) -> Entry {
Self::try_with_formatting(key, value, post_colon_ws, indent)
.expect("Invalid value: empty continuation line")
}
#[must_use]
/// Reformat this entry
///
/// # Arguments
/// * `indentation` - The indentation to use
/// * `immediate_empty_line` - Whether multi-line values should always start with an empty line
/// * `max_line_length_one_liner` - If set, then this is the max length of the value if it is
/// crammed into a "one-liner" value
/// * `format_value` - If set, then this function will format the value according to the given
/// function
///
/// # Returns
/// The reformatted entry
pub fn wrap_and_sort(
&self,
mut indentation: Indentation,
immediate_empty_line: bool,
max_line_length_one_liner: Option<usize>,
format_value: Option<&dyn Fn(&str, &str) -> String>,
) -> Entry {
let mut builder = GreenNodeBuilder::new();
let mut content = vec![];
builder.start_node(ENTRY.into());
for c in self.0.children_with_tokens() {
let text = c.as_token().map(|t| t.text());
match c.kind() {
KEY => {
builder.token(KEY.into(), text.unwrap());
if indentation == Indentation::FieldNameLength {
indentation = Indentation::Spaces(text.unwrap().len() as u32);
}
}
COLON => {
builder.token(COLON.into(), ":");
}
INDENT => {
// Discard original whitespace
}
ERROR | COMMENT | VALUE | WHITESPACE | NEWLINE => {
content.push(c);
}
EMPTY_LINE | ENTRY | ROOT | PARAGRAPH => unreachable!(),
}
}
let indentation = if let crate::Indentation::Spaces(i) = indentation {
i
} else {
1
};
assert!(indentation > 0);
// Strip trailing whitespace and newlines
while let Some(c) = content.last() {
if c.kind() == NEWLINE || c.kind() == WHITESPACE {
content.pop();
} else {
break;
}
}
// Reformat iff there is a format function and the value
// has no errors or comments
let tokens = if let Some(ref format_value) = format_value {
if !content
.iter()
.any(|c| c.kind() == ERROR || c.kind() == COMMENT)
{
let concat = content
.iter()
.filter_map(|c| c.as_token().map(|t| t.text()))
.collect::<String>();
let formatted = format_value(self.key().as_ref().unwrap(), &concat);
crate::lex::lex_inline(&formatted)
.map(|(k, t)| (k, t.to_string()))
.collect::<Vec<_>>()
} else {
content
.into_iter()
.map(|n| n.into_token().unwrap())
.map(|i| (i.kind(), i.text().to_string()))
.collect::<Vec<_>>()
}
} else {
content
.into_iter()
.map(|n| n.into_token().unwrap())
.map(|i| (i.kind(), i.text().to_string()))
.collect::<Vec<_>>()
};
rebuild_value(
&mut builder,
tokens,
self.key().map_or(0, |k| k.len()),
indentation,
immediate_empty_line,
max_line_length_one_liner,
);
builder.finish_node();
Self(SyntaxNode::new_root_mut(builder.finish()))
}
/// Returns the key of the entry.
pub fn key(&self) -> Option<String> {
self.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == KEY)
.map(|it| it.text().to_string())
}
/// Returns the value of the entry.
pub fn value(&self) -> String {
let mut parts = self
.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.filter(|it| it.kind() == VALUE)
.map(|it| it.text().to_string());
match parts.next() {
None => String::new(),
Some(first) => {
let mut result = first;
for part in parts {
result.push('\n');
result.push_str(&part);
}
result
}
}
}
/// Returns the value of this entry, including any comment lines embedded
/// within the multi-line value.
///
/// This is like [`value()`](Self::value) but also includes `#`-prefixed
/// comment lines that appear between continuation lines. This is useful
/// for parsers (e.g. Relations) that need to preserve commented-out entries.
pub fn value_with_comments(&self) -> String {
let mut parts = self
.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.filter(|it| it.kind() == VALUE || it.kind() == COMMENT)
.map(|it| it.text().to_string());
match parts.next() {
None => String::new(),
Some(first) => {
let mut result = first;
for part in parts {
result.push('\n');
result.push_str(&part);
}
result
}
}
}
/// Returns the indentation string used for continuation lines in this entry.
/// Returns None if the entry has no continuation lines.
fn get_indent(&self) -> Option<String> {
self.0
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == INDENT)
.map(|it| it.text().to_string())
}
/// Returns the whitespace immediately after the colon in this entry.
/// This includes WHITESPACE, NEWLINE, and INDENT tokens up to the first VALUE token.
/// Returns None if there is no whitespace (which would be malformed).
fn get_post_colon_whitespace(&self) -> Option<String> {
let mut found_colon = false;
let mut whitespace = String::new();
for token in self
.0
.children_with_tokens()
.filter_map(|it| it.into_token())
{
if token.kind() == COLON {
found_colon = true;
continue;
}
if found_colon {
if token.kind() == WHITESPACE || token.kind() == NEWLINE || token.kind() == INDENT {
whitespace.push_str(token.text());
} else {
// We've reached a non-whitespace token, stop collecting
break;
}
}
}
if whitespace.is_empty() {
None
} else {
Some(whitespace)
}
}
/// Normalize the spacing around the field separator (colon) in place.
///
/// This ensures that there is exactly one space after the colon and before the value.
/// This is a lossless operation that preserves the field name and value content,
/// but normalizes the whitespace formatting.
///
/// # Examples
///
/// ```
/// use deb822_lossless::Deb822;
/// use std::str::FromStr;
///
/// // Parse an entry with extra spacing after the colon
/// let input = "Field: value\n";
/// let mut deb822 = Deb822::from_str(input).unwrap();
/// let mut para = deb822.paragraphs().next().unwrap();
///
/// para.normalize_field_spacing();
/// assert_eq!(para.get("Field").as_deref(), Some("value"));
/// ```
pub fn normalize_field_spacing(&mut self) -> bool {
use rowan::GreenNodeBuilder;
// Store the original text for comparison
let original_text = self.0.text().to_string();
// Build normalized entry
let mut builder = GreenNodeBuilder::new();
builder.start_node(ENTRY.into());
let mut seen_colon = false;
let mut skip_whitespace = false;
for child in self.0.children_with_tokens() {
match child.kind() {
KEY => {
builder.token(KEY.into(), child.as_token().unwrap().text());
}
COLON => {
builder.token(COLON.into(), ":");
seen_colon = true;
skip_whitespace = true;
}
WHITESPACE if skip_whitespace => {
// Skip existing whitespace after colon
continue;
}
VALUE if skip_whitespace => {
// Add exactly one space before the first value token
builder.token(WHITESPACE.into(), " ");
builder.token(VALUE.into(), child.as_token().unwrap().text());
skip_whitespace = false;
}
NEWLINE if skip_whitespace && seen_colon => {
// Empty value case (e.g., "Field:\n" or "Field: \n")
// Normalize to no trailing space - just output newline
builder.token(NEWLINE.into(), "\n");
skip_whitespace = false;
}
_ => {
// Copy all other tokens as-is
if let Some(token) = child.as_token() {
builder.token(token.kind().into(), token.text());
}
}
}
}
builder.finish_node();
let normalized_green = builder.finish();
let normalized = SyntaxNode::new_root_mut(normalized_green);
// Check if normalization made any changes
let changed = original_text != normalized.text().to_string();
if changed {
// Replace this entry in place
if let Some(parent) = self.0.parent() {
let index = self.0.index();
parent.splice_children(index..index + 1, vec![normalized.into()]);
}
}
changed
}
/// Detach this entry from the paragraph.
pub fn detach(&mut self) {
self.0.detach();
}
}
impl FromStr for Deb822 {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Deb822::parse(s).to_result()
}
}
#[test]
fn test_parse_simple() {
const CONTROLV1: &str = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
Section: net
# This is a comment
Package: foo
Architecture: all
Depends:
bar,
blah
Description: This is a description
And it is
.
multiple
lines
"#;
let parsed = parse(CONTROLV1);
let node = parsed.syntax();
assert_eq!(
format!("{:#?}", node),
r###"ROOT@0..203
PARAGRAPH@0..63
ENTRY@0..12
KEY@0..6 "Source"
COLON@6..7 ":"
WHITESPACE@7..8 " "
VALUE@8..11 "foo"
NEWLINE@11..12 "\n"
ENTRY@12..50
KEY@12..22 "Maintainer"
COLON@22..23 ":"
WHITESPACE@23..24 " "
VALUE@24..49 "Foo Bar <foo@example. ..."
NEWLINE@49..50 "\n"
ENTRY@50..63
KEY@50..57 "Section"
COLON@57..58 ":"
WHITESPACE@58..59 " "
VALUE@59..62 "net"
NEWLINE@62..63 "\n"
EMPTY_LINE@63..64
NEWLINE@63..64 "\n"
EMPTY_LINE@64..84
COMMENT@64..83 "# This is a comment"
NEWLINE@83..84 "\n"
EMPTY_LINE@84..85
NEWLINE@84..85 "\n"
PARAGRAPH@85..203
ENTRY@85..98
KEY@85..92 "Package"
COLON@92..93 ":"
WHITESPACE@93..94 " "
VALUE@94..97 "foo"
NEWLINE@97..98 "\n"
ENTRY@98..116
KEY@98..110 "Architecture"
COLON@110..111 ":"
WHITESPACE@111..112 " "
VALUE@112..115 "all"
NEWLINE@115..116 "\n"
ENTRY@116..137
KEY@116..123 "Depends"
COLON@123..124 ":"
NEWLINE@124..125 "\n"
INDENT@125..126 " "
VALUE@126..130 "bar,"
NEWLINE@130..131 "\n"
INDENT@131..132 " "
VALUE@132..136 "blah"
NEWLINE@136..137 "\n"
ENTRY@137..203
KEY@137..148 "Description"
COLON@148..149 ":"
WHITESPACE@149..150 " "
VALUE@150..171 "This is a description"
NEWLINE@171..172 "\n"
INDENT@172..173 " "
VALUE@173..182 "And it is"
NEWLINE@182..183 "\n"
INDENT@183..184 " "
VALUE@184..185 "."
NEWLINE@185..186 "\n"
INDENT@186..187 " "
VALUE@187..195 "multiple"
NEWLINE@195..196 "\n"
INDENT@196..197 " "
VALUE@197..202 "lines"
NEWLINE@202..203 "\n"
"###
);
assert_eq!(parsed.errors, Vec::<String>::new());
let root = parsed.root_mut();
assert_eq!(root.paragraphs().count(), 2);
let source = root.paragraphs().next().unwrap();
assert_eq!(
source.keys().collect::<Vec<_>>(),
vec!["Source", "Maintainer", "Section"]
);
assert_eq!(source.get("Source").as_deref(), Some("foo"));
assert_eq!(
source.get("Maintainer").as_deref(),
Some("Foo Bar <foo@example.com>")
);
assert_eq!(source.get("Section").as_deref(), Some("net"));
assert_eq!(
source.items().collect::<Vec<_>>(),
vec![
("Source".into(), "foo".into()),
("Maintainer".into(), "Foo Bar <foo@example.com>".into()),
("Section".into(), "net".into()),
]
);
let binary = root.paragraphs().nth(1).unwrap();
assert_eq!(
binary.keys().collect::<Vec<_>>(),
vec!["Package", "Architecture", "Depends", "Description"]
);
assert_eq!(binary.get("Package").as_deref(), Some("foo"));
assert_eq!(binary.get("Architecture").as_deref(), Some("all"));
assert_eq!(binary.get("Depends").as_deref(), Some("bar,\nblah"));
assert_eq!(
binary.get("Description").as_deref(),
Some("This is a description\nAnd it is\n.\nmultiple\nlines")
);
assert_eq!(node.text(), CONTROLV1);
}
#[test]
fn test_with_trailing_whitespace() {
const CONTROLV1: &str = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
"#;
let parsed = parse(CONTROLV1);
let node = parsed.syntax();
assert_eq!(
format!("{:#?}", node),
r###"ROOT@0..52
PARAGRAPH@0..50
ENTRY@0..12
KEY@0..6 "Source"
COLON@6..7 ":"
WHITESPACE@7..8 " "
VALUE@8..11 "foo"
NEWLINE@11..12 "\n"
ENTRY@12..50
KEY@12..22 "Maintainer"
COLON@22..23 ":"
WHITESPACE@23..24 " "
VALUE@24..49 "Foo Bar <foo@example. ..."
NEWLINE@49..50 "\n"
EMPTY_LINE@50..51
NEWLINE@50..51 "\n"
EMPTY_LINE@51..52
NEWLINE@51..52 "\n"
"###
);
assert_eq!(parsed.errors, Vec::<String>::new());
let root = parsed.root_mut();
assert_eq!(root.paragraphs().count(), 1);
let source = root.paragraphs().next().unwrap();
assert_eq!(
source.items().collect::<Vec<_>>(),
vec![
("Source".into(), "foo".into()),
("Maintainer".into(), "Foo Bar <foo@example.com>".into()),
]
);
}
fn rebuild_value(
builder: &mut GreenNodeBuilder,
mut tokens: Vec<(SyntaxKind, String)>,
key_len: usize,
indentation: u32,
immediate_empty_line: bool,
max_line_length_one_liner: Option<usize>,
) {
let first_line_len = tokens
.iter()
.take_while(|(k, _t)| *k != NEWLINE)
.map(|(_k, t)| t.len())
.sum::<usize>() + key_len + 2 /* ": " */;
let has_newline = tokens.iter().any(|(k, _t)| *k == NEWLINE);
let mut last_was_newline = false;
if max_line_length_one_liner
.map(|mll| first_line_len <= mll)
.unwrap_or(false)
&& !has_newline
{
// Just copy tokens if the value fits into one line
for (k, t) in tokens {
builder.token(k.into(), &t);
}
} else {
// Insert a leading newline if the value is multi-line and immediate_empty_line is set
if immediate_empty_line && has_newline {
builder.token(NEWLINE.into(), "\n");
last_was_newline = true;
} else {
builder.token(WHITESPACE.into(), " ");
}
// Strip leading whitespace and newlines
let mut start_idx = 0;
while start_idx < tokens.len() {
if tokens[start_idx].0 == NEWLINE || tokens[start_idx].0 == WHITESPACE {
start_idx += 1;
} else {
break;
}
}
tokens.drain(..start_idx);
// Pre-allocate indentation string to avoid repeated allocations
let indent_str = " ".repeat(indentation as usize);
for (k, t) in tokens {
if last_was_newline {
builder.token(INDENT.into(), &indent_str);
}
builder.token(k.into(), &t);
last_was_newline = k == NEWLINE;
}
}
if !last_was_newline {
builder.token(NEWLINE.into(), "\n");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <jelmer@jelmer.uk>
Section: net
Package: foo
Architecture: all
Depends: libc6
Description: This is a description
With details
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let p = ps.next().unwrap();
assert_eq!(p.get("Source").as_deref(), Some("foo"));
assert_eq!(
p.get("Maintainer").as_deref(),
Some("Foo Bar <jelmer@jelmer.uk>")
);
assert_eq!(p.get("Section").as_deref(), Some("net"));
let b = ps.next().unwrap();
assert_eq!(b.get("Package").as_deref(), Some("foo"));
}
#[test]
fn test_after_multi_line() {
let d: super::Deb822 = r#"Source: golang-github-blah-blah
Section: devel
Priority: optional
Standards-Version: 4.2.0
Maintainer: Some Maintainer <example@example.com>
Build-Depends: debhelper (>= 11~),
dh-golang,
golang-any
Homepage: https://github.com/j-keck/arping
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let p = ps.next().unwrap();
assert_eq!(p.get("Source").as_deref(), Some("golang-github-blah-blah"));
assert_eq!(p.get("Section").as_deref(), Some("devel"));
assert_eq!(p.get("Priority").as_deref(), Some("optional"));
assert_eq!(p.get("Standards-Version").as_deref(), Some("4.2.0"));
assert_eq!(
p.get("Maintainer").as_deref(),
Some("Some Maintainer <example@example.com>")
);
assert_eq!(
p.get("Build-Depends").as_deref(),
Some("debhelper (>= 11~),\ndh-golang,\ngolang-any")
);
assert_eq!(
p.get("Homepage").as_deref(),
Some("https://github.com/j-keck/arping")
);
}
#[test]
fn test_remove_field() {
let d: super::Deb822 = r#"Source: foo
# Comment
Maintainer: Foo Bar <jelmer@jelmer.uk>
Section: net
Package: foo
Architecture: all
Depends: libc6
Description: This is a description
With details
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let mut p = ps.next().unwrap();
p.set("Foo", "Bar");
p.remove("Section");
p.remove("Nonexistent");
assert_eq!(p.get("Foo").as_deref(), Some("Bar"));
assert_eq!(
p.to_string(),
r#"Source: foo
# Comment
Maintainer: Foo Bar <jelmer@jelmer.uk>
Foo: Bar
"#
);
}
#[test]
fn test_rename_field() {
let d: super::Deb822 = r#"Source: foo
Vcs-Browser: https://salsa.debian.org/debian/foo
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let mut p = ps.next().unwrap();
assert!(p.rename("Vcs-Browser", "Homepage"));
assert_eq!(
p.to_string(),
r#"Source: foo
Homepage: https://salsa.debian.org/debian/foo
"#
);
assert_eq!(
p.get("Homepage").as_deref(),
Some("https://salsa.debian.org/debian/foo")
);
assert_eq!(p.get("Vcs-Browser").as_deref(), None);
// Nonexistent field
assert!(!p.rename("Nonexistent", "Homepage"));
}
#[test]
fn test_set_field() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <joe@example.com>
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let mut p = ps.next().unwrap();
p.set("Maintainer", "Somebody Else <jane@example.com>");
assert_eq!(
p.get("Maintainer").as_deref(),
Some("Somebody Else <jane@example.com>")
);
assert_eq!(
p.to_string(),
r#"Source: foo
Maintainer: Somebody Else <jane@example.com>
"#
);
}
#[test]
fn test_set_new_field() {
let d: super::Deb822 = r#"Source: foo
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let mut p = ps.next().unwrap();
p.set("Maintainer", "Somebody <joe@example.com>");
assert_eq!(
p.get("Maintainer").as_deref(),
Some("Somebody <joe@example.com>")
);
assert_eq!(
p.to_string(),
r#"Source: foo
Maintainer: Somebody <joe@example.com>
"#
);
}
#[test]
fn test_add_paragraph() {
let mut d = super::Deb822::new();
let mut p = d.add_paragraph();
p.set("Foo", "Bar");
assert_eq!(p.get("Foo").as_deref(), Some("Bar"));
assert_eq!(
p.to_string(),
r#"Foo: Bar
"#
);
assert_eq!(
d.to_string(),
r#"Foo: Bar
"#
);
let mut p = d.add_paragraph();
p.set("Foo", "Blah");
assert_eq!(p.get("Foo").as_deref(), Some("Blah"));
assert_eq!(
d.to_string(),
r#"Foo: Bar
Foo: Blah
"#
);
}
#[test]
fn test_crud_paragraph() {
let mut d = super::Deb822::new();
let mut p = d.insert_paragraph(0);
p.set("Foo", "Bar");
assert_eq!(p.get("Foo").as_deref(), Some("Bar"));
assert_eq!(
d.to_string(),
r#"Foo: Bar
"#
);
// test prepend
let mut p = d.insert_paragraph(0);
p.set("Foo", "Blah");
assert_eq!(p.get("Foo").as_deref(), Some("Blah"));
assert_eq!(
d.to_string(),
r#"Foo: Blah
Foo: Bar
"#
);
// test delete
d.remove_paragraph(1);
assert_eq!(d.to_string(), "Foo: Blah\n\n");
// test update again
p.set("Foo", "Baz");
assert_eq!(d.to_string(), "Foo: Baz\n\n");
// test delete again
d.remove_paragraph(0);
assert_eq!(d.to_string(), "");
}
#[test]
fn test_swap_paragraphs() {
// Test basic swap
let mut d: super::Deb822 = vec![
vec![("Foo", "Bar")].into_iter().collect(),
vec![("A", "B")].into_iter().collect(),
vec![("X", "Y")].into_iter().collect(),
]
.into_iter()
.collect();
d.swap_paragraphs(0, 2);
assert_eq!(d.to_string(), "X: Y\n\nA: B\n\nFoo: Bar\n");
// Swap back
d.swap_paragraphs(0, 2);
assert_eq!(d.to_string(), "Foo: Bar\n\nA: B\n\nX: Y\n");
// Swap adjacent paragraphs
d.swap_paragraphs(0, 1);
assert_eq!(d.to_string(), "A: B\n\nFoo: Bar\n\nX: Y\n");
// Swap with same index should be no-op
let before = d.to_string();
d.swap_paragraphs(1, 1);
assert_eq!(d.to_string(), before);
}
#[test]
fn test_swap_paragraphs_preserves_content() {
// Test that field content is preserved
let mut d: super::Deb822 = vec![
vec![("Field1", "Value1"), ("Field2", "Value2")]
.into_iter()
.collect(),
vec![("FieldA", "ValueA"), ("FieldB", "ValueB")]
.into_iter()
.collect(),
]
.into_iter()
.collect();
d.swap_paragraphs(0, 1);
let mut paras = d.paragraphs();
let p1 = paras.next().unwrap();
assert_eq!(p1.get("FieldA").as_deref(), Some("ValueA"));
assert_eq!(p1.get("FieldB").as_deref(), Some("ValueB"));
let p2 = paras.next().unwrap();
assert_eq!(p2.get("Field1").as_deref(), Some("Value1"));
assert_eq!(p2.get("Field2").as_deref(), Some("Value2"));
}
#[test]
#[should_panic(expected = "out of bounds")]
fn test_swap_paragraphs_out_of_bounds() {
let mut d: super::Deb822 = vec![
vec![("Foo", "Bar")].into_iter().collect(),
vec![("A", "B")].into_iter().collect(),
]
.into_iter()
.collect();
d.swap_paragraphs(0, 5);
}
#[test]
fn test_multiline_entry() {
use super::SyntaxKind::*;
use rowan::ast::AstNode;
let entry = super::Entry::new("foo", "bar\nbaz");
let tokens: Vec<_> = entry
.syntax()
.descendants_with_tokens()
.filter_map(|tok| tok.into_token())
.collect();
assert_eq!("foo: bar\n baz\n", entry.to_string());
assert_eq!("bar\nbaz", entry.value());
assert_eq!(
vec![
(KEY, "foo"),
(COLON, ":"),
(WHITESPACE, " "),
(VALUE, "bar"),
(NEWLINE, "\n"),
(INDENT, " "),
(VALUE, "baz"),
(NEWLINE, "\n"),
],
tokens
.iter()
.map(|token| (token.kind(), token.text()))
.collect::<Vec<_>>()
);
}
#[test]
fn test_apt_entry() {
let text = r#"Package: cvsd
Binary: cvsd
Version: 1.0.24
Maintainer: Arthur de Jong <adejong@debian.org>
Build-Depends: debhelper (>= 9), po-debconf
Architecture: any
Standards-Version: 3.9.3
Format: 3.0 (native)
Files:
b7a7d67a02974c52c408fdb5e118406d 890 cvsd_1.0.24.dsc
b73ee40774c3086cb8490cdbb96ac883 258139 cvsd_1.0.24.tar.gz
Vcs-Browser: http://arthurdejong.org/viewvc/cvsd/
Vcs-Cvs: :pserver:anonymous@arthurdejong.org:/arthur/
Checksums-Sha256:
a7bb7a3aacee19cd14ce5c26cb86e348b1608e6f1f6e97c6ea7c58efa440ac43 890 cvsd_1.0.24.dsc
46bc517760c1070ae408693b89603986b53e6f068ae6bdc744e2e830e46b8cba 258139 cvsd_1.0.24.tar.gz
Homepage: http://arthurdejong.org/cvsd/
Package-List:
cvsd deb vcs optional
Directory: pool/main/c/cvsd
Priority: source
Section: vcs
"#;
let d: super::Deb822 = text.parse().unwrap();
let p = d.paragraphs().next().unwrap();
assert_eq!(p.get("Binary").as_deref(), Some("cvsd"));
assert_eq!(p.get("Version").as_deref(), Some("1.0.24"));
assert_eq!(
p.get("Maintainer").as_deref(),
Some("Arthur de Jong <adejong@debian.org>")
);
}
#[test]
fn test_format() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
Section: net
Blah: blah # comment
Multi-Line:
Ahoi!
Matey!
"#
.parse()
.unwrap();
let mut ps = d.paragraphs();
let p = ps.next().unwrap();
let result = p.wrap_and_sort(
crate::Indentation::FieldNameLength,
false,
None,
None::<&dyn Fn(&super::Entry, &super::Entry) -> std::cmp::Ordering>,
None,
);
assert_eq!(
result.to_string(),
r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
Section: net
Blah: blah # comment
Multi-Line: Ahoi!
Matey!
"#
);
}
#[test]
fn test_format_sort_paragraphs() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
# This is a comment
Source: bar
Maintainer: Bar Foo <bar@example.com>
"#
.parse()
.unwrap();
let result = d.wrap_and_sort(
Some(&|a: &super::Paragraph, b: &super::Paragraph| {
a.get("Source").cmp(&b.get("Source"))
}),
Some(&|p| {
p.wrap_and_sort(
crate::Indentation::FieldNameLength,
false,
None,
None::<&dyn Fn(&super::Entry, &super::Entry) -> std::cmp::Ordering>,
None,
)
}),
);
assert_eq!(
result.to_string(),
r#"# This is a comment
Source: bar
Maintainer: Bar Foo <bar@example.com>
Source: foo
Maintainer: Foo Bar <foo@example.com>
"#,
);
}
#[test]
fn test_format_sort_fields() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
Build-Depends: debhelper (>= 9), po-debconf
Homepage: https://example.com/
"#
.parse()
.unwrap();
let result = d.wrap_and_sort(
None,
Some(&|p: &super::Paragraph| -> super::Paragraph {
p.wrap_and_sort(
crate::Indentation::FieldNameLength,
false,
None,
Some(&|a: &super::Entry, b: &super::Entry| a.key().cmp(&b.key())),
None,
)
}),
);
assert_eq!(
result.to_string(),
r#"Build-Depends: debhelper (>= 9), po-debconf
Homepage: https://example.com/
Maintainer: Foo Bar <foo@example.com>
Source: foo
"#
);
}
#[test]
fn test_para_from_iter() {
let p: super::Paragraph = vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect();
assert_eq!(
p.to_string(),
r#"Foo: Bar
Baz: Qux
"#
);
let p: super::Paragraph = vec![
("Foo".to_string(), "Bar".to_string()),
("Baz".to_string(), "Qux".to_string()),
]
.into_iter()
.collect();
assert_eq!(
p.to_string(),
r#"Foo: Bar
Baz: Qux
"#
);
}
#[test]
fn test_deb822_from_iter() {
let d: super::Deb822 = vec![
vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
vec![("A", "B"), ("C", "D")].into_iter().collect(),
]
.into_iter()
.collect();
assert_eq!(
d.to_string(),
r#"Foo: Bar
Baz: Qux
A: B
C: D
"#
);
}
#[test]
fn test_format_parse_error() {
assert_eq!(ParseError(vec!["foo".to_string()]).to_string(), "foo\n");
}
#[test]
fn test_set_with_field_order() {
let mut p = super::Paragraph::new();
let custom_order = &["Foo", "Bar", "Baz"];
p.set_with_field_order("Baz", "3", custom_order);
p.set_with_field_order("Foo", "1", custom_order);
p.set_with_field_order("Bar", "2", custom_order);
p.set_with_field_order("Unknown", "4", custom_order);
let keys: Vec<_> = p.keys().collect();
assert_eq!(keys[0], "Foo");
assert_eq!(keys[1], "Bar");
assert_eq!(keys[2], "Baz");
assert_eq!(keys[3], "Unknown");
}
#[test]
fn test_positioned_parse_error() {
let error = PositionedParseError {
message: "test error".to_string(),
range: rowan::TextRange::new(rowan::TextSize::from(5), rowan::TextSize::from(10)),
code: Some("test_code".to_string()),
};
assert_eq!(error.to_string(), "test error");
assert_eq!(error.range.start(), rowan::TextSize::from(5));
assert_eq!(error.range.end(), rowan::TextSize::from(10));
assert_eq!(error.code, Some("test_code".to_string()));
}
#[test]
fn test_format_error() {
assert_eq!(
super::Error::ParseError(ParseError(vec!["foo".to_string()])).to_string(),
"foo\n"
);
}
#[test]
fn test_get_all() {
let d: super::Deb822 = r#"Source: foo
Maintainer: Foo Bar <foo@example.com>
Maintainer: Bar Foo <bar@example.com>"#
.parse()
.unwrap();
let p = d.paragraphs().next().unwrap();
assert_eq!(
p.get_all("Maintainer").collect::<Vec<_>>(),
vec!["Foo Bar <foo@example.com>", "Bar Foo <bar@example.com>"]
);
}
#[test]
fn test_get_with_indent_single_line() {
let input = "Field: single line value\n";
let deb = super::Deb822::from_str(input).unwrap();
let para = deb.paragraphs().next().unwrap();
// Single-line values should be unchanged regardless of indent pattern
assert_eq!(
para.get_with_indent("Field", &super::IndentPattern::Fixed(2)),
Some("single line value".to_string())
);
assert_eq!(
para.get_with_indent("Field", &super::IndentPattern::FieldNameLength),
Some("single line value".to_string())
);
}
#[test]
fn test_get_with_indent_fixed() {
let input = "Field: First\n Second\n Third\n";
let deb = super::Deb822::from_str(input).unwrap();
let para = deb.paragraphs().next().unwrap();
// Get with fixed 2-space indentation - strips 2 spaces, leaves 1
let value = para
.get_with_indent("Field", &super::IndentPattern::Fixed(2))
.unwrap();
assert_eq!(value, "First\n Second\n Third");
// Get with fixed 1-space indentation - strips 1 space, leaves 2
let value = para
.get_with_indent("Field", &super::IndentPattern::Fixed(1))
.unwrap();
assert_eq!(value, "First\n Second\n Third");
// Get with fixed 3-space indentation - strips all 3 spaces
let value = para
.get_with_indent("Field", &super::IndentPattern::Fixed(3))
.unwrap();
assert_eq!(value, "First\nSecond\nThird");
}
#[test]
fn test_get_with_indent_field_name_length() {
let input = "Description: First line\n Second line\n Third line\n";
let deb = super::Deb822::from_str(input).unwrap();
let para = deb.paragraphs().next().unwrap();
// Get with FieldNameLength pattern
// "Description: " is 13 characters, so strips 13 spaces, leaves 0
let value = para
.get_with_indent("Description", &super::IndentPattern::FieldNameLength)
.unwrap();
assert_eq!(value, "First line\nSecond line\nThird line");
// Get with fixed 2-space indentation - strips 2, leaves 11
let value = para
.get_with_indent("Description", &super::IndentPattern::Fixed(2))
.unwrap();
assert_eq!(
value,
"First line\n Second line\n Third line"
);
}
#[test]
fn test_get_with_indent_nonexistent() {
let input = "Field: value\n";
let deb = super::Deb822::from_str(input).unwrap();
let para = deb.paragraphs().next().unwrap();
assert_eq!(
para.get_with_indent("NonExistent", &super::IndentPattern::Fixed(2)),
None
);
}
#[test]
fn test_get_entry() {
let input = r#"Package: test-package
Maintainer: Test User <test@example.com>
Description: A simple test package
with multiple lines
"#;
let deb = super::Deb822::from_str(input).unwrap();
let para = deb.paragraphs().next().unwrap();
// Test getting existing entry
let entry = para.get_entry("Package");
assert!(entry.is_some());
let entry = entry.unwrap();
assert_eq!(entry.key(), Some("Package".to_string()));
assert_eq!(entry.value(), "test-package");
// Test case-insensitive lookup
let entry = para.get_entry("package");
assert!(entry.is_some());
assert_eq!(entry.unwrap().value(), "test-package");
// Test multi-line value
let entry = para.get_entry("Description");
assert!(entry.is_some());
assert_eq!(
entry.unwrap().value(),
"A simple test package\nwith multiple lines"
);
// Test non-existent field
assert_eq!(para.get_entry("NonExistent"), None);
}
#[test]
fn test_entry_ranges() {
let input = r#"Package: test-package
Maintainer: Test User <test@example.com>
Description: A simple test package
with multiple lines
of description text"#;
let deb822 = super::Deb822::from_str(input).unwrap();
let paragraph = deb822.paragraphs().next().unwrap();
let entries: Vec<_> = paragraph.entries().collect();
// Test first entry (Package)
let package_entry = &entries[0];
assert_eq!(package_entry.key(), Some("Package".to_string()));
// Test key_range
let key_range = package_entry.key_range().unwrap();
assert_eq!(
&input[key_range.start().into()..key_range.end().into()],
"Package"
);
// Test colon_range
let colon_range = package_entry.colon_range().unwrap();
assert_eq!(
&input[colon_range.start().into()..colon_range.end().into()],
":"
);
// Test value_range
let value_range = package_entry.value_range().unwrap();
assert_eq!(
&input[value_range.start().into()..value_range.end().into()],
"test-package"
);
// Test text_range covers the whole entry
let text_range = package_entry.text_range();
assert_eq!(
&input[text_range.start().into()..text_range.end().into()],
"Package: test-package\n"
);
// Test single-line value_line_ranges
let value_lines = package_entry.value_line_ranges();
assert_eq!(value_lines.len(), 1);
assert_eq!(
&input[value_lines[0].start().into()..value_lines[0].end().into()],
"test-package"
);
}
#[test]
fn test_multiline_entry_ranges() {
let input = r#"Description: Short description
Extended description line 1
Extended description line 2"#;
let deb822 = super::Deb822::from_str(input).unwrap();
let paragraph = deb822.paragraphs().next().unwrap();
let entry = paragraph.entries().next().unwrap();
assert_eq!(entry.key(), Some("Description".to_string()));
// Test value_range spans all lines
let value_range = entry.value_range().unwrap();
let full_value = &input[value_range.start().into()..value_range.end().into()];
assert!(full_value.contains("Short description"));
assert!(full_value.contains("Extended description line 1"));
assert!(full_value.contains("Extended description line 2"));
// Test value_line_ranges gives individual lines
let value_lines = entry.value_line_ranges();
assert_eq!(value_lines.len(), 3);
assert_eq!(
&input[value_lines[0].start().into()..value_lines[0].end().into()],
"Short description"
);
assert_eq!(
&input[value_lines[1].start().into()..value_lines[1].end().into()],
"Extended description line 1"
);
assert_eq!(
&input[value_lines[2].start().into()..value_lines[2].end().into()],
"Extended description line 2"
);
}
#[test]
fn test_entries_public_access() {
let input = r#"Package: test
Version: 1.0"#;
let deb822 = super::Deb822::from_str(input).unwrap();
let paragraph = deb822.paragraphs().next().unwrap();
// Test that entries() method is now public
let entries: Vec<_> = paragraph.entries().collect();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].key(), Some("Package".to_string()));
assert_eq!(entries[1].key(), Some("Version".to_string()));
}
#[test]
fn test_empty_value_ranges() {
let input = r#"EmptyField: "#;
let deb822 = super::Deb822::from_str(input).unwrap();
let paragraph = deb822.paragraphs().next().unwrap();
let entry = paragraph.entries().next().unwrap();
assert_eq!(entry.key(), Some("EmptyField".to_string()));
// Empty value should still have ranges
assert!(entry.key_range().is_some());
assert!(entry.colon_range().is_some());
// Empty value might not have value tokens
let value_lines = entry.value_line_ranges();
// This depends on how the parser handles empty values
// but we should not panic
assert!(value_lines.len() <= 1);
}
#[test]
fn test_range_ordering() {
let input = r#"Field: value"#;
let deb822 = super::Deb822::from_str(input).unwrap();
let paragraph = deb822.paragraphs().next().unwrap();
let entry = paragraph.entries().next().unwrap();
let key_range = entry.key_range().unwrap();
let colon_range = entry.colon_range().unwrap();
let value_range = entry.value_range().unwrap();
let text_range = entry.text_range();
// Verify ranges are in correct order
assert!(key_range.end() <= colon_range.start());
assert!(colon_range.end() <= value_range.start());
assert!(key_range.start() >= text_range.start());
assert!(value_range.end() <= text_range.end());
}
#[test]
fn test_error_recovery_missing_colon() {
let input = r#"Source foo
Maintainer: Test User <test@example.com>
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should still parse successfully with errors
assert!(!errors.is_empty());
assert!(errors.iter().any(|e| e.contains("missing colon")));
// Should still have a paragraph with the valid field
let paragraph = deb822.paragraphs().next().unwrap();
assert_eq!(
paragraph.get("Maintainer").as_deref(),
Some("Test User <test@example.com>")
);
}
#[test]
fn test_error_recovery_missing_field_name() {
let input = r#": orphaned value
Package: test
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have errors about missing field name
assert!(!errors.is_empty());
assert!(errors
.iter()
.any(|e| e.contains("field name") || e.contains("missing")));
// The valid field should be in one of the paragraphs
let paragraphs: Vec<_> = deb822.paragraphs().collect();
let mut found_package = false;
for paragraph in paragraphs.iter() {
if paragraph.get("Package").is_some() {
found_package = true;
assert_eq!(paragraph.get("Package").as_deref(), Some("test"));
}
}
assert!(found_package, "Package field not found in any paragraph");
}
#[test]
fn test_error_recovery_orphaned_text() {
let input = r#"Package: test
some orphaned text without field name
Version: 1.0
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have errors about orphaned text
assert!(!errors.is_empty());
assert!(errors.iter().any(|e| e.contains("orphaned")
|| e.contains("unexpected")
|| e.contains("field name")));
// Should still parse the valid fields (may be split across paragraphs)
let mut all_fields = std::collections::HashMap::new();
for paragraph in deb822.paragraphs() {
for (key, value) in paragraph.items() {
all_fields.insert(key, value);
}
}
assert_eq!(all_fields.get("Package"), Some(&"test".to_string()));
assert_eq!(all_fields.get("Version"), Some(&"1.0".to_string()));
}
#[test]
fn test_error_recovery_consecutive_field_names() {
let input = r#"Package: test
Description
Maintainer: Another field without proper value
Version: 1.0
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have errors about missing values
assert!(!errors.is_empty());
assert!(errors.iter().any(|e| e.contains("consecutive")
|| e.contains("missing")
|| e.contains("incomplete")));
// Should still parse valid fields (may be split across paragraphs due to errors)
let mut all_fields = std::collections::HashMap::new();
for paragraph in deb822.paragraphs() {
for (key, value) in paragraph.items() {
all_fields.insert(key, value);
}
}
assert_eq!(all_fields.get("Package"), Some(&"test".to_string()));
assert_eq!(
all_fields.get("Maintainer"),
Some(&"Another field without proper value".to_string())
);
assert_eq!(all_fields.get("Version"), Some(&"1.0".to_string()));
}
#[test]
fn test_error_recovery_malformed_multiline() {
let input = r#"Package: test
Description: Short desc
Proper continuation
invalid continuation without indent
Another proper continuation
Version: 1.0
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should recover from malformed continuation
assert!(!errors.is_empty());
// Should still parse other fields correctly
let paragraph = deb822.paragraphs().next().unwrap();
assert_eq!(paragraph.get("Package").as_deref(), Some("test"));
assert_eq!(paragraph.get("Version").as_deref(), Some("1.0"));
}
#[test]
fn test_error_recovery_mixed_errors() {
let input = r#"Package test without colon
: orphaned colon
Description: Valid field
some orphaned text
Another-Field: Valid too
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have multiple different errors
assert!(!errors.is_empty());
assert!(errors.len() >= 2);
// Should still parse the valid fields
let paragraph = deb822.paragraphs().next().unwrap();
assert_eq!(paragraph.get("Description").as_deref(), Some("Valid field"));
assert_eq!(paragraph.get("Another-Field").as_deref(), Some("Valid too"));
}
#[test]
fn test_error_recovery_paragraph_boundary() {
let input = r#"Package: first-package
Description: First paragraph
corrupted data here
: more corruption
completely broken line
Package: second-package
Version: 1.0
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have errors from the corrupted section
assert!(!errors.is_empty());
// Should still parse both paragraphs correctly
let paragraphs: Vec<_> = deb822.paragraphs().collect();
assert_eq!(paragraphs.len(), 2);
assert_eq!(
paragraphs[0].get("Package").as_deref(),
Some("first-package")
);
assert_eq!(
paragraphs[1].get("Package").as_deref(),
Some("second-package")
);
assert_eq!(paragraphs[1].get("Version").as_deref(), Some("1.0"));
}
#[test]
fn test_error_recovery_with_positioned_errors() {
let input = r#"Package test
Description: Valid
"#;
let parsed = super::parse(input);
// Should have positioned errors with proper ranges
assert!(!parsed.positioned_errors.is_empty());
let first_error = &parsed.positioned_errors[0];
assert!(!first_error.message.is_empty());
assert!(first_error.range.start() <= first_error.range.end());
assert!(first_error.code.is_some());
// Error should point to the problematic location
let error_text = &input[first_error.range.start().into()..first_error.range.end().into()];
assert!(!error_text.is_empty());
}
#[test]
fn test_positioned_error_points_to_correct_token() {
let input = "Package test\nDescription: Valid\n";
let parsed = super::parse(input);
assert_eq!(parsed.positioned_errors.len(), 1);
let first_error = &parsed.positioned_errors[0];
assert_eq!(first_error.message, "missing colon ':' after field name");
assert_eq!(first_error.code.as_deref(), Some("missing_colon"));
let start: usize = first_error.range.start().into();
let end: usize = first_error.range.end().into();
assert_eq!(start, 8);
assert_eq!(end, 12);
assert_eq!(&input[start..end], "test");
}
#[test]
fn test_error_recovery_preserves_whitespace() {
let input = r#"Source: package
Maintainer Test User <test@example.com>
Section: utils
"#;
let (deb822, errors) = super::Deb822::from_str_relaxed(input);
// Should have error about missing colon
assert!(!errors.is_empty());
// Should preserve original formatting in output
let output = deb822.to_string();
assert!(output.contains("Section: utils"));
// Should still extract valid fields
let paragraph = deb822.paragraphs().next().unwrap();
assert_eq!(paragraph.get("Source").as_deref(), Some("package"));
assert_eq!(paragraph.get("Section").as_deref(), Some("utils"));
}
#[test]
fn test_error_recovery_empty_fields() {
let input = r#"Package: test
Description:
Maintainer: Valid User
EmptyField:
Version: 1.0
"#;
let (deb822, _errors) = super::Deb822::from_str_relaxed(input);
// Empty fields should parse without major errors - collect all fields from all paragraphs
let mut all_fields = std::collections::HashMap::new();
for paragraph in deb822.paragraphs() {
for (key, value) in paragraph.items() {
all_fields.insert(key, value);
}
}
assert_eq!(all_fields.get("Package"), Some(&"test".to_string()));
assert_eq!(all_fields.get("Description"), Some(&"".to_string()));
assert_eq!(
all_fields.get("Maintainer"),
Some(&"Valid User".to_string())
);
assert_eq!(all_fields.get("EmptyField"), Some(&"".to_string()));
assert_eq!(all_fields.get("Version"), Some(&"1.0".to_string()));
}
#[test]
fn test_insert_comment_before() {
let d: super::Deb822 = vec![
vec![("Source", "foo"), ("Maintainer", "Bar <bar@example.com>")]
.into_iter()
.collect(),
vec![("Package", "foo"), ("Architecture", "all")]
.into_iter()
.collect(),
]
.into_iter()
.collect();
// Insert comment before first paragraph
let mut p1 = d.paragraphs().next().unwrap();
p1.insert_comment_before("This is the source paragraph");
// Insert comment before second paragraph
let mut p2 = d.paragraphs().nth(1).unwrap();
p2.insert_comment_before("This is the binary paragraph");
let output = d.to_string();
assert_eq!(
output,
r#"# This is the source paragraph
Source: foo
Maintainer: Bar <bar@example.com>
# This is the binary paragraph
Package: foo
Architecture: all
"#
);
}
#[test]
fn test_parse_continuation_with_colon() {
// Test that continuation lines with colons are properly parsed
let input = "Package: test\nDescription: short\n line: with colon\n";
let result = input.parse::<Deb822>();
assert!(result.is_ok());
let deb822 = result.unwrap();
let para = deb822.paragraphs().next().unwrap();
assert_eq!(para.get("Package").as_deref(), Some("test"));
assert_eq!(
para.get("Description").as_deref(),
Some("short\nline: with colon")
);
}
#[test]
fn test_parse_continuation_starting_with_colon() {
// Test continuation line STARTING with a colon (issue #315)
let input = "Package: test\nDescription: short\n :value\n";
let result = input.parse::<Deb822>();
assert!(result.is_ok());
let deb822 = result.unwrap();
let para = deb822.paragraphs().next().unwrap();
assert_eq!(para.get("Package").as_deref(), Some("test"));
assert_eq!(para.get("Description").as_deref(), Some("short\n:value"));
}
#[test]
fn test_normalize_field_spacing_single_space() {
// Field already has correct spacing
let input = "Field: value\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(para.to_string(), "Field: value\n");
}
#[test]
fn test_normalize_field_spacing_extra_spaces() {
// Field has extra spaces after colon
let input = "Field: value\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(para.to_string(), "Field: value\n");
}
#[test]
fn test_normalize_field_spacing_no_space() {
// Field has no space after colon
let input = "Field:value\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(para.to_string(), "Field: value\n");
}
#[test]
fn test_normalize_field_spacing_multiple_fields() {
// Multiple fields with various spacing
let input = "Field1: value1\nField2:value2\nField3: value3\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(
para.to_string(),
"Field1: value1\nField2: value2\nField3: value3\n"
);
}
#[test]
fn test_normalize_field_spacing_multiline_value() {
// Field with multiline value
let input = "Description: short\n continuation line\n . \n final line\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(
para.to_string(),
"Description: short\n continuation line\n . \n final line\n"
);
}
#[test]
fn test_normalize_field_spacing_empty_value_with_whitespace() {
// Field with empty value (only whitespace) should normalize to no space
let input = "Field: \n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
// When value is empty/whitespace-only, normalize to no space
assert_eq!(para.to_string(), "Field:\n");
}
#[test]
fn test_normalize_field_spacing_no_value() {
// Field with no value (just newline) should stay unchanged
let input = "Depends:\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
// Should remain with no space
assert_eq!(para.to_string(), "Depends:\n");
}
#[test]
fn test_normalize_field_spacing_multiple_paragraphs() {
// Multiple paragraphs
let input = "Field1: value1\n\nField2: value2\n";
let mut deb822 = input.parse::<Deb822>().unwrap();
deb822.normalize_field_spacing();
assert_eq!(deb822.to_string(), "Field1: value1\n\nField2: value2\n");
}
#[test]
fn test_normalize_field_spacing_preserves_comments() {
// Normalize spacing while preserving comments (comments are at document level)
let input = "# Comment\nField: value\n";
let mut deb822 = input.parse::<Deb822>().unwrap();
deb822.normalize_field_spacing();
assert_eq!(deb822.to_string(), "# Comment\nField: value\n");
}
#[test]
fn test_normalize_field_spacing_preserves_values() {
// Ensure values are preserved exactly
let input = "Source: foo-bar\nMaintainer:Foo Bar <test@example.com>\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(para.get("Source").as_deref(), Some("foo-bar"));
assert_eq!(
para.get("Maintainer").as_deref(),
Some("Foo Bar <test@example.com>")
);
}
#[test]
fn test_normalize_field_spacing_tab_after_colon() {
// Field with tab after colon (should be normalized to single space)
let input = "Field:\tvalue\n";
let deb822 = input.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
para.normalize_field_spacing();
assert_eq!(para.to_string(), "Field: value\n");
}
#[test]
fn test_set_preserves_indentation() {
// Test that Paragraph.set() preserves the original indentation
let original = r#"Source: example
Build-Depends: foo,
bar,
baz
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Modify the Build-Depends field
para.set("Build-Depends", "foo,\nbar,\nbaz");
// The indentation should be preserved (15 spaces for "Build-Depends: ")
let expected = r#"Source: example
Build-Depends: foo,
bar,
baz
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_new_field_detects_field_name_length_indent() {
// Test that new fields detect field-name-length-based indentation
let original = r#"Source: example
Build-Depends: foo,
bar,
baz
Depends: lib1,
lib2
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field - should detect that indentation is field-name-length + 2
para.set("Recommends", "pkg1,\npkg2,\npkg3");
// "Recommends: " is 12 characters, so indentation should be 12 spaces
assert!(para
.to_string()
.contains("Recommends: pkg1,\n pkg2,"));
}
#[test]
fn test_set_new_field_detects_fixed_indent() {
// Test that new fields detect fixed indentation pattern
let original = r#"Source: example
Build-Depends: foo,
bar,
baz
Depends: lib1,
lib2
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field - should detect fixed 5-space indentation
para.set("Recommends", "pkg1,\npkg2,\npkg3");
// Should use the same 5-space indentation
assert!(para
.to_string()
.contains("Recommends: pkg1,\n pkg2,\n pkg3\n"));
}
#[test]
fn test_set_new_field_no_multiline_fields() {
// Test that new fields use field-name-length when no existing multi-line fields
let original = r#"Source: example
Maintainer: Test <test@example.com>
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field - should default to field name length + 2
para.set("Depends", "foo,\nbar,\nbaz");
// "Depends: " is 9 characters, so indentation should be 9 spaces
let expected = r#"Source: example
Maintainer: Test <test@example.com>
Depends: foo,
bar,
baz
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_new_field_mixed_indentation() {
// Test that new fields fall back to field-name-length when pattern is inconsistent
let original = r#"Source: example
Build-Depends: foo,
bar
Depends: lib1,
lib2
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field - mixed pattern, should fall back to field name length + 2
para.set("Recommends", "pkg1,\npkg2");
// "Recommends: " is 12 characters
assert!(para
.to_string()
.contains("Recommends: pkg1,\n pkg2\n"));
}
#[test]
fn test_entry_with_indentation() {
// Test Entry::with_indentation directly
let entry = super::Entry::with_indentation("Test-Field", "value1\nvalue2\nvalue3", " ");
assert_eq!(
entry.to_string(),
"Test-Field: value1\n value2\n value3\n"
);
}
#[test]
fn test_set_with_indent_pattern_fixed() {
// Test setting a field with explicit fixed indentation pattern
let original = r#"Source: example
Maintainer: Test <test@example.com>
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field with fixed 4-space indentation
para.set_with_indent_pattern(
"Depends",
"foo,\nbar,\nbaz",
Some(&super::IndentPattern::Fixed(4)),
None,
);
// Should use the specified 4-space indentation
let expected = r#"Source: example
Maintainer: Test <test@example.com>
Depends: foo,
bar,
baz
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_with_indent_pattern_field_name_length() {
// Test setting a field with field-name-length indentation pattern
let original = r#"Source: example
Maintainer: Test <test@example.com>
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a new multi-line field with field-name-length indentation
para.set_with_indent_pattern(
"Build-Depends",
"libfoo,\nlibbar,\nlibbaz",
Some(&super::IndentPattern::FieldNameLength),
None,
);
// "Build-Depends: " is 15 characters, so indentation should be 15 spaces
let expected = r#"Source: example
Maintainer: Test <test@example.com>
Build-Depends: libfoo,
libbar,
libbaz
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_with_indent_pattern_override_auto_detection() {
// Test that explicit default pattern overrides auto-detection for new fields
let original = r#"Source: example
Build-Depends: foo,
bar,
baz
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a NEW field with fixed 2-space indentation, overriding the auto-detected pattern
para.set_with_indent_pattern(
"Depends",
"lib1,\nlib2,\nlib3",
Some(&super::IndentPattern::Fixed(2)),
None,
);
// Should use the specified 2-space indentation, not the auto-detected 15-space
let expected = r#"Source: example
Build-Depends: foo,
bar,
baz
Depends: lib1,
lib2,
lib3
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_with_indent_pattern_none_auto_detects() {
// Test that None pattern auto-detects from existing fields
let original = r#"Source: example
Build-Depends: foo,
bar,
baz
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a field with None pattern - should auto-detect fixed 5-space
para.set_with_indent_pattern("Depends", "lib1,\nlib2", None, None);
// Should auto-detect and use the 5-space indentation
let expected = r#"Source: example
Build-Depends: foo,
bar,
baz
Depends: lib1,
lib2
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_with_indent_pattern_with_field_order() {
// Test setting a field with both indent pattern and field ordering
let original = r#"Source: example
Maintainer: Test <test@example.com>
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Add a field with fixed indentation and specific field ordering
para.set_with_indent_pattern(
"Priority",
"optional",
Some(&super::IndentPattern::Fixed(4)),
Some(&["Source", "Priority", "Maintainer"]),
);
// Priority should be inserted between Source and Maintainer
let expected = r#"Source: example
Priority: optional
Maintainer: Test <test@example.com>
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_set_with_indent_pattern_replace_existing() {
// Test that replacing an existing multi-line field preserves its indentation
let original = r#"Source: example
Depends: foo,
bar
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Replace Depends - the default pattern is ignored, existing indentation is preserved
para.set_with_indent_pattern(
"Depends",
"lib1,\nlib2,\nlib3",
Some(&super::IndentPattern::Fixed(3)),
None,
);
// Should preserve the existing 9-space indentation, not use the default 3-space
let expected = r#"Source: example
Depends: lib1,
lib2,
lib3
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_change_field_indent() {
// Test changing indentation of an existing field without changing its value
let original = r#"Source: example
Depends: foo,
bar,
baz
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Change Depends field to use 2-space indentation
let result = para
.change_field_indent("Depends", &super::IndentPattern::Fixed(2))
.unwrap();
assert!(result, "Field should have been found and updated");
let expected = r#"Source: example
Depends: foo,
bar,
baz
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_change_field_indent_nonexistent() {
// Test changing indentation of a non-existent field
let original = r#"Source: example
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Try to change indentation of non-existent field
let result = para
.change_field_indent("Depends", &super::IndentPattern::Fixed(2))
.unwrap();
assert!(!result, "Should return false for non-existent field");
// Paragraph should be unchanged
assert_eq!(para.to_string(), original);
}
#[test]
fn test_change_field_indent_case_insensitive() {
// Test that change_field_indent is case-insensitive
let original = r#"Build-Depends: foo,
bar
"#;
let mut para: super::Paragraph = original.parse().unwrap();
// Change using different case
let result = para
.change_field_indent("build-depends", &super::IndentPattern::Fixed(1))
.unwrap();
assert!(result, "Should find field case-insensitively");
let expected = r#"Build-Depends: foo,
bar
"#;
assert_eq!(para.to_string(), expected);
}
#[test]
fn test_entry_get_indent() {
// Test that we can extract indentation from an entry
let original = r#"Build-Depends: foo,
bar,
baz
"#;
let para: super::Paragraph = original.parse().unwrap();
let entry = para.entries().next().unwrap();
assert_eq!(entry.get_indent(), Some(" ".to_string()));
}
#[test]
fn test_entry_get_indent_single_line() {
// Single-line entries should return None for indentation
let original = r#"Source: example
"#;
let para: super::Paragraph = original.parse().unwrap();
let entry = para.entries().next().unwrap();
assert_eq!(entry.get_indent(), None);
}
}
#[test]
fn test_move_paragraph_forward() {
let mut d: Deb822 = vec![
vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
vec![("A", "B"), ("C", "D")].into_iter().collect(),
vec![("X", "Y"), ("Z", "W")].into_iter().collect(),
]
.into_iter()
.collect();
d.move_paragraph(0, 2);
assert_eq!(
d.to_string(),
"A: B\nC: D\n\nX: Y\nZ: W\n\nFoo: Bar\nBaz: Qux\n"
);
}
#[test]
fn test_move_paragraph_backward() {
let mut d: Deb822 = vec![
vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
vec![("A", "B"), ("C", "D")].into_iter().collect(),
vec![("X", "Y"), ("Z", "W")].into_iter().collect(),
]
.into_iter()
.collect();
d.move_paragraph(2, 0);
assert_eq!(
d.to_string(),
"X: Y\nZ: W\n\nFoo: Bar\nBaz: Qux\n\nA: B\nC: D\n"
);
}
#[test]
fn test_move_paragraph_middle() {
let mut d: Deb822 = vec![
vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
vec![("A", "B"), ("C", "D")].into_iter().collect(),
vec![("X", "Y"), ("Z", "W")].into_iter().collect(),
]
.into_iter()
.collect();
d.move_paragraph(2, 1);
assert_eq!(
d.to_string(),
"Foo: Bar\nBaz: Qux\n\nX: Y\nZ: W\n\nA: B\nC: D\n"
);
}
#[test]
fn test_move_paragraph_same_index() {
let mut d: Deb822 = vec![
vec![("Foo", "Bar"), ("Baz", "Qux")].into_iter().collect(),
vec![("A", "B"), ("C", "D")].into_iter().collect(),
]
.into_iter()
.collect();
let original = d.to_string();
d.move_paragraph(1, 1);
assert_eq!(d.to_string(), original);
}
#[test]
fn test_move_paragraph_single() {
let mut d: Deb822 = vec![vec![("Foo", "Bar")].into_iter().collect()]
.into_iter()
.collect();
let original = d.to_string();
d.move_paragraph(0, 0);
assert_eq!(d.to_string(), original);
}
#[test]
fn test_move_paragraph_invalid_index() {
let mut d: Deb822 = vec![
vec![("Foo", "Bar")].into_iter().collect(),
vec![("A", "B")].into_iter().collect(),
]
.into_iter()
.collect();
let original = d.to_string();
d.move_paragraph(0, 5);
assert_eq!(d.to_string(), original);
}
#[test]
fn test_move_paragraph_with_comments() {
let text = r#"Foo: Bar
# This is a comment
A: B
X: Y
"#;
let mut d: Deb822 = text.parse().unwrap();
d.move_paragraph(0, 2);
assert_eq!(
d.to_string(),
"# This is a comment\n\nA: B\n\nX: Y\n\nFoo: Bar\n"
);
}
#[test]
fn test_case_insensitive_get() {
let text = "Package: test\nVersion: 1.0\n";
let d: Deb822 = text.parse().unwrap();
let p = d.paragraphs().next().unwrap();
// Test different case variations
assert_eq!(p.get("Package").as_deref(), Some("test"));
assert_eq!(p.get("package").as_deref(), Some("test"));
assert_eq!(p.get("PACKAGE").as_deref(), Some("test"));
assert_eq!(p.get("PaCkAgE").as_deref(), Some("test"));
assert_eq!(p.get("Version").as_deref(), Some("1.0"));
assert_eq!(p.get("version").as_deref(), Some("1.0"));
assert_eq!(p.get("VERSION").as_deref(), Some("1.0"));
}
#[test]
fn test_case_insensitive_set() {
let text = "Package: test\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
// Set with different case should update the existing field
p.set("package", "updated");
assert_eq!(p.get("Package").as_deref(), Some("updated"));
assert_eq!(p.get("package").as_deref(), Some("updated"));
// Set with UPPERCASE
p.set("PACKAGE", "updated2");
assert_eq!(p.get("Package").as_deref(), Some("updated2"));
// Field count should remain 1
assert_eq!(p.keys().count(), 1);
}
#[test]
fn test_case_insensitive_remove() {
let text = "Package: test\nVersion: 1.0\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
// Remove with different case
p.remove("package");
assert_eq!(p.get("Package"), None);
assert_eq!(p.get("Version").as_deref(), Some("1.0"));
// Remove with uppercase
p.remove("VERSION");
assert_eq!(p.get("Version"), None);
// No fields left
assert_eq!(p.keys().count(), 0);
}
#[test]
fn test_case_preservation() {
let text = "Package: test\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
// Original case should be preserved
let original_text = d.to_string();
assert_eq!(original_text, "Package: test\n");
// Set with different case should preserve original case
p.set("package", "updated");
// The field name should still be "Package" (original case preserved)
let updated_text = d.to_string();
assert_eq!(updated_text, "Package: updated\n");
}
#[test]
fn test_case_insensitive_contains_key() {
let text = "Package: test\n";
let d: Deb822 = text.parse().unwrap();
let p = d.paragraphs().next().unwrap();
assert!(p.contains_key("Package"));
assert!(p.contains_key("package"));
assert!(p.contains_key("PACKAGE"));
assert!(!p.contains_key("NonExistent"));
}
#[test]
fn test_case_insensitive_get_all() {
let text = "Package: test1\npackage: test2\n";
let d: Deb822 = text.parse().unwrap();
let p = d.paragraphs().next().unwrap();
let values: Vec<String> = p.get_all("PACKAGE").collect();
assert_eq!(values, vec!["test1", "test2"]);
}
#[test]
fn test_case_insensitive_rename() {
let text = "Package: test\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
// Rename with different case
assert!(p.rename("package", "NewName"));
assert_eq!(p.get("NewName").as_deref(), Some("test"));
assert_eq!(p.get("Package"), None);
}
#[test]
fn test_rename_changes_case() {
let text = "Package: test\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
// Rename to different case of the same name
assert!(p.rename("package", "PACKAGE"));
// The field name should now be uppercase
let updated_text = d.to_string();
assert_eq!(updated_text, "PACKAGE: test\n");
// Can still get with any case
assert_eq!(p.get("package").as_deref(), Some("test"));
assert_eq!(p.get("Package").as_deref(), Some("test"));
assert_eq!(p.get("PACKAGE").as_deref(), Some("test"));
}
#[test]
fn test_rename_preserves_indentation_and_whitespace() {
// When renaming a field, the original post-colon whitespace and
// continuation-line indentation must be preserved (only the key changes).
let text =
"Comments: Exceptions\n 1997-1999, 2003 MIT\n License terms\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
assert!(p.rename("Comments", "Comment"));
assert_eq!(
d.to_string(),
"Comment: Exceptions\n 1997-1999, 2003 MIT\n License terms\n"
);
}
#[test]
fn test_rename_in_multi_field_paragraph() {
// Reproduce the intel-mkl scenario: Comments is the last of several
// fields, with multi-line value containing internal indentation.
let text = "Files: *\nCopyright: 2017 Foo\nLicense: GPL-2+\nComments: Exceptions\n There are many files in the .rpm archives.\n 1997-1999, 2003 MIT\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
assert!(p.rename("Comments", "Comment"));
assert_eq!(d.to_string(), text.replace("Comments:", "Comment:"));
}
#[test]
fn test_rename_preserves_post_colon_whitespace() {
// A single-line value with non-default post-colon whitespace must keep it.
let text = "Files: install_GUI.sh\n";
let d: Deb822 = text.parse().unwrap();
let mut p = d.paragraphs().next().unwrap();
assert!(p.rename("Files", "File"));
assert_eq!(d.to_string(), "File: install_GUI.sh\n");
}
#[test]
fn test_reject_whitespace_only_continuation_line() {
// Issue #350: A continuation line with only whitespace should not be accepted
// According to Debian Policy, continuation lines must have content after the leading space
// A line with only whitespace (like " \n") should terminate the field
// This should be rejected/treated as an error
let text = "Build-Depends:\n \ndebhelper\n";
let parsed = Deb822::parse(text);
// The empty line with just whitespace should cause an error
// or at minimum, should not be included as part of the field value
assert!(
!parsed.errors().is_empty(),
"Expected parse errors for whitespace-only continuation line"
);
}
#[test]
fn test_reject_empty_continuation_line_in_multiline_field() {
// Test that an empty line terminates a multi-line field (and generates an error)
let text = "Depends: foo,\n bar,\n \n baz\n";
let parsed = Deb822::parse(text);
// The empty line should cause parse errors
assert!(
!parsed.errors().is_empty(),
"Empty continuation line should generate parse errors"
);
// Verify we got the specific error about empty continuation line
let has_empty_line_error = parsed
.errors()
.iter()
.any(|e| e.contains("empty continuation line"));
assert!(
has_empty_line_error,
"Should have an error about empty continuation line"
);
}
#[test]
#[should_panic(expected = "empty continuation line")]
fn test_set_rejects_empty_continuation_lines() {
// Test that Paragraph.set() panics for values with empty continuation lines
let text = "Package: test\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
// Try to set a field with an empty continuation line
// This should panic with an appropriate error message
let value_with_empty_line = "foo\n \nbar";
para.set("Depends", value_with_empty_line);
}
#[test]
fn test_try_set_returns_error_for_empty_continuation_lines() {
// Test that Paragraph.try_set() returns an error for values with empty continuation lines
let text = "Package: test\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
// Try to set a field with an empty continuation line
let value_with_empty_line = "foo\n \nbar";
let result = para.try_set("Depends", value_with_empty_line);
// Should return an error
assert!(
result.is_err(),
"try_set() should return an error for empty continuation lines"
);
// Verify it's the right kind of error
match result {
Err(Error::InvalidValue(msg)) => {
assert!(
msg.contains("empty continuation line"),
"Error message should mention empty continuation line"
);
}
_ => panic!("Expected InvalidValue error"),
}
}
#[test]
fn test_try_set_with_indent_pattern_returns_error() {
// Test that try_set_with_indent_pattern() returns an error for empty continuation lines
let text = "Package: test\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
let value_with_empty_line = "foo\n \nbar";
let result = para.try_set_with_indent_pattern(
"Depends",
value_with_empty_line,
Some(&IndentPattern::Fixed(2)),
None,
);
assert!(
result.is_err(),
"try_set_with_indent_pattern() should return an error"
);
}
#[test]
fn test_try_set_succeeds_for_valid_value() {
// Test that try_set() succeeds for valid values
let text = "Package: test\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
// Valid multiline value
let valid_value = "foo\nbar";
let result = para.try_set("Depends", valid_value);
assert!(result.is_ok(), "try_set() should succeed for valid values");
assert_eq!(para.get("Depends").as_deref(), Some("foo\nbar"));
}
#[test]
fn test_field_with_empty_first_line() {
// Test parsing a field where the value starts on a continuation line (empty first line)
// This is valid according to Debian Policy - the first line can be empty
let text = "Foo:\n blah\n blah\n";
let parsed = Deb822::parse(text);
// This should be valid - no errors
assert!(
parsed.errors().is_empty(),
"Empty first line should be valid. Got errors: {:?}",
parsed.errors()
);
let deb822 = parsed.tree();
let para = deb822.paragraphs().next().unwrap();
assert_eq!(para.get("Foo").as_deref(), Some("blah\nblah"));
}
#[test]
fn test_try_set_with_empty_first_line() {
// Test that try_set() works with values that have empty first line
let text = "Package: test\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
// Value with empty first line - this should be valid
let value = "\nblah\nmore";
let result = para.try_set("Depends", value);
assert!(
result.is_ok(),
"try_set() should succeed for values with empty first line. Got: {:?}",
result
);
}
#[test]
fn test_field_with_value_then_empty_continuation() {
// Test that a field with a value on the first line followed by empty continuation is rejected
let text = "Foo: bar\n \n";
let parsed = Deb822::parse(text);
// This should have errors - empty continuation line after initial value
assert!(
!parsed.errors().is_empty(),
"Field with value then empty continuation line should be rejected"
);
// Verify we got the specific error about empty continuation line
let has_empty_line_error = parsed
.errors()
.iter()
.any(|e| e.contains("empty continuation line"));
assert!(
has_empty_line_error,
"Should have error about empty continuation line"
);
}
#[test]
fn test_substvar_continuation_line() {
let text = "\
Package: python3-cryptography
Architecture: any
Depends: python3-bcrypt,
${misc:Depends},
${python3:Depends},
${shlibs:Depends},
Suggests: python-cryptography-doc,
python3-cryptography-vectors,
Description: Python library exposing cryptographic recipes and primitives
The cryptography library is designed to be a \"one-stop-shop\" for
all your cryptographic needs in Python.
.
As an alternative to the libraries that came before it, cryptography
tries to address some of the issues with those libraries:
- Lack of PyPy and Python 3 support.
- Lack of maintenance.
- Use of poor implementations of algorithms (i.e. ones with known
side-channel attacks).
- Lack of high level, \"Cryptography for humans\", APIs.
- Absence of algorithms such as AES-GCM.
- Poor introspectability, and thus poor testability.
- Extremely error prone APIs, and bad defaults.
";
let parsed = Deb822::parse(text);
for e in parsed.positioned_errors() {
eprintln!("error at {:?}: {}", e.range, e.message);
}
assert!(
parsed.errors().is_empty(),
"Should not produce errors: {:?}",
parsed.errors()
);
assert!(
parsed.positioned_errors().is_empty(),
"Should not produce positioned errors: {:?}",
parsed.positioned_errors()
);
}
#[test]
fn test_line_col() {
let text = r#"Source: foo
Maintainer: Foo Bar <jelmer@jelmer.uk>
Section: net
Package: foo
Architecture: all
Depends: libc6
Description: This is a description
With details
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Test paragraph line numbers
let paras: Vec<_> = deb822.paragraphs().collect();
assert_eq!(paras.len(), 2);
// First paragraph starts at line 0
assert_eq!(paras[0].line(), 0);
assert_eq!(paras[0].column(), 0);
// Second paragraph starts at line 4 (after the empty line)
assert_eq!(paras[1].line(), 4);
assert_eq!(paras[1].column(), 0);
// Test entry line numbers
let entries: Vec<_> = paras[0].entries().collect();
assert_eq!(entries[0].line(), 0); // Source: foo
assert_eq!(entries[1].line(), 1); // Maintainer: ...
assert_eq!(entries[2].line(), 2); // Section: net
// Test column numbers
assert_eq!(entries[0].column(), 0); // Start of line
assert_eq!(entries[1].column(), 0); // Start of line
// Test line_col() method
assert_eq!(paras[1].line_col(), (4, 0));
assert_eq!(entries[0].line_col(), (0, 0));
// Test multi-line entry
let second_para_entries: Vec<_> = paras[1].entries().collect();
assert_eq!(second_para_entries[3].line(), 7); // Description starts at line 7
}
#[test]
fn test_deb822_snapshot_independence() {
let text = r#"Source: foo
Maintainer: Joe <joe@example.com>
Package: foo
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let snap = deb822.snapshot();
assert!(deb822.tree_eq(&snap));
let mut para = deb822.paragraphs().next().unwrap();
para.set("Source", "modified");
// snapshot unchanged
let snap_para = snap.paragraphs().next().unwrap();
assert_eq!(snap_para.get("Source").as_deref(), Some("foo"));
// ... and now they have diverged
assert!(!deb822.tree_eq(&snap));
}
#[test]
fn test_paragraph_snapshot_independence() {
let text = "Package: foo\nArchitecture: all\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
let snap = para.snapshot();
assert!(para.tree_eq(&snap));
para.set("Package", "modified");
assert_eq!(snap.get("Package").as_deref(), Some("foo"));
assert!(!para.tree_eq(&snap));
}
#[test]
fn test_tree_eq_value_equivalence() {
// Two independently-parsed trees with identical content should be tree_eq
// (no shared green pointer, but structural equality holds).
let text = "Package: foo\nArchitecture: all\n";
let a = text.parse::<Deb822>().unwrap();
let b = text.parse::<Deb822>().unwrap();
assert!(a.tree_eq(&b));
assert!(b.tree_eq(&a));
// Different content => not tree_eq.
let c: Deb822 = "Package: bar\n".parse().unwrap();
assert!(!a.tree_eq(&c));
}
#[test]
fn test_entry_snapshot_independence() {
let text = "Package: foo\n";
let deb822 = text.parse::<Deb822>().unwrap();
let mut para = deb822.paragraphs().next().unwrap();
let entry = para.entries().next().unwrap();
let snap = entry.snapshot();
assert!(entry.tree_eq(&snap));
para.set("Package", "modified");
// The snapshot entry points to an independent tree
assert_eq!(snap.value(), "foo");
}
#[test]
fn test_paragraph_text_range() {
// Test that text_range() returns the correct range for a paragraph
let text = r#"Source: foo
Maintainer: Joe <joe@example.com>
Package: foo
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let paras: Vec<_> = deb822.paragraphs().collect();
// First paragraph
let range1 = paras[0].text_range();
let para1_text = &text[range1.start().into()..range1.end().into()];
assert_eq!(
para1_text,
"Source: foo\nMaintainer: Joe <joe@example.com>\n"
);
// Second paragraph
let range2 = paras[1].text_range();
let para2_text = &text[range2.start().into()..range2.end().into()];
assert_eq!(para2_text, "Package: foo\nArchitecture: all\n");
}
#[test]
fn test_paragraphs_in_range_single() {
// Test finding a single paragraph in range
let text = r#"Source: foo
Package: bar
Package: baz
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Get range of first paragraph
let first_para = deb822.paragraphs().next().unwrap();
let range = first_para.text_range();
// Query paragraphs in that range
let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
assert_eq!(paras.len(), 1);
assert_eq!(paras[0].get("Source").as_deref(), Some("foo"));
}
#[test]
fn test_paragraphs_in_range_multiple() {
// Test finding multiple paragraphs in range
let text = r#"Source: foo
Package: bar
Package: baz
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Create a range that covers first two paragraphs
let range = rowan::TextRange::new(0.into(), 25.into());
// Query paragraphs in that range
let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
assert_eq!(paras.len(), 2);
assert_eq!(paras[0].get("Source").as_deref(), Some("foo"));
assert_eq!(paras[1].get("Package").as_deref(), Some("bar"));
}
#[test]
fn test_paragraphs_in_range_partial_overlap() {
// Test that paragraphs are included if they partially overlap with the range
let text = r#"Source: foo
Package: bar
Package: baz
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Create a range that starts in the middle of the second paragraph
let range = rowan::TextRange::new(15.into(), 30.into());
// Should include the second paragraph since it overlaps
let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
assert!(paras.len() >= 1);
assert!(paras
.iter()
.any(|p| p.get("Package").as_deref() == Some("bar")));
}
#[test]
fn test_paragraphs_in_range_no_match() {
// Test that empty iterator is returned when no paragraphs are in range
let text = r#"Source: foo
Package: bar
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Create a range that's way beyond the document
let range = rowan::TextRange::new(1000.into(), 2000.into());
// Should return empty iterator
let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
assert_eq!(paras.len(), 0);
}
#[test]
fn test_paragraphs_in_range_all() {
// Test finding all paragraphs when range covers entire document
let text = r#"Source: foo
Package: bar
Package: baz
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Create a range that covers the entire document
let range = rowan::TextRange::new(0.into(), text.len().try_into().unwrap());
// Should return all paragraphs
let paras: Vec<_> = deb822.paragraphs_in_range(range).collect();
assert_eq!(paras.len(), 3);
}
#[test]
fn test_paragraph_at_position() {
// Test finding paragraph at a given text offset
let text = r#"Package: foo
Version: 1.0
Package: bar
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Position 5 is within first paragraph ("Package: foo")
let para = deb822.paragraph_at_position(rowan::TextSize::from(5));
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("foo"));
// Position 30 is within second paragraph
let para = deb822.paragraph_at_position(rowan::TextSize::from(30));
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("bar"));
// Position beyond document
let para = deb822.paragraph_at_position(rowan::TextSize::from(1000));
assert!(para.is_none());
}
#[test]
fn test_paragraph_at_line() {
// Test finding paragraph at a given line number
let text = r#"Package: foo
Version: 1.0
Package: bar
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Line 0 is in first paragraph
let para = deb822.paragraph_at_line(0);
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("foo"));
// Line 1 is also in first paragraph
let para = deb822.paragraph_at_line(1);
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("foo"));
// Line 3 is in second paragraph
let para = deb822.paragraph_at_line(3);
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("bar"));
// Line beyond document
let para = deb822.paragraph_at_line(100);
assert!(para.is_none());
}
#[test]
fn test_entry_at_line_col() {
// Test finding entry at a given line/column position
let text = r#"Package: foo
Version: 1.0
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Line 0, column 0 is in "Package: foo"
let entry = deb822.entry_at_line_col(0, 0);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Package".to_string()));
// Line 1, column 0 is in "Version: 1.0"
let entry = deb822.entry_at_line_col(1, 0);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Version".to_string()));
// Line 2, column 5 is in "Architecture: all"
let entry = deb822.entry_at_line_col(2, 5);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Architecture".to_string()));
// Position beyond document
let entry = deb822.entry_at_line_col(100, 0);
assert!(entry.is_none());
}
#[test]
fn test_entry_at_line_col_multiline() {
// Test finding entry in a multiline value
let text = r#"Package: foo
Description: A package
with a long
description
Version: 1.0
"#;
let deb822 = text.parse::<Deb822>().unwrap();
// Line 1 is the start of Description
let entry = deb822.entry_at_line_col(1, 0);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Description".to_string()));
// Line 2 is continuation of Description
let entry = deb822.entry_at_line_col(2, 1);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Description".to_string()));
// Line 3 is also continuation of Description
let entry = deb822.entry_at_line_col(3, 1);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Description".to_string()));
// Line 4 is Version
let entry = deb822.entry_at_line_col(4, 0);
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Version".to_string()));
}
#[test]
fn test_entries_in_range() {
// Test finding entries in a paragraph within a range
let text = r#"Package: foo
Version: 1.0
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// Get first entry's range
let first_entry = para.entries().next().unwrap();
let range = first_entry.text_range();
// Query entries in that range - should get only first entry
let entries: Vec<_> = para.entries_in_range(range).collect();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].key(), Some("Package".to_string()));
// Query with a range covering first two entries
let range = rowan::TextRange::new(0.into(), 25.into());
let entries: Vec<_> = para.entries_in_range(range).collect();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].key(), Some("Package".to_string()));
assert_eq!(entries[1].key(), Some("Version".to_string()));
}
#[test]
fn test_entries_in_range_partial_overlap() {
// Test that entries with partial overlap are included
let text = r#"Package: foo
Version: 1.0
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// Create a range that starts in the middle of the second entry
let range = rowan::TextRange::new(15.into(), 30.into());
let entries: Vec<_> = para.entries_in_range(range).collect();
assert!(entries.len() >= 1);
assert!(entries
.iter()
.any(|e| e.key() == Some("Version".to_string())));
}
#[test]
fn test_entries_in_range_no_match() {
// Test that empty iterator is returned when no entries match
let text = "Package: foo\n";
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// Range beyond the paragraph
let range = rowan::TextRange::new(1000.into(), 2000.into());
let entries: Vec<_> = para.entries_in_range(range).collect();
assert_eq!(entries.len(), 0);
}
#[test]
fn test_entry_at_position() {
// Test finding entry at a specific text offset
let text = r#"Package: foo
Version: 1.0
Architecture: all
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// Position 5 is within "Package: foo"
let entry = para.entry_at_position(rowan::TextSize::from(5));
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Package".to_string()));
// Position 15 is within "Version: 1.0"
let entry = para.entry_at_position(rowan::TextSize::from(15));
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Version".to_string()));
// Position beyond paragraph
let entry = para.entry_at_position(rowan::TextSize::from(1000));
assert!(entry.is_none());
}
#[test]
fn test_entry_at_position_multiline() {
// Test finding entry in a multiline value
let text = r#"Description: A package
with a long
description
"#;
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// Position 5 is within the Description entry
let entry = para.entry_at_position(rowan::TextSize::from(5));
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Description".to_string()));
// Position in continuation line should also find the Description entry
let entry = para.entry_at_position(rowan::TextSize::from(30));
assert!(entry.is_some());
assert_eq!(entry.unwrap().key(), Some("Description".to_string()));
}
#[test]
fn test_paragraph_at_position_at_boundary() {
// Test paragraph_at_position at paragraph boundaries
let text = "Package: foo\n\nPackage: bar\n";
let deb822 = text.parse::<Deb822>().unwrap();
// Position 0 is start of first paragraph
let para = deb822.paragraph_at_position(rowan::TextSize::from(0));
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("foo"));
// Position at start of second paragraph
let para = deb822.paragraph_at_position(rowan::TextSize::from(15));
assert!(para.is_some());
assert_eq!(para.unwrap().get("Package").as_deref(), Some("bar"));
}
#[test]
fn test_comment_in_multiline_value() {
// Commented-out continuation lines within a multi-line field value
// should be preserved losslessly and not cause parse errors.
let text = "\
Build-Depends: dh-python,
libsvn-dev,
# python-all-dbg (>= 2.6.6-3),
python3-all-dev,
# python3-all-dbg,
python3-docutils
Standards-Version: 4.7.0
";
let deb822 = text.parse::<Deb822>().unwrap();
let para = deb822.paragraphs().next().unwrap();
// get() returns the value without comments
assert_eq!(
para.get("Build-Depends").as_deref(),
Some("dh-python,\nlibsvn-dev,\npython3-all-dev,\npython3-docutils")
);
// get_with_comments() / value_with_comments() includes the comment lines
assert_eq!(
para.get_with_comments("Build-Depends").as_deref(),
Some("dh-python,\nlibsvn-dev,\n# python-all-dbg (>= 2.6.6-3),\npython3-all-dev,\n# python3-all-dbg,\npython3-docutils")
);
assert_eq!(para.get("Standards-Version").as_deref(), Some("4.7.0"));
// Round-trip
assert_eq!(deb822.to_string(), text);
}