bigtext 0.15.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
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
//! BigText's tools for scripts, without a window: `bigtext-cli COMMAND …` (or `bigtext --COMMAND
//! …`). They stream like the editor does, so they work on files of any size.
//!
//! Exit codes: 0 done (for the commands that search: something was found), 1 nothing found
//! (for the diff family and `validate`: the files differ, or there are problems), 2 an error.
//! USAGE.md has the table per command; it does not change before 2.0 once 1.0 is out.

use std::io::{self, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::csv;
use crate::encoding::{self, Detected};
use crate::file::{display_path, OpenMode, Source};
use crate::filter::{self, FilterSpec};
use crate::index::LineIndex;
use crate::jobs::{human_bytes, CancelToken, Progress};
use crate::lines::LineReader;
use crate::loglevel::{self, Level, Levels};
use crate::merge::{self, Input};
use crate::search::{Matcher, Query};
use crate::split::{self, SplitBy};
use crate::table_export::{self, Format};
use crate::text::TextBuf;
use crate::timestamp;

pub const USAGE: &str = "\
bigtext-cli: BigText's tools for scripts (bigtext --COMMAND works too)

  filter [-v] [-i] [-w] [-E] [CONTEXT] PATTERN FILE [-o OUT]
        Lines with a match (-v: without one; -i: ignore case; -w: whole words;
        -E: regular expression). To OUT in the file's encoding, or to the
        console. Exit code 1 when no line matched.
        More patterns: -e PAT (each must match; with --any, one of them does),
        --not PAT (must not match); all can be repeated.
  levels ERROR,WARN,INFO,DEBUG [CONTEXT] FILE [-o OUT]
        Lines of these log levels.
        CONTEXT: -A N / -B N / -C N lines after / before / around each line,
        --entries the whole log entry (a stack trace under the line), -n line
        numbers (\"12:\" a match, \"13-\" context); \"--\" between groups;
        --from TIME / --to TIME only the lines between those times (\"14:30\",
        \"2024-05-01 14:30:00\"; --to includes its second).
  extract [-i] [-w] [-E] [-g N] [--count] PATTERN FILE [-o OUT]
        Only the matched texts (or capture group N), one per line; with
        --count, each different one with how often it matched, most first.
  count [-v] [-i] [-w] [-E] PATTERN FILE
        The number of lines with a match.
  split (--size 100MB | --lines 1000000) FILE [--out-dir DIR]
        [--gz|--zst|--xz|--bz2]
        Parts name.part001.ext, … cut at line breaks (compressed: .ext.gz,
        …); prints their paths. Sizes are binary: 100MB (or 100M, 100MiB) is
        100 × 1,048,576 bytes; KB, GB and TB likewise.
  stats [--fields] FILE...
        Size, lines, encoding, line breaks by kind, the longest line, NUL and
        non-UTF-8 bytes, and the first and last times;
        with --fields, the key paths of JSON records (JSON Lines or an array's
        items) with their types, counts, nulls, numbers and examples, as CSV.
  merge FILE FILE... [-o OUT]
        Log lines of all files in time order, each labelled with its file.
  gaps FILE [--min 30s]
        Places where the next timestamp is at least that much later (or
        earlier: the clock went back), with line numbers; --min in ms, s, m
        or min, h or d (not M, which could be a month). Exit code 1 when
        there are none.
  patterns FILE [--top N] [--rare] [-o OUT]
        The log's message templates (numbers, ids, IPs and paths replaced by
        <n>, <hex>, <ip>, <path>) with how many lines each has, as CSV, most
        lines first (--rare: fewest first).
  join LEFT RIGHT (--on COL | --left-on COL --right-on COL) [--inner] [-o OUT]
        Each row of the LEFT table with the other columns of the RIGHT table's
        rows with the same key (COL: a header name or a 1-based number), as
        CSV; rows without a match get empty fields, or are left out (--inner).
  jsonl FILE [-q QUERY] [-v] [--fields a,b.c] [--to jsonl|csv] [--count]
        [-o OUT]
  query FILE -q QUERY ... (the same)
        Lines that meet a field query: JSON Lines, logfmt (key=value), or a web
        server or syslog log by its columns (.status >= 500 and .method = POST).
        ==, !=, <, >, <=, >=, in (a, b), contains, ~ regex, exists, missing,
        joined with and, or, not and parentheses; a time value without a date
        compares with the time of day (.time >= 10:00). As they are, only some
        fields (--fields), or as CSV; --count prints how many.
  jsondiff A B
        Two JSON files compared by structure, whatever the key order and the
        formatting: path: old -> new, path: added, path: removed. Exit code 0
        when they are the same, 1 when they differ.
  diff A B [-w] [-i] [-t] [--mask RE] [-U N] [-q] [-o OUT]
        A unified diff (diff -u) with N lines of context (3), of files of any
        size; -w ignores white space, -i case, -t the timestamp at the start
        of each line, --mask what RE matches (ids, durations); -q only says
        whether they differ. Exit code 0 when they are the same, 1 when they
        differ.
  only-in A B [-w] [-i] [-t] [--mask RE] [--count] [-o OUT]
        The lines of A that occur nowhere in B, whatever their order, in A's
        order (files of any size); -w, -i, -t and --mask as for diff; --count
        prints how many. Exit code 0 when there are none, 1 when there are.
  diff-table A B (--on COL | --left-on COL --right-on COL) [--all] [-o OUT]
        Two tables compared by a key column (COL: a header name or a 1-based
        number; --right-on when B's differs) whatever their row order, as CSV:
        status (changed, removed, added; same with --all), the key, the
        changed columns, and A's columns with \"old → new\" where a value
        changed. Columns pair up by header name. Exit code 0 when they are the
        same, 1 when they differ.
  csv FILE cut COLS | drop COLS | sort --by COL [--desc] | where COND... |
           stats COL | group COL [--sum COL]
           [-o OUT] [--delimiter X] [--no-header]
        The table view's column tools, streamed: keep or delete columns, sort
        rows (files up to 1 GB), keep the rows where every condition holds
        (col=v, col!=v, col~v contains, col>n, col<n; or col eq|ne|has|gt|lt v,
        col empty, col nonempty — quote > and < for cmd.exe), a column's
        statistics, or rows per value. Columns are header names or 1-based
        numbers; --delimiter , ; | or tab.
  replace [-i] [-w] [-E] PATTERN REPLACEMENT FILE [-o OUT | --in-place [--bak]]
        Every match replaced by REPLACEMENT as written (with -E: $1, ${name},
        \\n and \\t in it), streamed, keeping the encoding and line breaks;
        --in-place swaps the file atomically (--bak keeps the old one).
        Exit code 1 when nothing matched.
  saved [--settings FILE]
        The searches saved in BigText (the search bar's star menu);
        filter, count and grep --saved NAME run one. Exit code 1 when there
        are none, 2 when FILE is not a BigText settings file.
  --json on filter, levels, grep, count, stats, replace (with -o or
  --in-place), saved and csv stats gives one JSON record per line ({file,
  line, offset, text, context}; errors as {\"error\": …}).
  -- ends the options: a pattern after it may start with a dash.

  grep [-i] [-w] [-E] PATTERN FILES... | -r DIR [--names '*.log;*.gz']
        Find in files without a window: file:line:text for every line with a
        match, over files, *.log patterns or a folder (compressed files are
        unpacked on the way).
  filter, count and levels take several FILES, patterns and -r DIR [--names]
  too (file: before each output line; count gives each file's count and a
  total), and --out-dir DIR for one name.filtered.ext per input.

  head [-n N] FILE [-o OUT]
  tail [-n N] FILE [-o OUT]
        The first or last N lines (10), read from that end only.
  slice FILE (--lines A-B | --bytes A-B | --from TIME [--to TIME])
        [--with-header] [-o OUT]
        Lines A to B (1-based, inclusive), the lines around bytes A to B, or
        the lines from one time to another (inclusive to the second; a --to
        without a date is on --from's day), found by binary search in a time-
        ordered log; --with-header puts line 1 first. Exit code 1 when nothing
        is in the range.
  sort [-r] [-n] [-i] [-u] FILE [-o OUT]
        The lines sorted (-r reversed, -n by the number at their start, -i
        ignoring case, -u each once), of a file of any size (temporary runs
        and a merge).
  uniq [-c] FILE [-o OUT]
        Each line once, sorted; with -c, count<TAB>line, most frequent first.
  transform --op upper|lower|trim|tabs|untabs FILE [-o OUT]
        The file in UPPERCASE or lowercase, with trailing white space trimmed,
        tabs as spaces or leading spaces as tabs (width 4), streamed.
  format FILE [--style pretty|minify] [-o OUT]
        JSON (or JSON Lines, a value per line) indented by two spaces (pretty,
        the default) or with all insignificant white space removed (minify);
        key order, numbers and escapes stay as written.
  derive FILE --name NAME --expr EXPR [-o OUT]
        The table with a new last column computed per row, like {price} * {qty},
        substr({ts}, 0, 10) or if({status} = \"ok\", 1, 0).
  pivot FILE --rows COL --cols COL [--value COL --agg sum|mean|min|max]
        [--by hour|day|month] [-o OUT]
        A pivot table as CSV: a row per value of --rows (or per hour, day or
        month of a time column), a column per value of --cols, row counts or
        the aggregated --value in the cells, and a total column.
  validate FILE [--as csv|json|jsonl] [--no-header] [--numeric 3,5]
        Checks a CSV / TSV table: rows with another field count, stray or
        unclosed quotes, control characters, and (--numeric) text in number
        columns (1-based). A JSON file is checked strictly as one value, a
        JSON Lines file line by line; --as gives the kind when the file does
        not look like it. Prints line: problem; exit code 1 when any.
  report FILE [--urls | --minutes | --slow] [--top N] [-o OUT]
        Reports of a web server log (nginx / Apache, AWS ALB or Classic ELB,
        IIS): requests by status, the top URLs, the minutes with the most 5xx
        errors and the slowest requests, as text (the first 10 of each, or
        N); or one of them in full as CSV: --urls (requests, 4xx, 5xx, bytes
        and times per URL), --minutes (requests, 4xx and 5xx per minute),
        --slow (the 1,000 slowest requests with their line numbers).
  redact FILE [-o OUT] [--ips] [--pattern RE]... [--no-tokens] [--no-urls]
          [--no-keys] [--no-emails]
        The file with secrets and personal data hidden, to share it: tokens,
        Authorization and Cookie headers, secrets in URLs, password= and
        \"secret\": values, e-mail addresses, with --ips IP addresses, with
        --pattern more (its first group, or the match). Each becomes a label
        like <email-3f9a2c>, the same for the same value in one run. What was
        hidden is counted on stderr. The rules find common secrets, not every
        one: look at the result before you share it.
  sqldump FILE [tables | extract TABLE[,TABLE...] | split] [-o OUT]
          [--out-dir DIR] [--no-settings]
        A SQL dump (mysqldump, pg_dump's plain format, SQLite's .dump), read in
        one pass: tables lists its tables with their rows and bytes as CSV;
        extract writes those tables (CREATE, rows, keys, indexes, triggers and
        for PostgreSQL their sequences) with the dump's opening and closing
        settings, so the file restores on its own (--no-settings: without
        them); split writes into --out-dir (the dump's folder) the files that
        restore the dump in the order of their names: NAME.0-before-tables.sql
        (functions, types), NAME.1-TABLE.sql per table, NAME.2-after-tables.sql
        (views, routines, foreign keys added after the data).
  values FIELD FILE [-o OUT]
        The values of a JSON Lines or logfmt (key=value) field with how many
        lines have each and their first and last time, as CSV, most frequent
        first. Nested JSON keys: user.id.
  convert FILE --to json|jsonl|md|xlsx|csv [--kind KIND] [--path $.a] [-o OUT]
        A CSV / TSV table as JSON, JSON Lines, Markdown or Excel (.xlsx needs
        -o); JSON Lines as CSV or one JSON array; a JSON array (or the one at
        --path, or the first under the top object) as JSON Lines; logfmt
        (key=value) lines, and nginx / Apache, AWS load balancer (ALB, Classic),
        IIS and syslog logs, as CSV with a column per field. --kind
        json|jsonl|logfmt|log|csv when the kind is not what it looks like.
        The header and lines before the table (sep=;, comments) are detected;
        --header / --no-header, --skip N and --quote ' override that (also
        for validate).

-o OUT ending in .gz, .zst, .xz or .bz2 is written compressed.

Exit codes: 0 done, 1 nothing found (for diff, only-in, jsondiff, diff-table
and validate: the files differ, or there are problems), 2 error.
";

const COMMANDS: [&str; 35] = [
    "filter",
    "levels",
    "count",
    "split",
    "stats",
    "merge",
    "convert",
    "report",
    "sqldump",
    "redact",
    "values",
    "gaps",
    "patterns",
    "extract",
    "validate",
    "join",
    "pivot",
    "derive",
    "jsonl",
    "query",
    "jsondiff",
    "diff",
    "only-in",
    "diff-table",
    "transform",
    "format",
    "sort",
    "uniq",
    "head",
    "tail",
    "slice",
    "grep",
    "replace",
    "saved",
    "csv",
];

/// Whether `arg` starts a command of the windowed program: `--filter`. A bare `filter` is a
/// file name there, so a file named like a command opens; `bigtext-cli` takes both forms.
pub fn is_command(arg: &str) -> bool {
    arg.strip_prefix("--")
        .is_some_and(|name| COMMANDS.contains(&name))
}

struct Fail(String);

impl From<io::Error> for Fail {
    fn from(e: io::Error) -> Fail {
        Fail(e.to_string())
    }
}

type Res<T> = Result<T, Fail>;

fn fail<T>(msg: impl Into<String>) -> Res<T> {
    Err(Fail(msg.into()))
}

/// The arguments of one command: flags, options with a value, and the rest.
struct Args {
    flags: Vec<String>,
    opts: Vec<(String, String)>,
    rest: Vec<String>,
}

impl Args {
    fn parse(args: &[String], flags: &[&str], opts: &[&str]) -> Res<Args> {
        let mut a = Args {
            flags: Vec::new(),
            opts: Vec::new(),
            rest: Vec::new(),
        };
        let mut it = args.iter();
        while let Some(x) = it.next() {
            if x == "--" {
                // Everything after `--` is a pattern or a file, even when it starts with `-`.
                a.rest.extend(it.cloned());
                break;
            } else if flags.contains(&x.as_str()) {
                a.flags.push(x.clone());
            } else if opts.contains(&x.as_str()) {
                let v = it
                    .next()
                    .ok_or_else(|| Fail(format!("{x} needs a value")))?;
                a.opts.push((x.clone(), v.clone()));
            } else if x.starts_with('-') && x.len() > 1 && x.parse::<f64>().is_err() {
                return fail(format!("unknown option {x}"));
            } else {
                a.rest.push(x.clone());
            }
        }
        Ok(a)
    }

    fn flag(&self, names: &[&str]) -> bool {
        self.flags.iter().any(|f| names.contains(&f.as_str()))
    }

    fn opt(&self, names: &[&str]) -> Option<&str> {
        self.opts
            .iter()
            .rev()
            .find(|(k, _)| names.contains(&k.as_str()))
            .map(|(_, v)| v.as_str())
    }

    /// Every value of a repeated option, in order.
    fn all(&self, names: &[&str]) -> Vec<&str> {
        self.opts
            .iter()
            .filter(|(k, _)| names.contains(&k.as_str()))
            .map(|(_, v)| v.as_str())
            .collect()
    }
}

thread_local! {
    /// `--json`: records rather than text.
    static JSON: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

fn json() -> bool {
    JSON.with(|j| j.get())
}

thread_local! {
    /// Unpacked copies of compressed inputs, removed when the command is done.
    static TEMPS: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
}

fn open(path: &Path) -> Res<(TextBuf, Detected)> {
    // A .gz / .zst / .xz / .bz2 input is unpacked first.
    let unpacked;
    let path = match crate::decompress::detect(path) {
        Some(kind) => {
            let t =
                crate::decompress::unpack(path, kind, &CancelToken::new(), &Progress::default())
                    .map_err(|e| Fail(format!("{}: {e}", display_path(path))))?
                    .ok_or_else(|| Fail("cancelled".into()))?;
            TEMPS.with(|v| v.borrow_mut().push(t.clone()));
            unpacked = t;
            unpacked.as_path()
        }
        None => path,
    };
    let src = Source::open(path, OpenMode::Auto)
        .map_err(|e| Fail(format!("{}: {e}", display_path(path))))?;
    let n = src.len().min(1 << 20);
    let det = encoding::detect(&src.read(0..n)?, n == src.len());
    let len = src.len();
    let mut buf = TextBuf::new(Arc::new(src), LineIndex::new(len), det.codec);
    buf.blocking = true;
    Ok((buf, det))
}

/// Writes through `w`, refusing to seek (for the console).
struct NoSeek<W>(W);

impl<W: Write> Write for NoSeek<W> {
    fn write(&mut self, b: &[u8]) -> io::Result<usize> {
        self.0.write(b)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl<W> Seek for NoSeek<W> {
    fn seek(&mut self, _: SeekFrom) -> io::Result<u64> {
        Err(io::Error::other("cannot seek"))
    }
}

/// Writes to `-o FILE` (via a temporary file, moved into place when done) or to `out`.
fn with_output(
    target: Option<&str>,
    out: &mut dyn Write,
    f: impl FnOnce(&mut dyn WriteSeek) -> Res<()>,
) -> Res<()> {
    match target {
        Some(t) => {
            let path = PathBuf::from(t);
            let temp = crate::save::temp_path_for(&path);
            let file = crate::save::create_temp(&temp, &path)
                .map_err(|e| Fail(format!("{}: {e}", display_path(&temp))))?;
            let r = (|| {
                // -o out.gz (.zst, .xz, .bz2) is compressed on the way.
                let mut w = crate::decompress::Packer::new(
                    io::BufWriter::with_capacity(8 << 20, &file),
                    crate::decompress::target_kind(&path),
                )?;
                f(&mut w)?;
                let mut w = w.finish()?;
                w.flush()?;
                drop(w);
                file.sync_all()?;
                Ok(())
            })();
            drop(file);
            match r {
                Ok(()) => crate::save::finalize(&temp, &path, false).map_err(Fail),
                Err(e) => {
                    let _ = std::fs::remove_file(&temp);
                    Err(e)
                }
            }
        }
        None => {
            let mut w = NoSeek(io::BufWriter::new(out));
            f(&mut w)?;
            w.flush()?;
            Ok(())
        }
    }
}

trait WriteSeek: Write + Seek {}
impl<T: Write + Seek> WriteSeek for T {}

fn query(a: &Args, pattern: &str) -> Query {
    Query {
        pattern: pattern.to_string(),
        regex: a.flag(&["-E", "--regex"]),
        case_sensitive: !a.flag(&["-i", "--ignore-case"]),
        whole_word: a.flag(&["-w", "--word"]),
        dot_all: false,
    }
}

/// Writes the kept lines: in the file's encoding to a file, as UTF-8 to the console. With
/// `numbers`, each line starts with its line number ("12:" a match, "13-" context, like grep).
#[allow(clippy::too_many_arguments)]
fn write_kept(
    buf: &TextBuf,
    file: &str,
    m: &Matcher,
    spec: FilterSpec,
    terms: &[filter::Term],
    numbers: bool,
    target: Option<&str>,
    out: &mut dyn Write,
) -> Res<u64> {
    let cancel = CancelToken::new();
    let mut kept = 0;
    let json = json();
    let numbers = numbers || json;
    with_output(target, out, |w| {
        let to_file = target.is_some() && !json;
        if to_file && !numbers {
            kept = filter::write_lines_to(buf, m, spec, terms, &mut &mut *w, &cancel, None)?
                .map(|n| n.lines)
                .unwrap_or(0);
            return Ok(());
        }
        let codec = buf.codec;
        let bom = codec.bom_len as u64;
        if to_file && bom > 0 {
            w.write_all(
                &buf.read(0..bom)
                    .ok_or_else(|| Fail("could not read the file".into()))?,
            )?;
        }
        let mut err: Option<io::Error> = None;
        let mut prev: Option<u64> = None;
        // Line breaks counted up to an offset: (offset, breaks before it).
        let mut counted = (0u64, 0u64);
        let end = filter::filter_lines_with(buf, m, spec, terms, &cancel, None, |ls, le, kind| {
            let r = (|| -> io::Result<()> {
                if let Some(pe) = prev.filter(|&pe| spec.has_context() && ls > pe && !json) {
                    if to_file {
                        w.write_all(&codec.encode("--"))?;
                        w.write_all(&filter::line_break_before(buf, pe))?;
                    } else {
                        writeln!(w, "--")?;
                    }
                }
                prev = Some(le);
                let mut prefix = String::new();
                if numbers {
                    let mut n = counted.1;
                    buf.for_each_chunk(counted.0..ls, |base, c| {
                        n += codec.count_nl(c, base);
                        true
                    })
                    .ok_or_else(|| io::Error::other("could not read the file"))?;
                    counted = (ls, n);
                    prefix = format!(
                        "{}{}",
                        n + 1,
                        if kind == filter::LineKind::Hit {
                            ':'
                        } else {
                            '-'
                        }
                    );
                }
                let bytes = buf
                    .read(ls.max(bom)..le)
                    .ok_or_else(|| io::Error::other("could not read the file"))?;
                if json {
                    let text = codec.decode_lossy(&bytes);
                    let line: u64 = prefix.trim_end_matches([':', '-']).parse().unwrap_or(0);
                    let rec = serde_json::json!({"file": file, "line": line, "offset": ls, "text": text.trim_end_matches(['\n', '\r']), "context": kind != filter::LineKind::Hit});
                    return writeln!(w, "{rec}");
                }
                if to_file {
                    w.write_all(&codec.encode(&prefix))?;
                    w.write_all(&bytes)
                } else {
                    let text = codec.decode_lossy(&bytes);
                    writeln!(w, "{prefix}{}", text.trim_end_matches(['\n', '\r']))
                }
            })();
            if let Err(e) = r {
                err = Some(e);
                return false;
            }
            kept += 1;
            true
        });
        match err {
            Some(e) => Err(e.into()),
            None if end == crate::search::SearchEnd::Unavailable => fail("could not read the file"),
            None => Ok(()),
        }
    })?;
    Ok(kept)
}

/// Flags of the context options (-A/-B/-C take a value).
const CONTEXT_FLAGS: [&str; 3] = ["--entries", "-n", "--line-numbers"];
const CONTEXT_OPTS: [&str; 8] = [
    "-A",
    "--after",
    "-B",
    "--before",
    "-C",
    "--context",
    "--from",
    "--to",
];

/// The filter with the context options.
fn spec_from(a: &Args, invert: bool) -> Res<FilterSpec> {
    let num = |names: &[&str]| -> Res<Option<u32>> {
        a.opt(names)
            .map(|v| {
                v.parse::<u32>()
                    .ok()
                    .filter(|&n| n <= filter::CONTEXT_MAX)
                    .ok_or_else(|| {
                        Fail(format!("not a line count (0-{}): {v}", filter::CONTEXT_MAX))
                    })
            })
            .transpose()
    };
    let around = num(&["-C", "--context"])?;
    let before = num(&["-B", "--before"])?.or(around).unwrap_or(0);
    let after = num(&["-A", "--after"])?.or(around).unwrap_or(0);
    Ok(FilterSpec {
        invert,
        column: None,
        before,
        after,
        entries: a.flag(&["--entries"]),
        range: None,
    })
}

/// The lines between `--from TIME` and `--to TIME` (up to and including that second).
fn time_range(a: &Args, buf: &TextBuf) -> Res<Option<(u64, u64)>> {
    let (from, to) = (a.opt(&["--from"]), a.opt(&["--to"]));
    if from.is_none() && to.is_none() {
        return Ok(None);
    }
    let parse = |t: Option<&str>| {
        t.map(|t| timestamp::parse(t).ok_or_else(|| Fail(format!("not a time: {t}"))))
            .transpose()
    };
    match timestamp::time_range(buf, parse(from)?, parse(to)?, &CancelToken::new()) {
        Ok(r) => Ok(Some(r)),
        Err(_) => fail("the file has no timestamps"),
    }
}

fn cmd_filter(args: &[String], out: &mut dyn Write, count_only: bool) -> Res<i32> {
    let flags = [
        &[
            "-v",
            "--invert",
            "-i",
            "--ignore-case",
            "-w",
            "--word",
            "-E",
            "--regex",
            "--any",
        ][..],
        &CONTEXT_FLAGS,
    ]
    .concat();
    let a = Args::parse(
        args,
        &flags,
        &[
            &["-o", "--output", "-e", "--pattern", "--not"][..],
            &CONTEXT_OPTS,
        ]
        .concat(),
    )?;
    if count_only && a.opt(&["-o", "--output"]).is_some() {
        return fail("count prints a number and writes no file; redirect it instead (> FILE)");
    }
    let mut pats: Vec<String> = a
        .all(&["-e", "--pattern"])
        .into_iter()
        .map(String::from)
        .collect();
    let file = match &a.rest[..] {
        [pattern, file] => {
            pats.insert(0, pattern.clone());
            file
        }
        [file] if !pats.is_empty() => file,
        _ => return fail("needs PATTERN (or -e PATTERN) and FILE"),
    };
    let (buf, _) = open(Path::new(file))?;
    // --any: one alternation of the patterns; otherwise every pattern must match.
    let any = a.flag(&["--any"]) && pats.len() > 1;
    let driver = if any {
        let regex = a.flag(&["-E", "--regex"]);
        let alt: Vec<String> = pats
            .iter()
            .map(|p| {
                format!(
                    "(?:{})",
                    if regex {
                        p.clone()
                    } else {
                        regex_syntax::escape(p)
                    }
                )
            })
            .collect();
        Query {
            pattern: alt.join("|"),
            regex: true,
            ..query(&a, "")
        }
    } else {
        query(&a, &pats[0])
    };
    let m = Matcher::new(&driver, buf.codec).map_err(Fail)?;
    let mut owned: Vec<(Matcher, bool)> = Vec::new();
    for p in if any { &[][..] } else { &pats[1..] } {
        owned.push((Matcher::new(&query(&a, p), buf.codec).map_err(Fail)?, false));
    }
    for p in a.all(&["--not"]) {
        owned.push((Matcher::new(&query(&a, p), buf.codec).map_err(Fail)?, true));
    }
    let terms: Vec<filter::Term> = owned
        .iter()
        .map(|(m, negated)| filter::Term {
            m,
            negated: *negated,
        })
        .collect();
    let mut spec = spec_from(&a, a.flag(&["-v", "--invert"]))?;
    spec.range = time_range(&a, &buf)?;
    let n = if count_only {
        let mut n = 0u64;
        filter::filter_lines_with(
            &buf,
            &m,
            FilterSpec {
                invert: spec.invert,
                range: spec.range,
                ..Default::default()
            },
            &terms,
            &CancelToken::new(),
            None,
            |_, _, _| {
                n += 1;
                true
            },
        );
        if json() {
            writeln!(out, "{}", serde_json::json!({"file": file, "count": n}))?;
        } else {
            writeln!(out, "{n}")?;
        }
        n
    } else {
        write_kept(
            &buf,
            file,
            &m,
            spec,
            &terms,
            a.flag(&["-n", "--line-numbers"]),
            a.opt(&["-o", "--output"]),
            out,
        )?
    };
    Ok(if n > 0 { 0 } else { 1 })
}

fn cmd_levels(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &CONTEXT_FLAGS,
        &[&["-o", "--output"][..], &CONTEXT_OPTS].concat(),
    )?;
    let [names, file] = &a.rest[..] else {
        return fail("needs LEVELS and FILE");
    };
    let mut levels = Levels::default();
    for n in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
        let l = Level::ALL.into_iter().find(|l| {
            l.name().eq_ignore_ascii_case(n)
                || (n.eq_ignore_ascii_case("warning") && *l == Level::Warn)
        });
        match l {
            Some(l) if !levels.contains(l) => levels = levels.toggled(l),
            Some(_) => {}
            None => return fail(format!("unknown level {n} (ERROR, WARN, INFO, DEBUG)")),
        }
    }
    let q = loglevel::query(levels).ok_or_else(|| Fail("no levels".into()))?;
    let (buf, _) = open(Path::new(file))?;
    let m = Matcher::new(&q, buf.codec).map_err(Fail)?;
    let spec = FilterSpec {
        range: time_range(&a, &buf)?,
        ..spec_from(&a, false)?
    };
    let n = write_kept(
        &buf,
        file,
        &m,
        spec,
        &[],
        a.flag(&["-n", "--line-numbers"]),
        a.opt(&["-o", "--output"]),
        out,
    )?;
    Ok(if n > 0 { 0 } else { 1 })
}

/// "100MB", "1.5G", "500k" or a number of bytes.
/// "100MB", "100M" or "100MiB" (all 100 × 1,048,576 bytes; KB, GB and TB likewise).
fn parse_size(s: &str) -> Option<u64> {
    let t = s.trim().to_ascii_lowercase();
    let t = t.trim_end_matches('b');
    let t = t.strip_suffix('i').unwrap_or(t);
    let (num, mul) = match t.chars().last()? {
        'k' => (&t[..t.len() - 1], 1u64 << 10),
        'm' => (&t[..t.len() - 1], 1 << 20),
        'g' => (&t[..t.len() - 1], 1 << 30),
        't' => (&t[..t.len() - 1], 1 << 40),
        _ => (t, 1),
    };
    let v: f64 = num.trim().parse().ok()?;
    (v > 0.0).then_some((v * mul as f64) as u64)
}

fn cmd_split(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--gz", "--zst", "--xz", "--bz2"],
        &["--size", "--lines", "--out-dir"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let by = match (a.opt(&["--size"]), a.opt(&["--lines"])) {
        (Some(s), None) => {
            SplitBy::Bytes(parse_size(s).ok_or_else(|| Fail(format!("not a size: {s}")))?)
        }
        (None, Some(n)) => SplitBy::Lines(
            n.parse()
                .ok()
                .filter(|&n| n > 0)
                .ok_or_else(|| Fail(format!("not a line count: {n}")))?,
        ),
        _ => return fail("give --size or --lines"),
    };
    let path = Path::new(file);
    let dir = a
        .opt(&["--out-dir"])
        .map(PathBuf::from)
        .or_else(|| path.parent().map(Path::to_path_buf))
        .unwrap_or_default();
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "part".into());
    let (buf, _) = open(path)?;
    let pack = crate::decompress::Kind::ALL
        .into_iter()
        .find(|k| a.flag(&[&format!("--{}", k.extension())]));
    // A .csv or .tsv file (or --csv) is cut between records; --lines then counts records.
    let lower = file.to_ascii_lowercase();
    let csv = if a.flag(&["--csv"]) || lower.ends_with(".csv") || lower.ends_with(".tsv") {
        Some(split::CsvSplit {
            dialect: table_of(&buf, file, &a)?.dialect,
            repeat_header: a.flag(&["--repeat-header"]),
        })
    } else {
        None
    };
    let parts = split::split_to_files(
        &buf,
        by,
        &dir,
        &name,
        pack,
        csv,
        &CancelToken::new(),
        &Progress::default(),
    )?
    .unwrap_or_default();
    for p in &parts {
        writeln!(out, "{}", display_path(p))?;
    }
    // No parts (an empty file): 1, like the commands that find nothing.
    Ok(if parts.is_empty() { 1 } else { 0 })
}

fn cmd_stats(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &["--fields"], &[])?;
    if a.rest.is_empty() {
        return fail("needs FILE");
    }
    if a.flag(&["--fields"]) {
        for file in &a.rest {
            let (buf, _) = open(Path::new(file))?;
            let f = crate::json_fields::field_stats(&buf, &CancelToken::new(), None)
                .map_err(Fail)?
                .unwrap_or_default();
            crate::json_fields::fields_to_csv(&f, &mut &mut *out)?;
        }
        return Ok(0);
    }
    for file in &a.rest {
        let path = Path::new(file);
        let (buf, det) = open(path)?;
        let codec = buf.codec;
        let Some(st) = crate::stats::scan(&buf.snapshot(), &CancelToken::new(), None, |_| {})
        else {
            return fail(format!("{}: could not read the file", display_path(path)));
        };
        if json() {
            let span = crate::stats::time_span(&buf).map(|(f, l)| {
                let key = |s: timestamp::Stamp| timestamp::format_key(s.ms, s.has_date, true);
                (key(f), key(l))
            });
            let rec = serde_json::json!({
                "file": display_path(path), "bytes": buf.len(), "lines": st.lines, "encoding": codec.enc.name(),
                "lf": st.lf, "crlf": st.crlf, "cr": st.cr, "final_line_break": st.final_break,
                "longest_line": {"bytes": st.longest.0, "line": st.longest.1 + 1}, "nul": st.nul, "not_utf8": st.invalid_utf8,
                "first_time": span.as_ref().map(|s| s.0.clone()), "last_time": span.map(|s| s.1),
            });
            writeln!(out, "{rec}")?;
            continue;
        }
        writeln!(out, "file: {}", display_path(path))?;
        writeln!(
            out,
            "size: {} ({} bytes)",
            human_bytes(buf.len()),
            buf.len()
        )?;
        writeln!(out, "lines: {}", st.lines)?;
        writeln!(out, "encoding: {}", codec.enc.name())?;
        writeln!(
            out,
            "line endings: {} (LF {}, CRLF {}, CR {})",
            det.line_ending.name(),
            st.lf,
            st.crlf,
            st.cr
        )?;
        writeln!(
            out,
            "final line break: {}",
            if st.final_break { "yes" } else { "no" }
        )?;
        writeln!(
            out,
            "longest line: {} bytes (line {})",
            st.longest.0,
            st.longest.1 + 1
        )?;
        if st.nul > 0 {
            writeln!(
                out,
                "NUL bytes: {} (first at byte {})",
                st.nul,
                st.first_nul.unwrap_or(0)
            )?;
        }
        if st.invalid_utf8 > 0 {
            writeln!(
                out,
                "bytes that are not UTF-8: {} (first at byte {})",
                st.invalid_utf8,
                st.first_invalid.unwrap_or(0)
            )?;
        }
        if let Some((f, l)) = crate::stats::time_span(&buf) {
            let key = |s: timestamp::Stamp| timestamp::format_key(s.ms, s.has_date, true);
            writeln!(out, "first time: {}", key(f))?;
            writeln!(out, "last time: {}", key(l))?;
            if f.has_date && l.has_date {
                writeln!(
                    out,
                    "span: {}",
                    timestamp::format_delta(l.ms - f.ms).trim_start_matches('+')
                )?;
            }
        }
        if a.rest.len() > 1 {
            writeln!(out)?;
        }
    }
    Ok(0)
}

fn cmd_merge(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &[], &["-o", "--output"])?;
    if a.rest.len() < 2 {
        return fail("needs two or more files");
    }
    let mut inputs = Vec::new();
    let mut names: Vec<String> = Vec::new();
    for f in &a.rest {
        let p = Path::new(f);
        let mut label = p
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| f.clone());
        let base = label.clone();
        let mut k = 1;
        while names.contains(&label) {
            k += 1;
            label = format!("{base} ({k})");
        }
        names.push(label.clone());
        inputs.push(Input {
            buf: open(p)?.0,
            label,
        });
    }
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        merge::merge_to(&inputs, &mut &mut *w, &CancelToken::new(), None)?;
        Ok(())
    })?;
    Ok(0)
}

/// What a file holds, from its first lines: json, jsonl, logfmt or csv.
fn sniff_kind(buf: &TextBuf) -> &'static str {
    // An array from its first byte: it may be one line of any length, not read as lines.
    if crate::json::top_array(buf, &CancelToken::new()).is_some() {
        return "json";
    }
    let mut r = LineReader::new(buf);
    let mut lines = Vec::new();
    while lines.len() < 10 {
        let Ok(Some((_, l))) = r.next() else { break };
        let t = l.trim_ascii();
        if !t.is_empty() {
            lines.push(t.to_vec());
        }
    }
    match lines.first().and_then(|l| l.first()) {
        Some(b'[') => "json",
        Some(b'{')
            if lines.len() > 1
                && lines
                    .iter()
                    .all(|l| l.first() == Some(&b'{') && l.last() == Some(&b'}')) =>
        {
            "jsonl"
        }
        Some(b'{') => "json",
        _ if crate::logformat::Format::guess(&lines).is_some() => "log",
        _ if lines
            .iter()
            .filter(|l| {
                crate::fields::line_fields(&String::from_utf8_lossy(l))
                    .is_some_and(|f| f.0 == crate::fields::Syntax::Logfmt)
            })
            .count()
            * 2
            > lines.len() =>
        {
            "logfmt"
        }
        _ => "csv",
    }
}

fn cmd_convert(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--no-header", "--header"],
        &[
            "--to", "--kind", "--from", "--path", "-o", "--output", "--skip", "--quote",
        ],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let to = a
        .opt(&["--to"])
        .ok_or_else(|| Fail("give --to json, jsonl, md, xlsx or csv".into()))?
        .to_ascii_lowercase();
    let target = a.opt(&["-o", "--output"]);
    let (buf, _) = open(Path::new(file))?;
    let cancel = CancelToken::new();
    // `--from` is the name before 0.15, kept until 2.0.
    let from = match a.opt(&["--kind", "--from"]) {
        Some(f) => f.to_ascii_lowercase(),
        None => sniff_kind(&buf).to_string(),
    };
    match (from.as_str(), to.as_str()) {
        ("json", "jsonl") => {
            let at = match a.opt(&["--path"]) {
                Some(p) => crate::json::resolve(&buf, &crate::json::parse_path(p).map_err(Fail)?, &cancel).map_err(Fail)?.0,
                None => crate::json::find_array(&buf, &cancel).map_err(Fail)?.0,
            };
            with_output(target, out, |w| {
                crate::json::array_to_lines(&buf, at, &mut &mut *w, &cancel, None).map_err(Fail)?;
                Ok(())
            })?;
            return Ok(0);
        }
        ("jsonl", "json") => {
            with_output(target, out, |w| {
                crate::json::lines_to_array(&buf, &mut &mut *w, &cancel, None)?;
                Ok(())
            })?;
            return Ok(0);
        }
        ("jsonl", "csv") | ("json", "csv") => {
            // A JSON array's items (the top-level array's, or those of the one at --path),
            // read value by value: the array may be on one line, or an item on several.
            let array = match a.opt(&["--path"]) {
                _ if from != "json" => None,
                Some(p) => Some(
                    crate::json::resolve(&buf, &crate::json::parse_path(p).map_err(Fail)?, &cancel)
                        .map_err(Fail)?
                        .0,
                ),
                None => crate::json::top_array(&buf, &cancel),
            };
            with_output(target, out, |w| {
                match array {
                    Some(at) => crate::json::array_to_csv(&buf, at, &mut &mut *w, &cancel, None)?,
                    // One object (per line) as a table, too.
                    None => crate::json::jsonl_to_csv(&buf, &mut &mut *w, &cancel, None)?,
                };
                Ok(())
            })?;
            return Ok(0);
        }
        ("log", "csv") => {
            let f = crate::logformat::detect(&buf)?.ok_or_else(|| Fail(format!("{file}: not an nginx / Apache, AWS load balancer, IIS or syslog log")))?;
            with_output(target, out, |w| {
                crate::logformat::to_csv(&buf, &f, &mut &mut *w, &cancel, None)?;
                Ok(())
            })?;
            return Ok(0);
        }
        ("logfmt", "csv") => {
            with_output(target, out, |w| {
                crate::fields::logfmt_to_csv(&buf, &mut &mut *w, &cancel, None)?;
                Ok(())
            })?;
            return Ok(0);
        }
        ("csv", _) => {}
        (f, t) => return fail(format!("cannot convert {f} to {t} (json → jsonl, jsonl → json or csv, logfmt or log → csv, csv → json, jsonl, md, xlsx)")),
    }
    let format = Format::ALL
        .into_iter()
        .find(|f| f.ext() == to || (to == "markdown" && *f == Format::Markdown))
        .ok_or_else(|| Fail(format!("unknown format {to}")))?;
    if format == Format::Xlsx && target.is_none() {
        return fail("an .xlsx workbook needs -o FILE");
    }
    let g = table_of(&buf, file, &a)?;
    let spec = table_export::Spec {
        dialect: g.dialect,
        cols: None,
        header: g.header,
        format,
    };
    with_output(target, out, |w| {
        table_export::export(&buf, spec, w, &CancelToken::new(), None)?;
        Ok(())
    })?;
    Ok(0)
}

fn cmd_report(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--urls", "--minutes", "--slow"],
        &["--top", "-o", "--output"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let top = a
        .opt(&["--top"])
        .map(|n| {
            n.parse::<usize>()
                .map_err(|_| Fail(format!("not a number: {n}")))
        })
        .transpose()?;
    let (buf, _) = open(Path::new(file))?;
    let f = crate::logformat::detect(&buf)?
        .filter(|f| f.has_requests())
        .ok_or_else(|| {
            Fail(format!(
                "{file}: not a web server log (nginx / Apache, AWS ALB or Classic ELB, IIS)"
            ))
        })?;
    let r =
        crate::logformat::report(&buf, &f, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        let w = &mut &mut *w;
        if a.flag(&["--urls"]) {
            crate::logformat::urls_csv(&r, w, top)?;
        } else if a.flag(&["--minutes"]) {
            crate::logformat::minutes_csv(&r, w)?;
        } else if a.flag(&["--slow"]) {
            crate::logformat::slow_csv(&r, w, top)?;
        } else {
            crate::logformat::write_summary(&r, &f, w, top.unwrap_or(10))?;
        }
        Ok(())
    })?;
    Ok(if r.requests > 0 { 0 } else { 1 })
}

fn cmd_redact(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &[
            "--ips",
            "--no-tokens",
            "--no-urls",
            "--no-keys",
            "--no-emails",
        ],
        &["-o", "--output", "--pattern"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let opts = crate::redact::Options {
        tokens: !a.flag(&["--no-tokens"]),
        urls: !a.flag(&["--no-urls"]),
        keys: !a.flag(&["--no-keys"]),
        emails: !a.flag(&["--no-emails"]),
        ips: a.flag(&["--ips"]),
        custom: a
            .all(&["--pattern"])
            .into_iter()
            .map(String::from)
            .collect(),
    };
    let mut r = crate::redact::Redactor::new(&opts, crate::redact::random_salt()).map_err(Fail)?;
    let (buf, _) = open(Path::new(file))?;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        crate::redact::redact_to(&buf, 0..buf.len(), &mut r, w, &CancelToken::new(), None)?;
        Ok(())
    })?;
    let hidden: Vec<String> = crate::redact::KINDS
        .iter()
        .zip(r.counts())
        .filter(|(_, n)| *n > 0)
        .map(|(k, n)| format!("{k} {n}"))
        .collect();
    eprintln!(
        "hidden: {}",
        if hidden.is_empty() {
            "nothing".to_string()
        } else {
            hidden.join(", ")
        }
    );
    Ok(0)
}

fn cmd_sqldump(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &["--no-settings"], &["-o", "--output", "--out-dir"])?;
    let (file, action, names) = match &a.rest[..] {
        [f] => (f, "tables", None),
        [f, act] => (f, act.as_str(), None),
        [f, act, n] => (f, act.as_str(), Some(n.as_str())),
        _ => return fail("needs FILE [tables | extract TABLE | split]"),
    };
    let (buf, _) = open(Path::new(file))?;
    let cancel = CancelToken::new();
    let dump = crate::sqldump::scan(&buf, &cancel, None, |_| {})?.unwrap_or_default();
    let settings = !a.flag(&["--no-settings"]);
    match (action, names) {
        ("tables", None) => {
            with_output(a.opt(&["-o", "--output"]), out, |w| {
                Ok(crate::sqldump::tables_csv(&dump, &mut &mut *w)?)
            })?;
            Ok(if dump.tables.is_empty() { 1 } else { 0 })
        }
        ("extract", Some(names)) => {
            let mut which = Vec::new();
            for n in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
                match dump.find(n) {
                    Some(i) => which.push(i),
                    None => {
                        return fail(format!(
                            "no table {n} in {file} (bigtext-cli sqldump {file} tables lists them)"
                        ))
                    }
                }
            }
            with_output(a.opt(&["-o", "--output"]), out, |w| {
                crate::sqldump::write_tables(
                    &buf,
                    &dump,
                    &which,
                    if settings {
                        crate::sqldump::Extract::WHOLE
                    } else {
                        crate::sqldump::Extract::BARE
                    },
                    &mut &mut *w,
                    &cancel,
                    None,
                )?;
                Ok(())
            })?;
            Ok(0)
        }
        ("split", None) => {
            let path = Path::new(file);
            let dir = a
                .opt(&["--out-dir"])
                .map(PathBuf::from)
                .or_else(|| path.parent().map(Path::to_path_buf))
                .unwrap_or_default();
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            let stem = name
                .trim_end_matches(".gz")
                .trim_end_matches(".zst")
                .trim_end_matches(".xz")
                .trim_end_matches(".bz2")
                .trim_end_matches(".sql")
                .to_string();
            std::fs::create_dir_all(&dir)?;
            let files = crate::sqldump::split(&buf, &dump, &dir, &stem, settings, &cancel, None)?
                .unwrap_or_default();
            for (p, n) in &files {
                writeln!(out, "{}\t{}", p.display(), human_bytes(*n))?;
            }
            Ok(if files.is_empty() { 1 } else { 0 })
        }
        _ => fail("needs tables, extract TABLE[,TABLE...] or split"),
    }
}

fn cmd_values(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &[], &["-o", "--output"])?;
    let [key, file] = &a.rest[..] else {
        return fail("needs FIELD and FILE");
    };
    let (buf, _) = open(Path::new(file))?;
    // JSON Lines when the first non-empty line is an object, otherwise logfmt.
    let mut r = LineReader::new(&buf);
    let mut syntax = crate::fields::Syntax::Logfmt;
    while let Some((_, l)) = r.next()? {
        match l.trim_ascii().first() {
            None => continue,
            Some(b'{') => syntax = crate::fields::Syntax::Json,
            Some(_) => {}
        }
        break;
    }
    let c = crate::fields::value_counts(&buf, key, syntax, &CancelToken::new(), None)?
        .unwrap_or_default();
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        Ok(crate::fields::counts_to_csv(&c, key, &mut &mut *w)?)
    })?;
    Ok(if c.lines > 0 { 0 } else { 1 })
}

/// The dialect of a table file (by its name and content).
/// The table in `file`: its delimiter, the lines before it and whether it has a header, with
/// `--skip N`, `--quote '` and `--header` / `--no-header` overriding what was detected.
fn table_of(buf: &TextBuf, file: &str, a: &Args) -> Res<csv::TableGuess> {
    let bom = buf.codec.bom_len as u64;
    let sample = buf
        .read(bom..buf.len().min(bom + 64 * 1024))
        .ok_or_else(|| Fail("could not read the file".into()))?;
    let preferred = if file.to_ascii_lowercase().ends_with(".tsv") {
        b'\t'
    } else {
        b','
    };
    let mut g = csv::detect_table(
        &buf.codec,
        &sample,
        bom + sample.len() as u64 == buf.len(),
        preferred,
        bom,
    );
    if let Some(n) = a.opt(&["--skip"]) {
        let n: usize = n
            .parse()
            .map_err(|_| Fail(format!("not a line count: {n}")))?;
        let mut at = bom;
        for _ in 0..n {
            at = crate::filter::line_end_at(buf, at).unwrap_or(buf.len());
        }
        g.skip = n;
        g.dialect.start = if n == 0 { 0 } else { at };
    }
    match a.opt(&["--quote"]) {
        Some(q) if q.len() == 1 => g.dialect.quote = q.as_bytes()[0],
        Some(q) => return fail(format!("the quote is one character, not {q}")),
        None => {}
    }
    if a.flag(&["--no-header"]) {
        g.header = false;
    } else if a.flag(&["--header"]) {
        g.header = true;
    }
    Ok(g)
}

/// A column given as a header name or a 1-based number.
fn column_index(buf: &TextBuf, g: &csv::TableGuess, col: &str) -> Res<usize> {
    if let Ok(n) = col.parse::<usize>() {
        return if n > 0 {
            Ok(n - 1)
        } else {
            fail("columns count from 1")
        };
    }
    let mut names = Vec::new();
    csv::for_each_record(buf, g.dialect, &CancelToken::new(), None, |r| {
        names = r
            .fields
            .iter()
            .filter_map(|f| {
                buf.read(f.clone())
                    .map(|b| csv::field_value(&buf.codec, g.dialect, &b))
            })
            .collect();
        false
    });
    names
        .iter()
        .position(|n| n.trim() == col.trim())
        .ok_or_else(|| Fail(format!("no column named {col}")))
}

fn cmd_join(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--inner", "--no-header", "--header"],
        &[
            "--on",
            "--left-on",
            "--right-on",
            "-o",
            "--output",
            "--skip",
            "--quote",
        ],
    )?;
    let [lf, rf] = &a.rest[..] else {
        return fail("needs LEFT and RIGHT");
    };
    let (left, _) = open(Path::new(lf))?;
    let (right, _) = open(Path::new(rf))?;
    let (lg, rg) = (table_of(&left, lf, &a)?, table_of(&right, rf, &a)?);
    let (lc, rc) = match (
        a.opt(&["--on"]),
        a.opt(&["--left-on"]),
        a.opt(&["--right-on"]),
    ) {
        (Some(c), None, None) => (c, c),
        (None, Some(l), Some(r)) => (l, r),
        _ => return fail("give --on COL, or --left-on COL and --right-on COL"),
    };
    let spec = crate::csv_join::JoinSpec {
        left_key: column_index(&left, &lg, lc)?,
        right_key: column_index(&right, &rg, rc)?,
        inner: a.flag(&["--inner"]),
        header: lg.header && rg.header,
    };
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        crate::csv_join::join_to(
            (&left, lg.dialect),
            (&right, rg.dialect),
            spec,
            &mut &mut *w,
            &CancelToken::new(),
            None,
        )?;
        Ok(())
    })?;
    Ok(0)
}

/// One condition of `csv … where`: `col=v` (or `col eq v`, `col empty` in words).
fn parse_conds(tokens: &[String], col: &dyn Fn(&str) -> Res<usize>) -> Res<Vec<csv::Cond>> {
    use csv::CondOp;
    let mut out = Vec::new();
    let mut i = 0;
    while i < tokens.len() {
        let t = &tokens[i];
        let sym = [
            ("!=", CondOp::NotEquals),
            ("!~", CondOp::NotContains),
            ("=", CondOp::Equals),
            ("~", CondOp::Contains),
            (">", CondOp::Greater),
            ("<", CondOp::Less),
        ];
        if let Some((at, len, op)) = sym
            .iter()
            .filter_map(|(s, op)| t.find(s).map(|at| (at, s.len(), *op)))
            .min_by_key(|x| x.0)
        {
            out.push(csv::Cond {
                col: col(&t[..at])?,
                op,
                value: t[at + len..].to_string(),
            });
            i += 1;
            continue;
        }
        let word = tokens
            .get(i + 1)
            .map(|w| w.to_ascii_lowercase())
            .unwrap_or_default();
        let (op, takes) = match word.as_str() {
            "eq" => (CondOp::Equals, true),
            "ne" => (CondOp::NotEquals, true),
            "has" => (CondOp::Contains, true),
            "gt" => (CondOp::Greater, true),
            "lt" => (CondOp::Less, true),
            "empty" => (CondOp::Empty, false),
            "nonempty" => (CondOp::NotEmpty, false),
            _ => {
                return fail(format!(
                    "not a condition: {t} (col=v, col>n, col~v, or col eq v)"
                ))
            }
        };
        let value = if takes {
            tokens
                .get(i + 2)
                .cloned()
                .ok_or_else(|| Fail(format!("{t} {word} needs a value")))?
        } else {
            String::new()
        };
        out.push(csv::Cond {
            col: col(t)?,
            op,
            value,
        });
        i += if takes { 3 } else { 2 };
    }
    if out.is_empty() {
        return fail("where needs a condition");
    }
    Ok(out)
}

fn cmd_csv(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--no-header", "--header", "--desc"],
        &[
            "-o",
            "--output",
            "--skip",
            "--quote",
            "--delimiter",
            "--by",
            "--sum",
        ],
    )?;
    let (file, op, rest) = match &a.rest[..] {
        [file, op, rest @ ..] => (file, op.as_str(), rest),
        _ => return fail("needs FILE and an operation (cut, drop, sort, where, stats, group)"),
    };
    let (buf, _) = open(Path::new(file))?;
    let mut g = table_of(&buf, file, &a)?;
    if let Some(d) = a.opt(&["--delimiter"]) {
        g.dialect.delim = match d {
            "tab" | "\\t" | "\t" => b'\t',
            d if d.len() == 1 => d.as_bytes()[0],
            d => return fail(format!("the delimiter is one character or tab, not {d}")),
        };
    }
    let d = g.dialect;
    let col = |t: &str| -> Res<usize> {
        column_index(&buf, &g, t).map_err(|Fail(e)| {
            let mut names = Vec::new();
            csv::for_each_record(&buf, d, &CancelToken::new(), None, |r| {
                names = r
                    .fields
                    .iter()
                    .filter_map(|f| {
                        buf.read(f.clone())
                            .map(|b| csv::field_value(&buf.codec, d, &b))
                    })
                    .collect();
                false
            });
            Fail(format!("{e}; the columns are {}", names.join(", ")))
        })
    };
    let cols = |list: &str| {
        list.split(',')
            .map(|c| col(c.trim()))
            .collect::<Res<Vec<usize>>>()
    };
    let to = a.opt(&["-o", "--output"]);
    let cancel = CancelToken::new();
    let one = |what: &str| {
        rest.first()
            .cloned()
            .ok_or_else(|| Fail(format!("{op} needs {what}")))
    };
    match op {
        "cut" | "drop" => {
            let mut c = cols(&one("COLUMNS")?)?;
            with_output(to, out, |w| {
                if op == "cut" {
                    csv::rewrite_to(
                        &buf,
                        d,
                        &csv::Rewrite::Select(c.clone()),
                        &mut &mut *w,
                        &cancel,
                        None,
                    )?;
                } else {
                    c.sort_unstable();
                    c.dedup();
                    csv::delete_columns_to(&buf, d, &c, &mut &mut *w, &cancel, None)?;
                }
                Ok(())
            })?;
            Ok(0)
        }
        "sort" => {
            let by = match a.opt(&["--by"]) {
                Some(b) => b.to_string(),
                None => one("--by COLUMN")?,
            };
            if buf.len() > csv::SORT_MAX {
                return fail(format!(
                    "sorting works on files up to {}; this one is {}",
                    human_bytes(csv::SORT_MAX),
                    human_bytes(buf.len())
                ));
            }
            let rw = csv::Rewrite::Sort {
                col: col(&by)?,
                desc: a.flag(&["--desc"]),
                header: g.header,
            };
            with_output(to, out, |w| {
                csv::rewrite_to(&buf, d, &rw, &mut &mut *w, &cancel, None)?;
                Ok(())
            })?;
            Ok(0)
        }
        "where" => {
            let conds = parse_conds(rest, &col)?;
            let mut kept = 0;
            with_output(to, out, |w| {
                kept = csv::filter_rows_to(&buf, d, &conds, g.header, &mut &mut *w, &cancel, None)?
                    .map(|x| x.0)
                    .unwrap_or(0);
                Ok(())
            })?;
            Ok(if kept > 0 { 0 } else { 1 })
        }
        "stats" => {
            let c = col(&one("a COLUMN")?)?;
            let st = csv::column_stats(&buf, d, c, g.header, &cancel, None)
                .map_err(|_| Fail("could not read the file".into()))?;
            if json() {
                let top: Vec<serde_json::Value> = st
                    .top
                    .iter()
                    .map(|(v, n)| serde_json::json!({"value": v, "count": n}))
                    .collect();
                writeln!(
                    out,
                    "{}",
                    serde_json::json!({"column": st.name, "rows": st.rows, "empty": st.empty, "numbers": st.numeric, "sum": st.sum, "min": st.min, "max": st.max, "mean": st.mean(), "distinct": st.distinct, "top": top})
                )?;
                return Ok(0);
            }
            writeln!(out, "column: {}", st.name)?;
            writeln!(out, "rows: {}", st.rows)?;
            writeln!(out, "empty: {}", st.empty)?;
            if st.numeric > 0 {
                writeln!(out, "numbers: {}", st.numeric)?;
                writeln!(out, "sum: {}", st.sum)?;
                if let (Some(lo), Some(hi)) = (st.min, st.max) {
                    writeln!(out, "min: {lo}\nmax: {hi}")?;
                }
                if let Some(m) = st.mean() {
                    writeln!(out, "mean: {m}")?;
                }
            }
            writeln!(
                out,
                "distinct: {}{}",
                st.distinct,
                if st.distinct_capped { "+" } else { "" }
            )?;
            for (v, n) in st.top.iter().take(10) {
                writeln!(out, "  {n}\t{v}")?;
            }
            Ok(0)
        }
        "group" => {
            let key = col(&one("a COLUMN")?)?;
            let sum = a.opt(&["--sum"]).map(col).transpose()?;
            let gr = csv::group_by(&buf, d, key, sum, g.header, &cancel, None)
                .map_err(|_| Fail("could not read the file".into()))?;
            with_output(to, out, |w| {
                csv::groups_to_csv(&gr, &mut &mut *w)?;
                Ok(())
            })?;
            Ok(0)
        }
        _ => fail(format!(
            "unknown csv operation {op} (cut, drop, sort, where, stats, group)"
        )),
    }
}

/// The settings file `--settings FILE` names, or the app's.
fn settings_path(a: &Args) -> Res<PathBuf> {
    match a.opt(&["--settings"]) {
        Some(p) => Ok(PathBuf::from(p)),
        None => crate::settings_file::state_file()
            .ok_or_else(|| Fail("no settings file (give --settings FILE)".into())),
    }
}

/// `--saved NAME [--settings FILE]` replaced by the saved search's pattern and switches.
fn with_saved(rest: &[String]) -> Res<Vec<String>> {
    let Some(i) = rest.iter().position(|a| a == "--saved") else {
        return Ok(rest.to_vec());
    };
    let name = rest
        .get(i + 1)
        .ok_or_else(|| Fail("--saved needs a NAME".into()))?
        .clone();
    let mut others: Vec<String> = Vec::new();
    let mut settings = None;
    let mut it = rest.iter().enumerate();
    while let Some((k, x)) = it.next() {
        if k == i || k == i + 1 {
            continue;
        }
        if x == "--settings" {
            settings = it.next().map(|(_, v)| v.clone());
            continue;
        }
        others.push(x.clone());
    }
    let path = match settings {
        Some(p) => PathBuf::from(p),
        None => crate::settings_file::state_file()
            .ok_or_else(|| Fail("no settings file (give --settings FILE)".into()))?,
    };
    let all = crate::settings_file::saved_searches(&path)
        .map_err(|e| Fail(format!("{}: {e}", display_path(&path))))?;
    let s = all
        .iter()
        .find(|s| s.name == name)
        .ok_or_else(|| Fail(format!("no saved search named “{name}”")))?;
    let mut out = Vec::new();
    if s.query.regex {
        out.push("-E".into());
    }
    if !s.query.case_sensitive {
        out.push("-i".into());
    }
    if s.query.whole_word {
        out.push("-w".into());
    }
    if s.invert {
        out.push("-v".into());
    }
    out.push("-e".into());
    out.push(s.query.pattern.clone());
    out.extend(others);
    Ok(out)
}

fn cmd_saved(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &[], &["--settings"])?;
    let path = settings_path(&a)?;
    let all = crate::settings_file::saved_searches(&path)
        .map_err(|e| Fail(format!("{}: {e}", display_path(&path))))?;
    for s in &all {
        let flags = crate::settings_file::query_flags(&s.query);
        if json() {
            writeln!(
                out,
                "{}",
                serde_json::json!({"name": s.name, "pattern": s.query.pattern, "regex": s.query.regex, "case_sensitive": s.query.case_sensitive, "whole_word": s.query.whole_word, "invert": s.invert})
            )?;
        } else {
            writeln!(
                out,
                "{}\t{}{}{}",
                s.name,
                s.query.pattern,
                if flags.is_empty() {
                    String::new()
                } else {
                    format!("  ({flags})")
                },
                if s.invert { "  (lines without)" } else { "" }
            )?;
        }
    }
    Ok(if all.is_empty() { 1 } else { 0 })
}

fn cmd_replace(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &[
            "-i",
            "--ignore-case",
            "-w",
            "--word",
            "-E",
            "--regex",
            "--in-place",
            "--bak",
        ],
        &["-o", "--output"],
    )?;
    let [pattern, replacement, file] = &a.rest[..] else {
        return fail("needs PATTERN, REPLACEMENT and FILE");
    };
    let path = Path::new(file);
    if a.flag(&["--in-place"]) && crate::decompress::detect(path).is_some() {
        return fail("--in-place does not work on a compressed file; give -o OUT");
    }
    if json() && !a.flag(&["--in-place"]) && a.opt(&["-o", "--output"]).is_none() {
        return fail(
            "--json needs -o OUT or --in-place: the replaced text would mix with the record",
        );
    }
    let (buf, _) = open(path)?;
    let q = query(&a, pattern);
    let m = Matcher::new(&q, buf.codec).map_err(Fail)?;
    let tpl = if q.regex {
        crate::replace::Template::new(replacement, true)
    } else {
        crate::replace::Template::verbatim(replacement)
    };
    let cancel = CancelToken::new();
    let count = if a.flag(&["--in-place"]) {
        let t = crate::save::Transform::Replace {
            matcher: &m,
            template: &tpl,
            range: 0..buf.len(),
        };
        let (temp, stats) =
            match crate::save::write_temp(&buf, path, t, &cancel, &Progress::default()) {
                Ok(x) => x,
                Err(crate::save::SaveError::Io(e)) => return fail(e),
                Err(crate::save::SaveError::Cancelled) => return fail("cancelled"),
            };
        // The file is still mapped until the buffer goes.
        drop(buf);
        if stats.count == 0 {
            let _ = std::fs::remove_file(&temp);
        } else {
            crate::save::finalize(&temp, path, a.flag(&["--bak"])).map_err(Fail)?;
        }
        stats.count
    } else {
        let mut n = 0;
        with_output(a.opt(&["-o", "--output"]), out, |w| {
            n = crate::replace::replace_all_to(
                &buf,
                &m,
                &tpl,
                0..buf.len(),
                &mut &mut *w,
                &cancel,
                None,
            )?
            .map(|s| s.count)
            .unwrap_or(0);
            Ok(())
        })?;
        n
    };
    if json() {
        writeln!(
            out,
            "{}",
            serde_json::json!({"file": file, "replaced": count})
        )?;
    } else if a.flag(&["--in-place"]) {
        writeln!(out, "{count} replaced")?;
    }
    Ok(if count > 0 { 0 } else { 1 })
}

/// Writes `range` of `buf` (with line 1 first when `header` and the range starts later): as it
/// is to a file, decoded to UTF-8 on the console.
fn write_slice(
    buf: &TextBuf,
    range: std::ops::Range<u64>,
    header: bool,
    to: Option<&str>,
    out: &mut dyn Write,
) -> Res<i32> {
    let codec = buf.codec;
    let bom = codec.bom_len as u64;
    let header = if header && range.start > bom {
        crate::filter::line_end_at(buf, bom).map(|e| bom..e)
    } else {
        None
    };
    let raw = to.is_some() || codec.enc == crate::encoding::Encoding::Utf8;
    with_output(to, out, |w| {
        if to.is_some() && bom > 0 {
            w.write_all(
                &buf.read(0..bom)
                    .ok_or_else(|| Fail("could not read the file".into()))?,
            )?;
        }
        let mut copy = |r: std::ops::Range<u64>| -> Res<()> {
            let r = r.start.max(bom)..r.end;
            let mut err = None;
            buf.for_each_chunk(r, |_, b| {
                let res = if raw {
                    w.write_all(b)
                } else {
                    w.write_all(codec.decode_lossy(b).as_bytes())
                };
                match res {
                    Ok(()) => true,
                    Err(e) => {
                        err = Some(e);
                        false
                    }
                }
            })
            .ok_or_else(|| Fail("could not read the file".into()))?;
            match err {
                Some(e) => Err(e.into()),
                None => Ok(()),
            }
        };
        if let Some(h) = header {
            copy(h)?;
        }
        copy(range.clone())
    })?;
    Ok((range.start >= range.end) as i32)
}

fn cmd_head_tail(args: &[String], out: &mut dyn Write, head: bool) -> Res<i32> {
    let a = Args::parse(args, &[], &["-n", "--lines", "-o", "--output"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let n: u64 = match a.opt(&["-n", "--lines"]) {
        Some(v) => v
            .parse()
            .map_err(|_| Fail(format!("-n needs a number of lines, not {v}")))?,
        None => 10,
    };
    let (buf, _) = open(Path::new(file))?;
    let buf = buf.snapshot();
    let range = if head {
        match split::line_range(&buf, 1, n.max(1), &CancelToken::new(), None) {
            Some(r) if n > 0 => r,
            _ => 0..0,
        }
    } else {
        crate::lines::last_lines_start(&buf, n)
            .ok_or_else(|| Fail("could not read the file".into()))?..buf.len()
    };
    write_slice(&buf, range, false, a.opt(&["-o", "--output"]), out)
}

fn cmd_slice(args: &[String], out: &mut dyn Write) -> Res<i32> {
    // `--header` is the name before 0.15 (the table commands' --header says a table has one),
    // kept until 2.0.
    let a = Args::parse(
        args,
        &["--with-header", "--header"],
        &["--lines", "--bytes", "--from", "--to", "-o", "--output"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let (buf, _) = open(Path::new(file))?;
    let buf = buf.snapshot();
    let pair = |v: &str, what: &str| -> Res<(u64, u64)> {
        let (x, y) = v
            .split_once('-')
            .ok_or_else(|| Fail(format!("{what} needs A-B")))?;
        let num = |s: &str| {
            s.trim()
                .replace('_', "")
                .parse::<u64>()
                .map_err(|_| Fail(format!("{what}: “{s}” is not a number")))
        };
        let (x, y) = (num(x)?, num(y)?);
        if x > y {
            return fail(format!("{what}: {x} is after {y}"));
        }
        Ok((x, y))
    };
    let cancel = CancelToken::new();
    let range = match (
        a.opt(&["--lines"]),
        a.opt(&["--bytes"]),
        a.opt(&["--from"]),
        a.opt(&["--to"]),
    ) {
        (Some(v), None, None, None) => {
            let (x, y) = pair(v, "--lines")?;
            split::line_range(&buf, x.max(1), y.max(1), &cancel, None).unwrap_or(0..0)
        }
        (None, Some(v), None, None) => {
            // Out to whole lines.
            let (x, y) = pair(v, "--bytes")?;
            let (x, y) = (x.min(buf.len()), y.min(buf.len()));
            let s = crate::filter::line_start_at(&buf, x).unwrap_or(x);
            let e = crate::filter::line_end_at(&buf, y.saturating_sub(1).max(x)).unwrap_or(y);
            s..e.max(s)
        }
        (None, None, from, to) if from.is_some() || to.is_some() => {
            let parse =
                |t: &str| timestamp::parse(t).ok_or_else(|| Fail(format!("not a time: {t}")));
            let from = from.map(parse).transpose()?;
            let to = to
                .map(parse)
                .transpose()?
                .map(|t| from.map(|f| timestamp::rebase(t, f)).unwrap_or(t));
            match timestamp::time_range(&buf, from, to, &cancel) {
                Ok((s, e)) => s..e,
                Err(timestamp::TimeError::NoTimestamps) => {
                    return fail("the file has no timestamps")
                }
                Err(e) => return fail(format!("{e:?}")),
            }
        }
        _ => return fail("give one of --lines A-B, --bytes A-B, or --from (and --to)"),
    };
    write_slice(
        &buf,
        range,
        a.flag(&["--with-header", "--header"]),
        a.opt(&["-o", "--output"]),
        out,
    )
}

fn cmd_sort(args: &[String], out: &mut dyn Write, uniq: bool) -> Res<i32> {
    use crate::extsort::{SortMode, SortSpec};
    let a = Args::parse(args, &["-r", "-n", "-i", "-u", "-c"], &["-o", "--output"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let mode = match (uniq, a.flag(&["-c"]), a.flag(&["-u"])) {
        (true, true, _) => SortMode::Count,
        (true, false, _) | (false, _, true) => SortMode::Unique,
        _ => SortMode::Sort,
    };
    let spec = SortSpec {
        reverse: a.flag(&["-r"]),
        numeric: a.flag(&["-n"]),
        ignore_case: a.flag(&["-i"]),
        mode,
        counts_csv: false,
    };
    let (buf, det) = open(Path::new(file))?;
    let snap = buf.snapshot();
    let eol = snap
        .codec
        .encode(if det.line_ending == crate::encoding::LineEnding::CrLf {
            "\r\n"
        } else {
            "\n"
        });
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        crate::extsort::sort_to(&snap, spec, &eol, w, &CancelToken::new(), None)?;
        Ok(())
    })?;
    Ok(0)
}

/// Streams the whole file through a text operation.
fn text_op(file: &str, op: crate::textops::Op, to: Option<&str>, out: &mut dyn Write) -> Res<i32> {
    let (buf, _) = open(Path::new(file))?;
    let snap = buf.snapshot();
    with_output(to, out, |w| {
        crate::textops::text_op_to(
            &snap,
            0..snap.len(),
            op,
            crate::text::rows::TAB_WIDTH,
            w,
            &CancelToken::new(),
            None,
        )
        .map_err(|e| Fail(e.to_string()))?;
        Ok(())
    })?;
    Ok(0)
}

fn cmd_transform(args: &[String], out: &mut dyn Write) -> Res<i32> {
    use crate::textops::Op;
    let a = Args::parse(args, &[], &["--op", "-o", "--output"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let op = match a.opt(&["--op"]) {
        Some("upper") => Op::Upper,
        Some("lower") => Op::Lower,
        Some("trim") => Op::TrimTrailing,
        Some("tabs") => Op::TabsToSpaces,
        Some("untabs") => Op::SpacesToTabs,
        Some(o) => {
            return fail(format!(
                "unknown --op {o} (upper, lower, trim, tabs, untabs)"
            ))
        }
        None => return fail("give --op upper|lower|trim|tabs|untabs"),
    };
    text_op(file, op, a.opt(&["-o", "--output"]), out)
}

fn cmd_format(args: &[String], out: &mut dyn Write) -> Res<i32> {
    use crate::textops::Op;
    // `--json pretty|minify` is the name before 0.15, kept until 2.0 (`--json` is otherwise
    // the output format of the commands that write records).
    let a = Args::parse(args, &[], &["--style", "--json", "-o", "--output"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let op = match a.opt(&["--style", "--json"]) {
        Some("pretty") | None => Op::JsonPretty,
        Some("minify") => Op::JsonMinify,
        Some(o) => return fail(format!("unknown --style {o} (pretty, minify)")),
    };
    text_op(file, op, a.opt(&["-o", "--output"]), out)
}

fn cmd_diff_table(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--all", "--no-header", "--header"],
        &[
            "--on",
            "--left-on",
            "--right-on",
            "--key",
            "--key-b",
            "-o",
            "--output",
            "--skip",
            "--quote",
        ],
    )?;
    let [fa, fb] = &a.rest[..] else {
        return fail("needs A and B");
    };
    // The key columns are named as for join; `--key` and `--key-b` are the names before 0.15,
    // kept until 2.0.
    let Some(ka) = a.opt(&["--on", "--left-on", "--key"]) else {
        return fail("give --on COL (a header name or a 1-based number)");
    };
    let kb = a.opt(&["--right-on", "--key-b"]).unwrap_or(ka);
    let (ta, _) = open(Path::new(fa))?;
    let (tb, _) = open(Path::new(fb))?;
    let (ga, gb) = (table_of(&ta, fa, &a)?, table_of(&tb, fb, &a)?);
    let spec = crate::csv_diff::KeyedSpec {
        key_a: column_index(&ta, &ga, ka)?,
        key_b: column_index(&tb, &gb, kb)?,
        header: ga.header && gb.header,
        all: a.flag(&["--all"]),
    };
    let mut stats = None;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        stats = crate::csv_diff::keyed_diff_to(
            (&ta, ga.dialect),
            (&tb, gb.dialect),
            spec,
            w,
            &CancelToken::new(),
            None,
        )?;
        Ok(())
    })?;
    Ok(stats.is_some_and(|s| s.changed + s.added + s.removed > 0) as i32)
}

fn cmd_jsonl(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["-v", "--invert", "--count"],
        &["-q", "--query", "--fields", "--to", "-o", "--output"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let q = a
        .opt(&["-q", "--query"])
        .map(crate::jsonq::FieldQuery::parse)
        .transpose()
        .map_err(Fail)?;
    let invert = a.flag(&["-v", "--invert"]);
    let fields: Vec<String> = a
        .opt(&["--fields"])
        .map(|f| {
            f.split(',')
                .map(|s| s.trim().trim_start_matches('.').to_string())
                .filter(|s| !s.is_empty())
                .collect()
        })
        .unwrap_or_default();
    let csv_out = match a.opt(&["--to"]).map(str::to_ascii_lowercase).as_deref() {
        None | Some("jsonl") => false,
        Some("csv") if !fields.is_empty() => true,
        Some("csv") => return fail("--to csv needs --fields"),
        Some(t) => return fail(format!("unknown --to {t} (jsonl, csv)")),
    };
    let (buf, _) = open(Path::new(file))?;
    if buf.codec.unit() != 1 {
        return fail("JSON Lines must be UTF-8");
    }
    // A web server or syslog log is queried by its columns; JSON Lines and logfmt by their keys.
    let head = buf
        .read(0..buf.len().min(4096))
        .map(|b| b.to_vec())
        .unwrap_or_default();
    let format = if head.trim_ascii_start().starts_with(b"{") {
        None
    } else {
        crate::logformat::detect(&buf)?
    };
    // A field's value: a web server or syslog log's column, a JSON key, or a logfmt key.
    let value_of = |line: &[u8], f: &str| -> Option<String> {
        if let Some(fmt) = &format {
            let mut s = crate::logformat::Splitter::new(fmt);
            if s.split(line) != crate::logformat::Split::Row {
                return None;
            }
            let i = fmt.columns.iter().position(|c| c.eq_ignore_ascii_case(f))?;
            let values = s.values(line);
            let v = values.get(i).filter(|v| !v.is_empty())?;
            Some(String::from_utf8_lossy(v).into_owned())
        } else if line.trim_ascii_start().starts_with(b"{") {
            crate::fields::find_value(line, f, crate::fields::Syntax::Json)
        } else {
            crate::fields::find_value(line, f, crate::fields::Syntax::Logfmt)
        }
    };
    let q = q.map(|q| q.for_document(format.clone(), false));
    let quote = |s: &str| {
        if s.contains([',', '"', '\n', '\r']) {
            format!("\"{}\"", s.replace('"', "\"\""))
        } else {
            s.to_string()
        }
    };
    let mut n = 0u64;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        if csv_out {
            writeln!(
                w,
                "{}",
                fields
                    .iter()
                    .map(|f| quote(f))
                    .collect::<Vec<_>>()
                    .join(",")
            )?;
        }
        let mut r = LineReader::new(&buf);
        while let Some((_, line)) = r.next()? {
            let keep = q.as_ref().is_none_or(|q| q.matches(line)) != invert;
            if !keep || (line.trim_ascii().is_empty() && q.is_none()) {
                continue;
            }
            n += 1;
            if a.flag(&["--count"]) {
                continue;
            }
            if fields.is_empty() {
                w.write_all(line.strip_suffix(b"\r").unwrap_or(line))?;
                w.write_all(b"\n")?;
            } else if csv_out {
                let row: Vec<String> = fields
                    .iter()
                    .map(|f| quote(&value_of(line, f).unwrap_or_default()))
                    .collect();
                writeln!(w, "{}", row.join(","))?;
            } else {
                let parts: Vec<String> = fields
                    .iter()
                    .map(|f| {
                        format!(
                            "{}:{}",
                            serde_json::Value::from(f.as_str()),
                            if line.trim_ascii_start().starts_with(b"{") {
                                crate::fields::find_raw_json(line, f)
                                    .map(|v| String::from_utf8_lossy(v).into_owned())
                            } else {
                                // Text of a log column or a logfmt key, as a JSON string.
                                value_of(line, f).map(|v| serde_json::Value::from(v).to_string())
                            }
                            .unwrap_or_else(|| "null".into())
                        )
                    })
                    .collect();
                writeln!(w, "{{{}}}", parts.join(","))?;
            }
        }
        if a.flag(&["--count"]) {
            writeln!(w, "{n}")?;
        }
        Ok(())
    })?;
    Ok(if n > 0 { 0 } else { 1 })
}

fn cmd_jsondiff(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &[], &[])?;
    let [fa, fb] = &a.rest[..] else {
        return fail("needs A and B");
    };
    let (ba, _) = open(Path::new(fa))?;
    let (bb, _) = open(Path::new(fb))?;
    let cancel = CancelToken::new();
    let pa = crate::json_diff::flatten_to_temp(&ba, "a.flat", &cancel, None)
        .map_err(Fail)?
        .ok_or_else(|| Fail("cancelled".into()))?;
    let pb = match crate::json_diff::flatten_to_temp(&bb, "b.flat", &cancel, None) {
        Ok(Some(p)) => p,
        r => {
            crate::decompress::remove_temp(&pa);
            return Err(Fail(r.err().unwrap_or_else(|| "cancelled".into())));
        }
    };
    let mut err = None;
    let r = crate::json_diff::changes(&pa, &pb, &cancel, None, |ch| {
        let line = match (&ch.old, &ch.new) {
            (Some(o), Some(n)) => format!("{}: {o} -> {n}", ch.path),
            (None, Some(n)) => format!("{}: added {n}", ch.path),
            (Some(o), None) => format!("{}: removed {o}", ch.path),
            (None, None) => return true,
        };
        if let Err(e) = writeln!(out, "{line}") {
            err = Some(e);
            return false;
        }
        true
    });
    crate::decompress::remove_temp(&pa);
    crate::decompress::remove_temp(&pb);
    if let Some(e) = err {
        return Err(e.into());
    }
    Ok(if r.map_err(Fail)?.unwrap_or(false) {
        1
    } else {
        0
    })
}

/// What -w, -b, -i, -t and --mask ignore.
fn diff_options(a: &Args) -> Res<crate::diff::DiffOptions> {
    let mask = match a.opt(&["--mask"]) {
        Some(m) => {
            Some(regex_automata::meta::Regex::new(m).map_err(|e| Fail(format!("--mask: {e}")))?)
        }
        None => None,
    };
    Ok(crate::diff::DiffOptions {
        whitespace: a.flag(&["-w", "-b"]),
        case: a.flag(&["-i"]),
        timestamps: a.flag(&["-t"]),
        mask,
    })
}

fn cmd_only_in(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["-w", "-b", "-i", "-t", "--count"],
        &["--mask", "-o", "--output"],
    )?;
    let [fa, fb] = &a.rest[..] else {
        return fail("needs A and B");
    };
    let opts = diff_options(&a)?;
    let (ba, _) = open(Path::new(fa))?;
    let (bb, _) = open(Path::new(fb))?;
    let (ba, bb) = (ba.snapshot(), bb.snapshot());
    let cancel = CancelToken::new();
    let budget = crate::setdiff::BUDGET;
    if a.flag(&["--count"]) {
        let c = crate::setdiff::only_in(&ba, &bb, &opts, budget, &cancel, None, |_| true)?
            .ok_or_else(|| Fail("cancelled".into()))?;
        writeln!(out, "{}", c.only)?;
        return Ok((c.only > 0) as i32);
    }
    let mut only = 0u64;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        let mut err = None;
        let c = crate::setdiff::only_in(&ba, &bb, &opts, budget, &cancel, None, |off| {
            match crate::setdiff::write_line_at(&ba, off, w) {
                Ok(()) => true,
                Err(e) => {
                    err = Some(e);
                    false
                }
            }
        })?;
        if let Some(e) = err {
            return Err(e.into());
        }
        only = c.map(|c| c.only).unwrap_or(0);
        Ok(())
    })?;
    Ok((only > 0) as i32)
}

fn cmd_diff(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["-w", "-b", "-i", "-t", "-q", "-u"],
        &["--mask", "-U", "--context", "-o", "--output"],
    )?;
    let [fa, fb] = &a.rest[..] else {
        return fail("needs A and B");
    };
    let opts = diff_options(&a)?;
    let context = match a.opt(&["-U", "--context"]) {
        Some(n) => n
            .parse::<u64>()
            .map_err(|_| Fail(format!("-U needs a number of lines, not {n}")))?,
        None => 3,
    };
    let (ba, _) = open(Path::new(fa))?;
    let (bb, _) = open(Path::new(fb))?;
    if a.flag(&["-q"]) {
        let mut differ = false;
        let end = crate::diff::diff_with(
            &*ba.source,
            &*bb.source,
            &opts,
            &CancelToken::new(),
            None,
            |_| {
                differ = true;
                false
            },
        );
        if matches!(
            end,
            crate::diff::DiffEnd::Failed | crate::diff::DiffEnd::Cancelled
        ) {
            return fail("could not read the files");
        }
        if differ {
            writeln!(out, "Files {fa} and {fb} differ")?;
        }
        return Ok(differ as i32);
    }
    let u = crate::unified::Unified {
        a: &*ba.source,
        b: &*bb.source,
        a_name: fa,
        b_name: fb,
        opts: &opts,
        context,
    };
    let mut differ = false;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        differ = crate::unified::write_unified(&u, w, &CancelToken::new(), None)?.unwrap_or(false);
        Ok(())
    })?;
    Ok(differ as i32)
}

fn cmd_derive(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &["--no-header", "--header"],
        &["--name", "--expr", "-o", "--output", "--skip", "--quote"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let (name, expr) = match (a.opt(&["--name"]), a.opt(&["--expr"])) {
        (Some(n), Some(e)) => (n.to_string(), e.to_string()),
        _ => return fail("give --name NAME and --expr EXPR"),
    };
    let (buf, _) = open(Path::new(file))?;
    let g = table_of(&buf, file, &a)?;
    let mut names = Vec::new();
    if g.header {
        csv::for_each_record(&buf, g.dialect, &CancelToken::new(), None, |r| {
            names = r
                .fields
                .iter()
                .filter_map(|f| {
                    buf.read(f.clone())
                        .map(|b| csv::field_value(&buf.codec, g.dialect, &b))
                })
                .collect();
            false
        });
    }
    crate::csv_expr::Expr::compile(&expr, &names).map_err(Fail)?;
    let rw = csv::Rewrite::Derive {
        name,
        expr,
        names,
        header: g.header,
    };
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        csv::rewrite_to(
            &buf,
            g.dialect,
            &rw,
            &mut &mut *w,
            &CancelToken::new(),
            None,
        )?;
        Ok(())
    })?;
    Ok(0)
}

fn cmd_pivot(args: &[String], out: &mut dyn Write) -> Res<i32> {
    use crate::csv_pivot::{Agg, Bucket, PivotSpec};
    let a = Args::parse(
        args,
        &["--no-header", "--header"],
        &[
            "--rows", "--cols", "--value", "--agg", "--by", "-o", "--output", "--skip", "--quote",
        ],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let (buf, _) = open(Path::new(file))?;
    let g = table_of(&buf, file, &a)?;
    let col = |name: &str| -> Res<usize> {
        let c = a
            .opt(&[name])
            .ok_or_else(|| Fail(format!("give {name} COL")))?;
        column_index(&buf, &g, c)
    };
    let value = a
        .opt(&["--value"])
        .map(|c| column_index(&buf, &g, c))
        .transpose()?;
    let agg = match a.opt(&["--agg"]) {
        None if value.is_some() => Agg::Sum,
        None => Agg::Count,
        Some(n) => Agg::ALL
            .into_iter()
            .find(|x| x.name() == n.to_ascii_lowercase())
            .ok_or_else(|| Fail(format!("unknown --agg {n} (count, sum, mean, min, max)")))?,
    };
    if agg != Agg::Count && value.is_none() {
        return fail("--agg needs --value COL");
    }
    let bucket = match a.opt(&["--by"]).map(str::to_ascii_lowercase).as_deref() {
        None => Bucket::AsIs,
        Some("hour") => Bucket::Hour,
        Some("day") => Bucket::Day,
        Some("month") => Bucket::Month,
        Some(b) => return fail(format!("unknown --by {b} (hour, day, month)")),
    };
    let spec = PivotSpec {
        rows: col("--rows")?,
        cols: col("--cols")?,
        value,
        agg,
        bucket,
        header: g.header,
    };
    let p = crate::csv_pivot::pivot(&buf, g.dialect, spec, &CancelToken::new(), None)
        .map_err(|_| Fail("could not read the file".into()))?;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        Ok(crate::csv_pivot::pivot_to_csv(&p, agg, &mut &mut *w)?)
    })?;
    Ok(0)
}

fn cmd_validate(args: &[String], out: &mut dyn Write) -> Res<i32> {
    // `--json` and `--lines` are the names before 0.15 (`--as json`, `--as jsonl`), kept until
    // 2.0.
    let a = Args::parse(
        args,
        &["--no-header", "--header", "--json", "--lines"],
        &["--as", "--numeric", "--skip", "--quote"],
    )?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    // JSON: as one document, or as JSON Lines.
    let (jbuf, _) = open(Path::new(file))?;
    let kind = match a.opt(&["--as"]).map(str::to_ascii_lowercase).as_deref() {
        Some("json") => "json",
        Some("jsonl") => "jsonl",
        Some("csv") => "csv",
        Some(o) => return fail(format!("unknown --as {o} (json, jsonl, csv)")),
        None if a.flag(&["--lines"]) => "jsonl",
        None if a.flag(&["--json"]) => "json",
        None => sniff_kind(&jbuf),
    };
    if kind == "json" || kind == "jsonl" {
        let cancel = CancelToken::new();
        let c = if kind == "jsonl" {
            crate::json_check::check_lines(&jbuf, &cancel, None, |_| {})?
        } else {
            crate::json_check::check_document(&jbuf, &cancel, None)
        }
        .unwrap_or_default();
        let (mut at, mut line) = (0u64, 0u64);
        for p in &c.problems {
            jbuf.for_each_chunk(at..p.at, |base, ch| {
                line += jbuf.codec.count_nl(ch, base);
                true
            })
            .ok_or_else(|| Fail("could not read the file".into()))?;
            at = p.at;
            writeln!(out, "{}: byte {}: {}", line + 1, p.at, p.message)?;
        }
        return Ok(if c.problems.is_empty() { 0 } else { 1 });
    }
    let mut numeric = Vec::new();
    for n in a
        .opt(&["--numeric"])
        .unwrap_or("")
        .split(',')
        .map(str::trim)
        .filter(|n| !n.is_empty())
    {
        match n.parse::<usize>() {
            Ok(n) if n > 0 => numeric.push(n - 1),
            _ => return fail(format!("not a column number: {n}")),
        }
    }
    let (buf, _) = open(Path::new(file))?;
    let g = table_of(&buf, file, &a)?;
    let c = crate::csv_check::check(
        &buf,
        g.dialect,
        g.header,
        &numeric,
        &CancelToken::new(),
        None,
        |_| {},
    )?
    .unwrap_or_default();
    let (mut at, mut line) = (0u64, 0u64);
    for p in &c.problems {
        buf.for_each_chunk(at..p.start, |base, ch| {
            line += buf.codec.count_nl(ch, base);
            true
        })
        .ok_or_else(|| Fail("could not read the file".into()))?;
        at = p.start;
        let what = match p.kind {
            crate::csv_check::Kind::Fields { got, want } => {
                format!("{got} fields instead of {want}")
            }
            crate::csv_check::Kind::StrayQuote { col } => {
                format!("column {}: a stray quote", col + 1)
            }
            crate::csv_check::Kind::Unclosed { col } => {
                format!("column {}: a quote that is never closed", col + 1)
            }
            crate::csv_check::Kind::Control { col } => {
                format!("column {}: a control character", col + 1)
            }
            crate::csv_check::Kind::NotNumber { col } => {
                format!("column {}: not a number", col + 1)
            }
            crate::csv_check::Kind::Huge => "longer than 64 KB, not checked".to_string(),
        };
        writeln!(out, "{}: {what}", line + 1)?;
    }
    Ok(if c.problems.is_empty() { 0 } else { 1 })
}

fn cmd_extract(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(
        args,
        &[
            "-i",
            "--ignore-case",
            "-w",
            "--word",
            "-E",
            "--regex",
            "--count",
        ],
        &["-g", "--group", "-o", "--output"],
    )?;
    let [pattern, file] = &a.rest[..] else {
        return fail("needs PATTERN and FILE");
    };
    let group = a
        .opt(&["-g", "--group"])
        .map(|g| {
            g.parse::<usize>()
                .map_err(|_| Fail(format!("not a group number: {g}")))
        })
        .transpose()?
        .unwrap_or(0);
    let (buf, _) = open(Path::new(file))?;
    let m = Matcher::new(&query(&a, pattern), buf.codec).map_err(Fail)?;
    if group > crate::search::group_names(&m).len() {
        return fail(format!("the pattern has no group {group}"));
    }
    let cancel = CancelToken::new();
    let mut n = 0;
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        if a.flag(&["--count"]) {
            let t = crate::extract::count(&buf, &m, group, 0..buf.len(), &cancel, None)?
                .unwrap_or_default();
            for (v, c) in &t.values {
                writeln!(w, "{c}\t{v}")?;
            }
            n = t.matches;
        } else {
            n = crate::extract::write_values_to(
                &buf,
                &m,
                group,
                0..buf.len(),
                &mut &mut *w,
                &cancel,
                None,
            )?
            .unwrap_or(0);
        }
        Ok(())
    })?;
    Ok(if n > 0 { 0 } else { 1 })
}

fn cmd_patterns(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &["--rare"], &["--top", "-o", "--output"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let top = a
        .opt(&["--top"])
        .map(|n| {
            n.parse::<usize>()
                .map_err(|_| Fail(format!("not a number: {n}")))
        })
        .transpose()?;
    let (buf, _) = open(Path::new(file))?;
    let mut p =
        crate::patterns::build(&buf, None, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
    crate::patterns::sort(&mut p.templates, a.flag(&["--rare"]));
    if let Some(n) = top {
        p.templates.truncate(n);
    }
    with_output(a.opt(&["-o", "--output"]), out, |w| {
        Ok(crate::patterns::to_csv(&p.templates, &mut &mut *w)?)
    })?;
    Ok(0)
}

fn cmd_gaps(args: &[String], out: &mut dyn Write) -> Res<i32> {
    let a = Args::parse(args, &[], &["--min"])?;
    let [file] = &a.rest[..] else {
        return fail("needs FILE");
    };
    let min = a.opt(&["--min"]).unwrap_or("30s");
    let min_ms = crate::gaps::parse_duration(min)
        .ok_or_else(|| Fail(format!("not a duration: {min} (30s, 5m or 5min, 1h)")))?;
    let (buf, _) = open(Path::new(file))?;
    let g = crate::gaps::scan(&buf, min_ms, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
    // Line numbers, counted forward from gap to gap.
    let (mut at, mut line) = (0u64, 0u64);
    let mut line_of = |off: u64| -> Res<u64> {
        buf.for_each_chunk(at..off, |base, c| {
            line += buf.codec.count_nl(c, base);
            true
        })
        .ok_or_else(|| Fail("could not read the file".into()))?;
        at = off;
        Ok(line + 1)
    };
    for x in &g.gaps {
        let (a1, a2) = (line_of(x.before)?, line_of(x.after)?);
        // The times as the file writes them, as values and log → CSV give them.
        let time = |at, k| {
            timestamp::stamp_text_at(&buf, at)
                .unwrap_or_else(|| timestamp::format_key(k, g.dated, true))
        };
        writeln!(
            out,
            "{a1}-{a2}: {} ({} -> {})",
            timestamp::format_delta(x.ms()),
            time(x.before, x.from),
            time(x.after, x.to)
        )?;
    }
    Ok(if g.gaps.is_empty() { 1 } else { 0 })
}

/// Runs a command; returns the exit code. `args` start with the command name.
pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
    let code = run_command(args, out, err);
    // The inputs are closed by now: their unpacked copies can go.
    for t in TEMPS.with(|v| std::mem::take(&mut *v.borrow_mut())) {
        crate::decompress::remove_temp(&t);
    }
    code
}

/// The files of `positionals` (with `*` and `?` in names expanded, as Windows shells do not)
/// and of `-r DIR` limited to `--names`.
fn expand_inputs(
    positionals: &[String],
    dir: Option<&str>,
    names: Option<&str>,
) -> Res<Vec<String>> {
    let cancel = CancelToken::new();
    let mut out = Vec::new();
    for p in positionals {
        let path = Path::new(p);
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        if name.contains(['*', '?']) && !path.exists() {
            let parent = path
                .parent()
                .filter(|d| !d.as_os_str().is_empty())
                .unwrap_or(Path::new("."));
            let mut found =
                crate::find_files::list_files(parent, std::slice::from_ref(&name), false, &cancel)
                    .map_err(|e| Fail(format!("{p}: {e}")))?;
            if found.is_empty() {
                return fail(format!("no files match {p}"));
            }
            found.sort();
            out.extend(found.into_iter().map(|f| f.to_string_lossy().into_owned()));
        } else {
            out.push(p.clone());
        }
    }
    if let Some(d) = dir {
        let pats = names.map(crate::find_files::patterns).unwrap_or_default();
        let mut found = crate::find_files::list_files(Path::new(d), &pats, true, &cancel)
            .map_err(|e| Fail(format!("{d}: {e}")))?;
        found.sort();
        out.extend(found.into_iter().map(|f| f.to_string_lossy().into_owned()));
    }
    Ok(out)
}

/// `filter`, `count`, `levels` and `grep` over several files (or a folder): each file's
/// output with its name in front (`file:12:line` for grep, `file: N` and a total for count),
/// or one output per file in `--out-dir`. The exit code is 2 if a file failed, else 0 if any
/// matched, else 1. `None` when it is a plain single-file run.
fn run_batch(cmd: &str, rest: &[String], out: &mut dyn Write, err: &mut dyn Write) -> Option<i32> {
    let filter_flags = [
        &[
            "-v",
            "--invert",
            "-i",
            "--ignore-case",
            "-w",
            "--word",
            "-E",
            "--regex",
            "--any",
        ][..],
        &CONTEXT_FLAGS,
    ]
    .concat();
    let (flags, opts): (Vec<&str>, Vec<&str>) = match cmd {
        "filter" | "count" | "grep" => (
            filter_flags,
            [
                &["-o", "--output", "-e", "--pattern", "--not"][..],
                &CONTEXT_OPTS,
            ]
            .concat(),
        ),
        "levels" => (
            CONTEXT_FLAGS.to_vec(),
            [&["-o", "--output"][..], &CONTEXT_OPTS].concat(),
        ),
        _ => return None,
    };
    const BATCH: [&str; 4] = ["-r", "--recursive", "--names", "--out-dir"];
    // Split the arguments into the command's own and the positionals.
    let (mut own, mut positionals) = (Vec::new(), Vec::new());
    let (mut dir, mut names, mut out_dir) = (None, None, None);
    let mut it = rest.iter();
    while let Some(x) = it.next() {
        if x == "--" {
            positionals.extend(it.cloned());
            break;
        }
        if BATCH.contains(&x.as_str()) {
            let v = it.next().cloned();
            match x.as_str() {
                "--names" => names = v,
                "--out-dir" => out_dir = v,
                _ => dir = v,
            }
        } else if flags.contains(&x.as_str()) {
            own.push(x.clone());
        } else if opts.contains(&x.as_str()) {
            own.push(x.clone());
            own.extend(it.next().cloned());
        } else if x.starts_with('-') && x.len() > 1 && x.parse::<f64>().is_err() {
            // An unknown option: the command's own parser reports it, once.
            return None;
        } else {
            positionals.push(x.clone());
        }
    }
    // A pattern (or levels) first, unless the patterns come with -e and the first is a file.
    let with_e = own.iter().any(|o| o == "-e" || o == "--pattern");
    let lead = if cmd != "levels"
        && with_e
        && positionals.first().is_some_and(|p| Path::new(p).exists())
    {
        0
    } else {
        1
    };
    if positionals.len() < lead {
        return None;
    }
    let files = match expand_inputs(&positionals[lead..], dir.as_deref(), names.as_deref()) {
        Ok(f) => f,
        Err(Fail(e)) => {
            let _ = writeln!(err, "bigtext {cmd}: {e}");
            return Some(2);
        }
    };
    if cmd != "grep"
        && files.len() <= 1
        && dir.is_none()
        && out_dir.is_none()
        && files.len() + lead == positionals.len()
    {
        return None;
    }
    let single = if cmd == "grep" { "filter" } else { cmd };
    let json = JSON.with(|j| j.get());
    if files.len() > 1 && own.iter().any(|o| o == "-o" || o == "--output") {
        let _ = writeln!(err, "bigtext {cmd}: -o writes one file; with several input files use --out-dir DIR (a NAME.filtered.EXT per file)");
        return Some(2);
    }
    if let Some(d) = &out_dir {
        if let Err(e) = std::fs::create_dir_all(d) {
            let _ = writeln!(err, "bigtext {cmd}: {d}: {e}");
            return Some(2);
        }
    }
    let mut used_names = std::collections::HashSet::new();
    let (mut matched, mut failed, mut total) = (false, false, 0u64);
    for f in &files {
        let mut a: Vec<String> = vec![single.to_string()];
        a.extend(own.iter().cloned());
        if json {
            a.push("--json".into());
        }
        if cmd == "grep" && !own.iter().any(|o| o == "-n" || o == "--line-numbers") {
            a.push("-n".into());
        }
        a.extend(positionals[..lead].iter().cloned());
        a.push(f.clone());
        if let Some(d) = &out_dir {
            let p = Path::new(f);
            let inner = match crate::decompress::detect(p) {
                Some(_) => crate::decompress::inner_name(p),
                None => p
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default(),
            };
            let q = Path::new(&inner);
            let stem = q
                .file_stem()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_default();
            let ext = q.extension().map(|e| format!(".{}", e.to_string_lossy()));
            let ext = ext.unwrap_or_default();
            // Two inputs of the same name (from two folders, or x.log and x.log.gz) get
            // NAME.filtered.EXT and NAME.filtered-2.EXT instead of one overwriting the other.
            let mut name = format!("{stem}.filtered{ext}");
            let mut k = 2;
            while !used_names.insert(name.to_lowercase()) {
                name = format!("{stem}.filtered-{k}{ext}");
                k += 1;
            }
            a.push("-o".into());
            a.push(Path::new(d).join(name).to_string_lossy().into_owned());
        }
        let mut buf = Vec::new();
        let mut ebuf = Vec::new();
        let code = run_command(&a, &mut buf, &mut ebuf);
        let _ = err.write_all(&ebuf);
        match code {
            0 => matched = true,
            1 => {}
            _ => failed = true,
        }
        let name = display_path(Path::new(f));
        if json {
            // The records name their file already.
            if cmd == "count" {
                let n = serde_json::from_slice::<serde_json::Value>(&buf)
                    .ok()
                    .and_then(|v| v["count"].as_u64())
                    .unwrap_or(0);
                total += n;
            }
            let _ = out.write_all(&buf);
        } else if cmd == "count" {
            let n: u64 = String::from_utf8_lossy(&buf).trim().parse().unwrap_or(0);
            total += n;
            let _ = writeln!(out, "{name}: {n}");
        } else {
            for line in buf.split_inclusive(|&b| b == b'\n') {
                let _ = out.write_all(format!("{name}:").as_bytes());
                let _ = out.write_all(line);
            }
        }
    }
    if cmd == "count" && json {
        let _ = writeln!(out, "{}", serde_json::json!({ "total": total }));
    } else if cmd == "count" {
        let _ = writeln!(out, "total: {total}");
    }
    Some(if failed {
        2
    } else if matched {
        0
    } else {
        1
    })
}

fn run_command(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
    let Some(cmd) = args.first().map(|c| c.trim_start_matches('-').to_string()) else {
        let _ = write!(err, "{USAGE}");
        return 2;
    };
    // --json anywhere: records; errors as {"error": …}. Only for the commands that write
    // records; for the others (format and validate have a --json option of their own) it is
    // passed on, and a command without it says so.
    let json = matches!(
        cmd.as_str(),
        "filter" | "grep" | "count" | "levels" | "stats" | "replace" | "saved" | "csv"
    ) && args.iter().any(|a| a == "--json");
    JSON.with(|j| j.set(json));
    let mut rest: Vec<String> = args[1..]
        .iter()
        .filter(|a| !json || *a != "--json")
        .cloned()
        .collect();
    if matches!(cmd.as_str(), "filter" | "count" | "grep") {
        match with_saved(&rest) {
            Ok(r) => rest = r,
            Err(Fail(e)) => {
                if json {
                    let _ = writeln!(out, "{}", serde_json::json!({"error": e}));
                } else {
                    let _ = writeln!(err, "bigtext {cmd}: {e}");
                }
                return 2;
            }
        }
    }
    let rest = &rest[..];
    if let Some(code) = run_batch(&cmd, rest, out, err) {
        return code;
    }
    let r = match cmd.as_str() {
        "filter" | "grep" => cmd_filter(rest, out, false),
        "count" => cmd_filter(rest, out, true),
        "levels" => cmd_levels(rest, out),
        "split" => cmd_split(rest, out),
        "redact" => cmd_redact(rest, out),
        "stats" => cmd_stats(rest, out),
        "merge" => cmd_merge(rest, out),
        "convert" => cmd_convert(rest, out),
        "report" => cmd_report(rest, out),
        "sqldump" => cmd_sqldump(rest, out),
        "values" => cmd_values(rest, out),
        "gaps" => cmd_gaps(rest, out),
        "patterns" => cmd_patterns(rest, out),
        "extract" => cmd_extract(rest, out),
        "validate" => cmd_validate(rest, out),
        "join" => cmd_join(rest, out),
        "pivot" => cmd_pivot(rest, out),
        "derive" => cmd_derive(rest, out),
        "jsonl" | "query" => cmd_jsonl(rest, out),
        "jsondiff" => cmd_jsondiff(rest, out),
        "diff" => cmd_diff(rest, out),
        "only-in" => cmd_only_in(rest, out),
        "diff-table" => cmd_diff_table(rest, out),
        "transform" => cmd_transform(rest, out),
        "replace" => cmd_replace(rest, out),
        "csv" => cmd_csv(rest, out),
        "saved" => cmd_saved(rest, out),
        "head" => cmd_head_tail(rest, out, true),
        "tail" => cmd_head_tail(rest, out, false),
        "slice" => cmd_slice(rest, out),
        "sort" => cmd_sort(rest, out, false),
        "uniq" => cmd_sort(rest, out, true),
        "format" => cmd_format(rest, out),
        "help" | "h" => {
            let _ = write!(out, "{USAGE}");
            return 0;
        }
        _ => fail(format!("unknown command {cmd}")),
    };
    let _ = out.flush();
    match r {
        Ok(code) => code,
        Err(Fail(m)) if json => {
            let _ = writeln!(out, "{}", serde_json::json!({"error": m}));
            2
        }
        Err(Fail(m)) => {
            let _ = writeln!(err, "bigtext {cmd}: {m}");
            2
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run_args(args: &[&str]) -> (i32, String, String) {
        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let (mut out, mut err) = (Vec::new(), Vec::new());
        let code = run(&args, &mut out, &mut err);
        (
            code,
            String::from_utf8_lossy(&out).into_owned(),
            String::from_utf8_lossy(&err).into_owned(),
        )
    }

    fn file(dir: &tempfile::TempDir, name: &str, text: &[u8]) -> String {
        let p = dir.path().join(name);
        std::fs::write(&p, text).unwrap();
        p.to_string_lossy().into_owned()
    }

    #[test]
    fn sizes_are_binary_with_or_without_i() {
        assert_eq!(parse_size("100MB"), Some(100 << 20));
        assert_eq!(parse_size("100M"), Some(100 << 20));
        assert_eq!(parse_size("100MiB"), Some(100 << 20));
        assert_eq!(parse_size("1.5GiB"), Some(3 << 29));
        assert_eq!(parse_size("64kib"), Some(64 << 10));
        assert_eq!(parse_size("512"), Some(512));
        assert_eq!(parse_size("MiB"), None);
        assert_eq!(parse_size("0MB"), None);
    }

    #[test]
    fn the_windowed_program_takes_commands_with_two_dashes() {
        assert!(is_command("--filter"));
        assert!(is_command("--diff-table"));
        // A bare name is a file there (`bigtext sort` opens a file named sort).
        assert!(!is_command("sort"));
        assert!(!is_command("-sort"));
        assert!(!is_command("--nope"));
        // bigtext-cli takes both.
        let d = tempfile::tempdir().unwrap();
        let f = file(&d, "a.log", b"b\na\n");
        assert_eq!(run_args(&["sort", &f]).1, "a\nb\n");
        assert_eq!(run_args(&["--sort", &f]).1, "a\nb\n");
    }

    #[test]
    fn filter_count_and_exit_codes() {
        let d = tempfile::tempdir().unwrap();
        let log = file(
            &d,
            "app.log",
            b"10:00:00 INFO a\r\n10:00:01 ERROR b\r\n10:00:02 error c\r\n",
        );
        assert_eq!(
            run_args(&["filter", "ERROR", &log]),
            (0, "10:00:01 ERROR b\n".into(), String::new())
        );
        assert_eq!(
            run_args(&["--filter", "-i", "error", &log]).1,
            "10:00:01 ERROR b\n10:00:02 error c\n"
        );
        assert_eq!(
            run_args(&["filter", "-v", "-E", "ERROR|INFO", &log]).1,
            "10:00:02 error c\n"
        );
        assert_eq!(run_args(&["filter", "NOPE", &log]).0, 1);
        assert_eq!(
            run_args(&["count", "-i", "error", &log]),
            (0, "2\n".into(), String::new())
        );
        assert_eq!(run_args(&["levels", "error", &log]).1, "10:00:01 ERROR b\n");
        // To a file, in the file's own form (CRLF kept).
        let out = d.path().join("errors.log");
        assert_eq!(
            run_args(&["filter", "ERROR", &log, "-o", &out.to_string_lossy()]).0,
            0
        );
        assert_eq!(std::fs::read(&out).unwrap(), b"10:00:01 ERROR b\r\n");
        // Errors.
        let (code, _, err) =
            run_args(&["filter", "x", &d.path().join("missing").to_string_lossy()]);
        assert_eq!(code, 2);
        assert!(err.starts_with("bigtext filter: "), "{err}");
        assert_eq!(run_args(&["filter", "--bogus", "x", &log]).0, 2);
        assert_eq!(run_args(&["frobnicate"]).0, 2);
        assert_eq!(run_args(&["filter", "-E", "(", &log]).0, 2);
        assert!(is_command("--stats") && !is_command("merge") && !is_command("--follow"));
    }

    #[test]
    fn context_options() {
        let d = tempfile::tempdir().unwrap();
        let log = file(&d, "app.log", b"2024-05-01 10:00:00 INFO a\n2024-05-01 10:00:01 ERROR b\n\tat x.Y(Y.java:1)\n2024-05-01 10:00:02 INFO c\n2024-05-01 10:00:03 INFO d\n2024-05-01 10:00:04 ERROR e\n");
        let (code, out, _) = run_args(&["filter", "-n", "-B", "1", "ERROR", &log]);
        assert_eq!(code, 0);
        assert_eq!(out, "1-2024-05-01 10:00:00 INFO a\n2:2024-05-01 10:00:01 ERROR b\n--\n5-2024-05-01 10:00:03 INFO d\n6:2024-05-01 10:00:04 ERROR e\n");
        assert_eq!(
            run_args(&["levels", "--entries", "error", &log]).1,
            "2024-05-01 10:00:01 ERROR b\n\tat x.Y(Y.java:1)\n--\n2024-05-01 10:00:04 ERROR e\n"
        );
        assert_eq!(
            run_args(&["filter", "-C", "1", "c$", &log, "-E"])
                .1
                .lines()
                .count(),
            3
        );
        assert_eq!(run_args(&["count", "-C", "3", "ERROR", &log]).1, "2\n");
        let o = d.path().join("o.log");
        run_args(&[
            "filter",
            "-n",
            "-A",
            "1",
            "ERROR",
            &log,
            "-o",
            &o.to_string_lossy(),
        ]);
        assert_eq!(std::fs::read_to_string(&o).unwrap(), "2:2024-05-01 10:00:01 ERROR b\n3-\tat x.Y(Y.java:1)\n--\n6:2024-05-01 10:00:04 ERROR e\n");
        assert_eq!(run_args(&["filter", "-A", "x", "ERROR", &log]).0, 2);
    }

    #[test]
    fn convert_json_and_logfmt() {
        let d = tempfile::tempdir().unwrap();
        let j = file(
            &d,
            "a.json",
            b"{\"n\": 2, \"events\": [ {\"id\": 1}, {\"id\": 2} ]}",
        );
        assert_eq!(
            run_args(&["convert", &j, "--to", "jsonl"]).1,
            "{\"id\":1}\n{\"id\":2}\n"
        );
        assert_eq!(
            run_args(&["convert", &j, "--to", "jsonl", "--path", "$.events[1]"]).0,
            2
        );
        let l = file(&d, "a.jsonl", b"{\"id\":1}\n{\"id\":2}\n");
        assert_eq!(
            run_args(&["convert", &l, "--to", "json"]).1,
            "[\n{\"id\":1},\n{\"id\":2}\n]\n"
        );
        let f = file(
            &d,
            "a.log",
            b"level=info msg=ok\nlevel=error msg=\"bad x\"\n",
        );
        assert_eq!(
            run_args(&["convert", &f, "--to", "csv"]).1,
            "level,msg\ninfo,ok\nerror,bad x\n"
        );
        assert_eq!(run_args(&["convert", &f, "--to", "json"]).0, 2);
        // --kind reads it as another kind; --from is the name before 0.15.
        let as_csv = run_args(&["convert", &f, "--to", "jsonl", "--kind", "csv"]);
        assert_eq!(as_csv.0, 0);
        assert_eq!(
            as_csv,
            run_args(&["convert", &f, "--to", "jsonl", "--from", "csv"])
        );
    }

    #[test]
    fn convert_json_array_to_csv_however_it_is_laid_out() {
        let d = tempfile::tempdir().unwrap();
        let rows = "a,b\n1,\"x, y\"\n2,\n";
        for (name, text) in [
            // On one line, as tools and APIs write it; after white space or a byte order mark.
            ("one.json", &b"[{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]"[..]),
            ("space.json", b" \n [{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]\n"),
            (
                "bom.json",
                b"\xEF\xBB\xBF[{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]",
            ),
            // Pretty-printed: an item per line, or each over several.
            (
                "pretty.json",
                b"[\n  {\"a\": 1, \"b\": \"x, y\"},\n  {\"a\": 2}\n]\n",
            ),
            (
                "deep.json",
                b"[\n  {\n    \"a\": 1,\n    \"b\": \"x, y\"\n  },\n  {\n    \"a\": 2\n  }\n]\n",
            ),
        ] {
            let f = file(&d, name, text);
            assert_eq!(
                run_args(&["convert", &f, "--to", "csv"]),
                (0, rows.into(), String::new()),
                "{name}"
            );
        }
        // The array at --path.
        let o = file(
            &d,
            "o.json",
            b"{\"n\": 2, \"events\": [{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]}",
        );
        assert_eq!(
            run_args(&["convert", &o, "--to", "csv", "--path", "$.events"]).1,
            rows
        );
        // A broken array is an error, not an empty table.
        let bad = file(&d, "bad.json", b"[{\"a\":1} {\"a\":2}]");
        let (code, _, err) = run_args(&["convert", &bad, "--to", "csv"]);
        assert_eq!(code, 2);
        assert!(err.starts_with("bigtext convert: expected ','"), "{err}");
    }

    #[test]
    fn convert_detects_the_table() {
        let d = tempfile::tempdir().unwrap();
        let t = file(&d, "t.csv", b"sep=;\n# note\nk;v\nx;1\n");
        assert_eq!(
            run_args(&["convert", &t, "--to", "jsonl"]).1,
            "{\"k\":\"x\",\"v\":\"1\"}\n"
        );
        let n = file(&d, "n.csv", b"1,2\n3,4\n5,6\n");
        assert_eq!(
            run_args(&["convert", &n, "--to", "jsonl"]).1.lines().next(),
            Some("{\"column1\":\"1\",\"column2\":\"2\"}")
        );
        assert_eq!(
            run_args(&["convert", &n, "--to", "jsonl", "--header"])
                .1
                .lines()
                .next(),
            Some("{\"1\":\"3\",\"2\":\"4\"}")
        );
        let q = file(&d, "q.csv", b"a,b\n'x,y',2\n");
        assert_eq!(
            run_args(&["convert", &q, "--to", "jsonl", "--quote", "'"]).1,
            "{\"a\":\"x,y\",\"b\":\"2\"}\n"
        );
    }

    #[test]
    fn json_lines_queries() {
        let d = tempfile::tempdir().unwrap();
        let f = file(&d, "e.jsonl", b"{\"level\":\"error\",\"ms\":700,\"u\":{\"id\":1}}\n{\"level\":\"info\",\"ms\":20}\n{\"level\":\"error\",\"ms\":5,\"msg\":\"a, b\"}\n");
        assert_eq!(
            run_args(&["jsonl", &f, "-q", ".level == error and .ms > 500"]).1,
            "{\"level\":\"error\",\"ms\":700,\"u\":{\"id\":1}}\n"
        );
        assert_eq!(
            run_args(&["jsonl", &f, "-q", ".level = error", "--count"]).1,
            "2\n"
        );
        assert_eq!(
            run_args(&[
                "jsonl",
                &f,
                "-q",
                ".level = error",
                "-v",
                "--fields",
                "level,ms"
            ])
            .1,
            "{\"level\":\"info\",\"ms\":20}\n"
        );
        assert_eq!(
            run_args(&["jsonl", &f, "--fields", "ms,u.id,msg", "--to", "csv"]).1,
            "ms,u.id,msg\n700,1,\n20,,\n5,,\"a, b\"\n"
        );
        assert_eq!(run_args(&["jsonl", &f, "-q", ".nope exists"]).0, 1);
        assert_eq!(run_args(&["jsonl", &f, "-q", "level"]).0, 2);
    }

    #[test]
    fn derived_column() {
        let d = tempfile::tempdir().unwrap();
        let t = file(&d, "s.csv", b"price,qty\r\n2.5,4\r\n1,\"x\"\r\n");
        assert_eq!(
            run_args(&["derive", &t, "--name", "total", "--expr", "{price} * {qty}"]).1,
            "price,qty,total\r\n2.5,4,10\r\n1,\"x\",\r\n"
        );
        assert_eq!(
            run_args(&["derive", &t, "--name", "x", "--expr", "{nope}"]).0,
            2
        );
    }

    #[test]
    fn pivot_tables() {
        let d = tempfile::tempdir().unwrap();
        let t = file(
            &d,
            "s.csv",
            b"city,product,qty\nT,tea,3\nB,tea,5\nT,rice,7\n",
        );
        assert_eq!(
            run_args(&["pivot", &t, "--rows", "city", "--cols", "product"]).1,
            "city,rice,tea,total\nT,1,1,2\nB,0,1,1\n"
        );
        assert_eq!(
            run_args(&["pivot", &t, "--rows", "1", "--cols", "2", "--value", "qty"]).1,
            "city,rice,tea,total\nT,7,3,10\nB,,5,5\n"
        );
        assert_eq!(
            run_args(&["pivot", &t, "--rows", "city", "--cols", "product", "--agg", "mean"]).0,
            2
        );
    }

    #[test]
    fn join_tables() {
        let d = tempfile::tempdir().unwrap();
        let o = file(&d, "o.csv", b"order,user\n1,u1\n2,u3\n");
        let u = file(&d, "u.csv", b"id,name\nu1,Ann\nu2,Bob\n");
        assert_eq!(
            run_args(&["join", &o, &u, "--left-on", "user", "--right-on", "id"]).1,
            "order,user,name\n1,u1,Ann\n2,u3,\n"
        );
        assert_eq!(
            run_args(&[
                "join",
                &o,
                &u,
                "--left-on",
                "2",
                "--right-on",
                "1",
                "--inner"
            ])
            .1,
            "order,user,name\n1,u1,Ann\n"
        );
        assert_eq!(run_args(&["join", &o, &u, "--on", "nope"]).0, 2);
    }

    #[test]
    fn line_diff() {
        let d = tempfile::tempdir().unwrap();
        let a = file(
            &d,
            "a.log",
            b"10:00:01 start req=a1\n10:00:02 Working\n10:00:03 end\n",
        );
        let b = file(
            &d,
            "b.log",
            b"11:20:01 start req=f9\n11:20:02 working\n11:20:03 end\nextra\n",
        );
        let (code, out, _) = run_args(&["diff", &a, &b]);
        assert_eq!(code, 1);
        assert!(
            out.starts_with(&format!(
                "--- {a}\n+++ {b}\n@@ -1,3 +1,4 @@\n-10:00:01 start req=a1\n"
            )),
            "{out}"
        );
        assert!(out.ends_with("+11:20:03 end\n+extra\n"), "{out}");
        let masked = ["diff", &a, &b, "-t", "-i", "--mask", "req=[0-9a-f]+"];
        let (code, out, _) = run_args(&masked);
        let body = |out: &str| out.lines().skip(2).map(String::from).collect::<Vec<_>>();
        assert_eq!(
            (code, body(&out)),
            (
                1,
                vec![
                    "@@ -1,3 +1,4 @@".into(),
                    " 10:00:01 start req=a1".into(),
                    " 10:00:02 Working".into(),
                    " 10:00:03 end".into(),
                    "+extra".into()
                ]
            )
        );
        let (_, out, _) = run_args(&[&masked[..], &["-U", "0"]].concat());
        assert_eq!(body(&out), vec!["@@ -3,0 +4,1 @@", "+extra"]);
        assert_eq!(
            run_args(&["diff", &a, &b, "-q"]),
            (1, format!("Files {a} and {b} differ\n"), String::new())
        );
        let o = d.path().join("out.diff").to_string_lossy().into_owned();
        assert_eq!(run_args(&["diff", &a, &b, "-o", &o]).1, "");
        assert!(std::fs::read_to_string(&o).unwrap().contains("+extra\n"));
        assert_eq!(
            run_args(&["diff", &a, &a]),
            (0, String::new(), String::new())
        );
        assert_eq!(run_args(&["diff", &a, &a, "-q"]).0, 0);
        assert_eq!(run_args(&["diff", &a, &b, "--mask", "("]).0, 2);
    }

    #[test]
    fn lines_only_in_one_file() {
        let d = tempfile::tempdir().unwrap();
        let a = file(
            &d,
            "a.log",
            b"09:00:01 start job=1\n09:00:02 load\n09:00:03 crash\n09:00:04 load\n",
        );
        let b = file(&d, "b.log", b"10:15:00 load\n10:15:01 start job=7\n");
        assert_eq!(
            run_args(&["only-in", &a, &b]),
            (
                1,
                "09:00:01 start job=1\n09:00:02 load\n09:00:03 crash\n09:00:04 load\n".into(),
                String::new()
            )
        );
        let masked = ["only-in", &a, &b, "-t", "--mask", "job=[0-9]+"];
        assert_eq!(
            run_args(&masked),
            (1, "09:00:03 crash\n".into(), String::new())
        );
        assert_eq!(
            run_args(&[&masked[..], &["--count"]].concat()),
            (1, "1\n".into(), String::new())
        );
        assert_eq!(
            run_args(&["only-in", &b, &a, "-t", "--mask", "job=[0-9]+"]),
            (0, String::new(), String::new())
        );
    }

    #[test]
    fn table_diff_by_key() {
        let d = tempfile::tempdir().unwrap();
        let a = file(&d, "a.csv", b"id,name,qty\n1,apple,5\n2,banana,7\n");
        let b = file(
            &d,
            "b.csv",
            b"qty,name,id\n6,apple,1\n7,banana,2\n1,fig,9\n",
        );
        assert_eq!(
            run_args(&["diff-table", &a, &b, "--on", "id"]),
            (
                1,
                "status,id,changed,name,qty\nchanged,1,qty,apple,5 → 6\nadded,9,,fig,1\n".into(),
                String::new()
            )
        );
        assert_eq!(
            run_args(&[
                "diff-table",
                &a,
                &b,
                "--left-on",
                "1",
                "--right-on",
                "3",
                "--all"
            ])
            .1
            .lines()
            .nth(2),
            Some("same,2,,banana,7")
        );
        // The names before 0.15 still work.
        assert_eq!(
            run_args(&["diff-table", &a, &b, "--key", "1", "--key-b", "3", "--all"]).1,
            run_args(&[
                "diff-table",
                &a,
                &b,
                "--on",
                "1",
                "--right-on",
                "3",
                "--all"
            ])
            .1
        );
        assert_eq!(run_args(&["diff-table", &a, &a, "--key", "id"]).0, 0);
        assert_eq!(run_args(&["diff-table", &a, &b]).0, 2);
    }

    #[test]
    fn csv_column_tools() {
        let d = tempfile::tempdir().unwrap();
        let t = file(
            &d,
            "s.csv",
            b"id,city,amount\n1,Tashkent,120\n2,Bukhara,80\n3,Tashkent,40\n",
        );
        assert_eq!(
            run_args(&["csv", &t, "cut", "amount,id"]).1,
            "amount,id\n120,1\n80,2\n40,3\n"
        );
        assert_eq!(
            run_args(&["csv", &t, "drop", "2"]).1,
            "id,amount\n1,120\n2,80\n3,40\n"
        );
        assert_eq!(
            run_args(&["csv", &t, "sort", "--by", "amount", "--desc"]).1,
            "id,city,amount\n1,Tashkent,120\n2,Bukhara,80\n3,Tashkent,40\n"
        );
        assert_eq!(
            run_args(&["csv", &t, "sort", "amount"]).1.lines().nth(1),
            Some("3,Tashkent,40")
        );
        assert_eq!(
            run_args(&["csv", &t, "where", "city=Tashkent", "amount>50"]).1,
            "id,city,amount\n1,Tashkent,120\n"
        );
        assert_eq!(
            run_args(&["csv", &t, "where", "amount", "lt", "100"]).1,
            "id,city,amount\n2,Bukhara,80\n3,Tashkent,40\n"
        );
        assert_eq!(run_args(&["csv", &t, "where", "city~zzz"]).0, 1);
        let st = run_args(&["csv", &t, "stats", "amount"]).1;
        assert!(
            st.contains("rows: 3\n") && st.contains("sum: 240\n") && st.contains("mean: 80\n"),
            "{st}"
        );
        let gr = run_args(&["csv", &t, "group", "city", "--sum", "amount"]).1;
        assert!(
            gr.starts_with("city,rows,sum") || gr.contains("Tashkent"),
            "{gr}"
        );
        let (code, _, err) = run_args(&["csv", &t, "cut", "nope"]);
        assert!(
            code == 2 && err.contains("the columns are id, city, amount"),
            "{err}"
        );
        let semi = file(&d, "p.txt", b"a|b\n1|2\n");
        assert_eq!(
            run_args(&["csv", &semi, "cut", "b", "--delimiter", "|"]).1,
            "b\n2\n"
        );
    }

    #[test]
    fn json_replace_and_saved_searches() {
        let d = tempfile::tempdir().unwrap();
        let log = file(&d, "a.log", b"ok\r\nERROR one\r\nERROR two\r\n");
        let (code, out, _) = run_args(&["filter", "ERROR", &log, "--json"]);
        assert_eq!(code, 0);
        let recs: Vec<serde_json::Value> = out
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(
            (
                recs.len(),
                recs[0]["line"].as_u64(),
                recs[0]["offset"].as_u64(),
                recs[1]["text"].as_str()
            ),
            (2, Some(2), Some(4), Some("ERROR two"))
        );
        let c: serde_json::Value =
            serde_json::from_str(run_args(&["count", "ERROR", &log, "--json"]).1.trim()).unwrap();
        assert_eq!(c["count"], 2);
        let st: serde_json::Value =
            serde_json::from_str(run_args(&["stats", &log, "--json"]).1.trim()).unwrap();
        assert_eq!(
            (st["lines"].as_u64(), st["crlf"].as_u64()),
            (Some(3), Some(3))
        );
        let no_saved = file(&d, "state.txt", b"# BigText session state\nfont_size=14\n");
        let e: serde_json::Value = serde_json::from_str(
            run_args(&[
                "count",
                "x",
                "--saved",
                "nope",
                "--settings",
                &no_saved,
                "--json",
            ])
            .1
            .trim(),
        )
        .unwrap();
        assert!(e["error"].as_str().unwrap().contains("nope"));
        // Replace to stdout, then in place with a backup.
        assert_eq!(
            run_args(&["replace", "-E", "ERROR (\\w+)", "E[$1]", &log]).1,
            "ok\r\nE[one]\r\nE[two]\r\n"
        );
        assert_eq!(
            run_args(&["replace", "ERROR", "Error", &log, "--in-place", "--bak"]),
            (0, "2 replaced\n".into(), String::new())
        );
        assert_eq!(
            std::fs::read(&log).unwrap(),
            b"ok\r\nError one\r\nError two\r\n"
        );
        assert!(std::path::Path::new(&format!("{log}.bak")).exists());
        assert_eq!(
            run_args(&["replace", "nothing", "x", &log, "--in-place"]).0,
            1
        );
        // A saved search from a settings file.
        let settings = file(
            &d,
            "settings.txt",
            b"saved=Errors|i|0||error\nsaved=Not ok|c|1||ok\n",
        );
        assert_eq!(
            run_args(&["saved", "--settings", &settings]).1,
            "Errors\terror\nNot ok\tok  (c)  (lines without)\n"
        );
        assert_eq!(
            run_args(&["count", "--saved", "Errors", "--settings", &settings, &log]).1,
            "2\n"
        );
        assert_eq!(
            run_args(&["filter", "--saved", "Not ok", "--settings", &settings, &log]).1,
            "Error one\nError two\n"
        );
    }

    #[test]
    fn saved_tells_a_wrong_file_from_settings_without_searches() {
        let d = tempfile::tempdir().unwrap();
        // The app's own file without saved searches: nothing, exit code 1.
        let state = file(
            &d,
            "state.txt",
            b"# BigText session state\r\nfont_size=14\r\n",
        );
        assert_eq!(
            run_args(&["saved", "--settings", &state]),
            (1, String::new(), String::new())
        );
        // Anything else is an error that names the file.
        let not =
            "not a BigText settings file (the app's state.txt, or one from Help → Export settings)";
        for (name, text) in [
            (
                "app.log",
                &b"2024-05-01 10:00:00 INFO start\n2024-05-01 10:00:01 ERROR x\n"[..],
            ),
            ("t.csv", b"name,count\nsaved,3\n"),
            ("a.json", b"[{\"saved\":1},{\"saved\":2}]"),
            ("b.bin", b"\x00\x01\x02\xFF\xFE\x00garbage"),
            ("logfmt.log", b"level=info msg=ok\nlevel=error msg=bad\n"),
            // A saved session is not the settings either.
            (
                "work.session",
                b"# BigText session\ntab=0|0|0||a.log\npinned=0\n",
            ),
            ("empty.txt", b""),
        ] {
            let f = file(&d, name, text);
            let shown = display_path(Path::new(&f));
            assert_eq!(
                run_args(&["saved", "--settings", &f]),
                (2, String::new(), format!("bigtext saved: {shown}: {not}\n")),
                "{name}"
            );
            if name == "app.log" {
                assert_eq!(
                    run_args(&["saved", "--json", "--settings", &f]),
                    (
                        2,
                        format!(
                            "{}\n",
                            serde_json::json!({"error": format!("{shown}: {not}")})
                        ),
                        String::new()
                    )
                );
                assert_eq!(
                    run_args(&["count", "--saved", "Errors", "--settings", &f, &f]),
                    (2, String::new(), format!("bigtext count: {shown}: {not}\n"))
                );
            }
        }
        // A missing file, as other commands report one.
        let missing = d.path().join("missing.txt");
        let shown = display_path(&missing);
        let (code, out, err) = run_args(&["saved", "--settings", &missing.to_string_lossy()]);
        assert_eq!((code, out.as_str()), (2, ""));
        assert!(
            err.starts_with(&format!("bigtext saved: {shown}: ")) && !err.contains(not),
            "{err}"
        );
        // An exported file (after a byte order mark, with a hand edit in another encoding).
        let exported = file(
            &d,
            "my.settings",
            b"\xEF\xBB\xBF# BigText settings\nfont=Caf\xE9\nsaved=Errors|i|0||error\n",
        );
        assert_eq!(
            run_args(&["saved", "--settings", &exported]),
            (0, "Errors\terror\n".into(), String::new())
        );
    }

    #[test]
    fn many_files_folders_and_compressed_inputs() {
        use std::io::Write as _;
        let d = tempfile::tempdir().unwrap();
        let sub = d.path().join("old");
        std::fs::create_dir(&sub).unwrap();
        let a = file(&d, "a.log", b"ok\nERROR one\n");
        let _b = file(&d, "b.log", b"fine\n");
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        gz.write_all(b"ERROR packed\nok\n").unwrap();
        std::fs::write(sub.join("c.log.gz"), gz.finish().unwrap()).unwrap();
        let star = d.path().join("*.log").to_string_lossy().into_owned();
        let (code, out, _) = run_args(&["count", "ERROR", &star]);
        assert_eq!(code, 0);
        assert!(
            out.contains("a.log: 1\n") && out.contains("b.log: 0\n") && out.ends_with("total: 1\n"),
            "{out}"
        );
        let dir = d.path().to_string_lossy().into_owned();
        let (code, out, _) = run_args(&["grep", "ERROR", "-r", &dir, "--names", "*.log;*.gz"]);
        assert_eq!(code, 0);
        assert!(
            out.contains("a.log:2:ERROR one\n") && out.contains("c.log.gz:1:ERROR packed\n"),
            "{out}"
        );
        assert_eq!(run_args(&["grep", "nothing", &a]).0, 1);
        // One output per input.
        let outdir = d.path().join("out");
        std::fs::create_dir(&outdir).unwrap();
        let (code, _, _) = run_args(&[
            "filter",
            "ERROR",
            &star,
            "--out-dir",
            &outdir.to_string_lossy(),
        ]);
        assert_eq!(code, 0);
        assert_eq!(
            std::fs::read_to_string(outdir.join("a.filtered.log")).unwrap(),
            "ERROR one\n"
        );
        // A compressed input on its own.
        assert_eq!(
            run_args(&["filter", "packed", &sub.join("c.log.gz").to_string_lossy()]).1,
            "ERROR packed\n"
        );
        assert_eq!(
            run_args(&["count", "ERROR", &d.path().join("*.txt").to_string_lossy()]).0,
            2
        );
    }

    #[test]
    fn head_tail_slice() {
        let d = tempfile::tempdir().unwrap();
        let log: String = (0..100)
            .map(|i| format!("2024-05-01 10:{:02}:{:02} line {i}\n", i / 60, i % 60))
            .collect();
        let f = file(&d, "t.log", log.as_bytes());
        let lines = |s: &str| s.lines().map(String::from).collect::<Vec<_>>();
        assert_eq!(
            lines(&run_args(&["head", "-n", "2", &f]).1),
            ["2024-05-01 10:00:00 line 0", "2024-05-01 10:00:01 line 1"]
        );
        assert_eq!(
            lines(&run_args(&["tail", "-n", "1", &f]).1),
            ["2024-05-01 10:01:39 line 99"]
        );
        assert_eq!(run_args(&["tail", &f]).1.lines().count(), 10);
        assert_eq!(
            lines(&run_args(&["slice", &f, "--lines", "3-4"]).1),
            ["2024-05-01 10:00:02 line 2", "2024-05-01 10:00:03 line 3"]
        );
        // Bytes widen to whole lines.
        assert_eq!(
            run_args(&["slice", &f, "--bytes", "5-40"])
                .1
                .lines()
                .count(),
            2
        );
        let (code, out, _) = run_args(&[
            "slice",
            &f,
            "--from",
            "2024-05-01 10:01:00",
            "--to",
            "10:01:02",
        ]);
        assert_eq!(
            (code, lines(&out)),
            (
                0,
                vec![
                    "2024-05-01 10:01:00 line 60".to_string(),
                    "2024-05-01 10:01:01 line 61".into(),
                    "2024-05-01 10:01:02 line 62".into()
                ]
            )
        );
        assert_eq!(
            run_args(&["slice", &f, "--from", "2024-05-02 00:00:00"]).0,
            1
        );
        let csv = file(&d, "t.csv", b"id,v\n1,a\n2,b\n3,c\n");
        assert_eq!(
            run_args(&["slice", &csv, "--lines", "3-3", "--with-header"]).1,
            "id,v\n2,b\n"
        );
        // The name before 0.15 still works.
        assert_eq!(
            run_args(&["slice", &csv, "--lines", "3-3", "--header"]).1,
            "id,v\n2,b\n"
        );
        assert_eq!(run_args(&["slice", &f]).0, 2);
    }

    #[test]
    fn sort_and_uniq() {
        let d = tempfile::tempdir().unwrap();
        let f = file(&d, "s.txt", b"pear\napple\n10\n9\napple\n");
        assert_eq!(run_args(&["sort", &f]).1, "10\n9\napple\napple\npear\n");
        assert_eq!(
            run_args(&["sort", "-n", "-r", &f]).1.lines().next(),
            Some("10")
        );
        assert_eq!(run_args(&["sort", "-u", &f]).1, "10\n9\napple\npear\n");
        assert_eq!(
            run_args(&["uniq", "-c", &f]).1,
            "2\tapple\n1\t10\n1\t9\n1\tpear\n"
        );
    }

    #[test]
    fn transform_and_format() {
        let d = tempfile::tempdir().unwrap();
        let t = file(&d, "t.log", b"Hello\tworld  \nSecond\n");
        assert_eq!(
            run_args(&["transform", "--op", "upper", &t]).1,
            "HELLO\tWORLD  \nSECOND\n"
        );
        assert_eq!(
            run_args(&["transform", "--op", "trim", &t]).1,
            "Hello\tworld\nSecond\n"
        );
        assert_eq!(
            run_args(&["transform", "--op", "tabs", &t]).1,
            "Hello   world  \nSecond\n"
        );
        assert_eq!(run_args(&["transform", "--op", "sort", &t]).0, 2);
        let j = file(&d, "j.json", b"{\"a\": [1, {\"b\": null}]}\n");
        assert_eq!(
            run_args(&["format", &j, "--style", "minify"]).1,
            "{\"a\":[1,{\"b\":null}]}\n"
        );
        // The name before 0.15 still works.
        assert_eq!(
            run_args(&["format", &j, "--json", "minify"]).1,
            "{\"a\":[1,{\"b\":null}]}\n"
        );
        assert_eq!(run_args(&["format", &j, "--style", "tight"]).0, 2);
        assert_eq!(
            run_args(&["format", &j]).1,
            "{\n  \"a\": [\n    1,\n    {\n      \"b\": null\n    }\n  ]\n}\n"
        );
        let bad = file(&d, "bad.json", b"[1, 2");
        assert_eq!(run_args(&["format", &bad]).0, 2);
    }

    #[test]
    fn json_diff() {
        let d = tempfile::tempdir().unwrap();
        let a = file(&d, "a.json", b"{\"x\": 1, \"y\": [1, 2]}");
        let b = file(&d, "b.json", b"{\n  \"y\": [1, 3],\n  \"x\": 1\n}");
        assert_eq!(
            run_args(&["jsondiff", &a, &b]),
            (1, "$.y[1]: 2 -> 3\n".into(), String::new())
        );
        let c = file(&d, "c.json", b"{\"y\":[1,2],\"x\":1}");
        assert_eq!(run_args(&["jsondiff", &a, &c]).0, 0);
    }

    #[test]
    fn validate_json() {
        let d = tempfile::tempdir().unwrap();
        let j = file(&d, "a.json", b"{\n  \"a\": [1, 2,]\n}\n");
        assert_eq!(
            run_args(&["validate", &j]),
            (
                1,
                "2: byte 15: a comma before a closing bracket (a trailing comma)\n".into(),
                String::new()
            )
        );
        let l = file(&d, "a.jsonl", b"{\"a\":1}\n{\"a\":}\n{\"b\":2}\n");
        assert_eq!(
            run_args(&["validate", &l]).1,
            "2: byte 13: a value is missing after the key\n"
        );
        let ok = file(&d, "ok.json", b"[1, {\"x\": null}]");
        assert_eq!(run_args(&["validate", &ok]).0, 0);
        // --as gives the kind; --lines and --json are the names before 0.15.
        let t = file(&d, "lines.txt", b"{\"a\":1}\n{\"a\":}\n");
        let jsonl_problem = "2: byte 13: a value is missing after the key\n";
        assert_eq!(
            run_args(&["validate", &t, "--as", "jsonl"]).1,
            jsonl_problem
        );
        assert_eq!(run_args(&["validate", &t, "--lines"]).1, jsonl_problem);
        assert_eq!(run_args(&["validate", &t, "--as", "json"]).0, 1);
        let braces = file(&d, "braces.csv", b"{a},b\n1,2\n");
        assert_eq!(run_args(&["validate", &braces]).0, 1);
        assert_eq!(run_args(&["validate", &braces, "--as", "csv"]).0, 0);
        assert_eq!(run_args(&["validate", &ok, "--as", "xml"]).0, 2);
    }

    #[test]
    fn validate_a_table() {
        let d = tempfile::tempdir().unwrap();
        let t = file(&d, "t.csv", b"id,qty\n1,2\n2\n3,x\n");
        assert_eq!(
            run_args(&["validate", "--numeric", "2", &t]),
            (
                1,
                "3: 1 fields instead of 2\n4: column 2: not a number\n".into(),
                String::new()
            )
        );
        let ok = file(&d, "ok.csv", b"a,b\n1,2\n");
        assert_eq!(run_args(&["validate", &ok]).0, 0);
    }

    #[test]
    fn extract_matches() {
        let d = tempfile::tempdir().unwrap();
        let log = file(&d, "a.log", b"GET /a 200\nGET /b 404\nPOST /a 200\n");
        assert_eq!(
            run_args(&["extract", "-E", "[0-9]{3}", &log]).1,
            "200\n404\n200\n"
        );
        assert_eq!(
            run_args(&["extract", "-E", "--count", "-g", "1", r"(GET|POST) /", &log]).1,
            "2\tGET\n1\tPOST\n"
        );
        assert_eq!(run_args(&["extract", "-E", "-g", "2", "(x)", &log]).0, 2);
        assert_eq!(run_args(&["extract", "nope", &log]).0, 1);
    }

    #[test]
    fn message_patterns() {
        let d = tempfile::tempdir().unwrap();
        let log = file(
            &d,
            "a.log",
            b"10:00:00 INFO req 1 ok\n10:00:01 INFO req 2 ok\n10:00:02 ERROR disk full\n",
        );
        let (code, out, _) = run_args(&["patterns", &log]);
        assert_eq!(code, 0);
        assert_eq!(out.lines().nth(1), Some("2,INFO,INFO req <n> ok,0,23"));
        assert_eq!(
            run_args(&["patterns", "--rare", "--top", "1", &log])
                .1
                .lines()
                .nth(1),
            Some("1,ERROR,ERROR disk full,46,46")
        );
    }

    #[test]
    fn between_times() {
        let d = tempfile::tempdir().unwrap();
        let log = file(&d, "a.log", b"2024-05-01 10:00:00 ERROR a\n2024-05-01 10:00:30 ERROR b\n2024-05-01 10:01:00 INFO c\n2024-05-01 10:01:30 ERROR d\n");
        assert_eq!(
            run_args(&["filter", "ERROR", "--from", "10:00:30", "--to", "10:01:00", &log]).1,
            "2024-05-01 10:00:30 ERROR b\n"
        );
        assert_eq!(
            run_args(&["levels", "error", "--from", "2024-05-01 10:00:15", &log]).1,
            "2024-05-01 10:00:30 ERROR b\n2024-05-01 10:01:30 ERROR d\n"
        );
        assert_eq!(
            run_args(&["count", "ERROR", "--to", "10:00:30", &log]).1,
            "2\n"
        );
        assert_eq!(run_args(&["filter", "ERROR", "--from", "noon", &log]).0, 2);
    }

    #[test]
    fn combined_patterns() {
        let d = tempfile::tempdir().unwrap();
        let log = file(
            &d,
            "a.log",
            b"ERROR timeout user=1\nERROR timeout healthcheck\nWARN timeout user=1\nERROR disk\n",
        );
        assert_eq!(
            run_args(&[
                "filter",
                "ERROR",
                "-e",
                "timeout",
                "--not",
                "healthcheck",
                &log
            ])
            .1,
            "ERROR timeout user=1\n"
        );
        assert_eq!(
            run_args(&["count", "-e", "disk", "-e", "WARN", "--any", &log]).1,
            "2\n"
        );
        assert_eq!(
            run_args(&["count", "-e", "ERROR", "-e", "user=1", &log]).1,
            "1\n"
        );
        assert_eq!(
            run_args(&["filter", "-E", "--any", "-e", "^WARN", "-e", "disk$", &log]).1,
            "WARN timeout user=1\nERROR disk\n"
        );
        assert_eq!(run_args(&["filter", &log]).0, 2);
    }

    #[test]
    fn values_of_a_field() {
        let d = tempfile::tempdir().unwrap();
        let jl = file(
            &d,
            "e.jsonl",
            b"\n{\"level\":\"info\"}\n{\"level\":\"error\"}\n{\"level\":\"info\"}\n",
        );
        assert_eq!(
            run_args(&["values", "level", &jl]),
            (
                0,
                "level,lines,percent,first,last\ninfo,2,66.67,,\nerror,1,33.33,,\n".into(),
                String::new()
            )
        );
        let lf = file(
            &d,
            "a.log",
            b"ts=2024-05-01T10:00:00Z status=200\nts=2024-05-01T10:00:09Z status=200\n",
        );
        // The times as the file writes them.
        assert_eq!(
            run_args(&["values", "status", &lf]).1.lines().nth(1),
            Some("200,2,100.00,2024-05-01T10:00:00Z,2024-05-01T10:00:09Z")
        );
        // A time with a comma is quoted.
        let comma = file(
            &d,
            "c.log",
            b"2024-05-01 10:00:00,250 status=500\n2024-05-01 10:00:01,500 status=500\n",
        );
        assert_eq!(
            run_args(&["values", "status", &comma]).1.lines().nth(1),
            Some("500,2,100.00,\"2024-05-01 10:00:00,250\",\"2024-05-01 10:00:01,500\"")
        );
        assert_eq!(run_args(&["values", "nope", &lf]).0, 1);
    }

    #[test]
    fn gaps_with_line_numbers() {
        let d = tempfile::tempdir().unwrap();
        let log = file(
            &d,
            "a.log",
            b"2024-05-01 10:00:00 a\n2024-05-01 10:00:05 b\n  trace\n2024-05-01 10:02:05 c\n",
        );
        assert_eq!(
            run_args(&["gaps", &log]),
            (
                0,
                "2-4: +2 m 00.000 s (2024-05-01 10:00:05 -> 2024-05-01 10:02:05)\n".into(),
                String::new()
            )
        );
        assert_eq!(run_args(&["gaps", "--min", "5m", &log]).0, 1);
        assert_eq!(run_args(&["gaps", "--min", "soon", &log]).0, 2);
        // M could be a month: minutes are m or min.
        assert_eq!(run_args(&["gaps", "--min", "1M", &log]).0, 2);
        assert_eq!(run_args(&["gaps", "--min", "1min", &log]).0, 0);
        // The times as the file writes them.
        let iso = file(
            &d,
            "iso.log",
            b"2024-05-01T10:00:00.120Z a\n2024-05-01T10:01:00.120Z b\n",
        );
        assert_eq!(
            run_args(&["gaps", &iso]).1,
            "1-2: +1 m 00.000 s (2024-05-01T10:00:00.120Z -> 2024-05-01T10:01:00.120Z)\n"
        );
    }

    #[test]
    fn split_stats_merge_convert() {
        let d = tempfile::tempdir().unwrap();
        let log = file(
            &d,
            "a.log",
            b"2024-05-01 10:00:00 one\n2024-05-01 10:00:02 two\n2024-05-01 11:00:00 three\n",
        );
        let (code, out, _) = run_args(&["split", "--lines", "2", &log]);
        assert_eq!(code, 0);
        assert_eq!(out.lines().count(), 2);
        assert_eq!(
            std::fs::read_to_string(d.path().join("a.part002.log")).unwrap(),
            "2024-05-01 11:00:00 three\n"
        );
        let packed = d.path().join("packed");
        std::fs::create_dir(&packed).unwrap();
        let (_, out, _) = run_args(&[
            "split",
            "--lines",
            "2",
            "--gz",
            "--out-dir",
            &packed.to_string_lossy(),
            &log,
        ]);
        assert!(out.lines().all(|l| l.ends_with(".log.gz")), "{out}");
        // An empty file has no parts: exit code 1, like the other commands that find nothing.
        let empty = file(&d, "empty.log", b"");
        assert_eq!(
            run_args(&["split", "--lines", "2", &empty]),
            (1, String::new(), String::new())
        );
        // -o with a compressed name compresses.
        let gz = d.path().join("two.log.gz").to_string_lossy().into_owned();
        assert_eq!(run_args(&["filter", "two", &log, "-o", &gz]).0, 0);
        let mut text = Vec::new();
        crate::decompress::unpack_to(
            Path::new(&gz),
            crate::decompress::Kind::Gzip,
            &mut text,
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap();
        assert_eq!(text, b"2024-05-01 10:00:02 two\n");
        let (_, s, _) = run_args(&["stats", &log]);
        assert!(
            s.contains("line endings: LF (LF 3, CRLF 0, CR 0)\n")
                && s.contains("final line break: yes\n")
                && s.contains("longest line: 25 bytes (line 3)\n"),
            "{s}"
        );
        assert!(
            s.contains("lines: 3\n")
                && s.contains("encoding: UTF-8")
                && s.contains("first time: 2024-05-01 10:00:00")
                && s.contains("last time: 2024-05-01 11:00:00")
                && s.contains("span: 1 h 00 m 00 s"),
            "{s}"
        );
        let b = file(&d, "b.log", b"2024-05-01 10:00:01 b1\n");
        assert_eq!(
            run_args(&["merge", &log, &b]).1.lines().nth(1),
            Some("b.log │ 2024-05-01 10:00:01 b1")
        );
        let csv_path = file(&d, "t.csv", b"k,v\nx,1\n");
        assert_eq!(
            run_args(&["convert", &csv_path, "--to", "jsonl"]).1,
            "{\"k\":\"x\",\"v\":\"1\"}\n"
        );
        assert_eq!(run_args(&["convert", &csv_path, "--to", "xlsx"]).0, 2);
        let jl = file(&d, "e.jsonl", b"{\"a\": 1}\n");
        assert_eq!(run_args(&["convert", &jl, "--to", "csv"]).1, "a\n1\n");
        assert_eq!(parse_size("100MB"), Some(100 << 20));
        assert_eq!(parse_size("1.5g"), Some(3 << 29));
        assert_eq!(parse_size("x"), None);
    }

    /// Found by an audit of the command line before 1.0.
    #[test]
    fn options_json_and_several_files() {
        let d = tempfile::tempdir().unwrap();
        let a = file(
            &d,
            "a.log",
            b"ERROR one
-foo two
INFO three
",
        );
        let sub = d.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        let b = sub.join("a.log");
        std::fs::write(
            &b,
            b"ERROR four
",
        )
        .unwrap();
        let b = b.to_string_lossy().into_owned();
        // `--` ends the options: a pattern may start with a dash.
        let (code, out, err) = run_args(&["filter", "--", "-foo", &a]);
        assert_eq!(
            (code, out.as_str()),
            (
                0,
                "-foo two
"
            ),
            "{err}"
        );
        // An unknown option is reported once.
        let (code, _, err) = run_args(&["filter", "-iv", "error", &a]);
        assert_eq!(
            (code, err.matches("unknown option").count()),
            (2, 1),
            "{err}"
        );
        // A negative number is a value.
        let t = file(
            &d,
            "t.csv",
            b"k,qty
x,-9
y,3
",
        );
        let (code, out, err) = run_args(&["csv", &t, "where", "qty", "lt", "-5"]);
        assert_eq!(
            (code, out.as_str()),
            (
                0,
                "k,qty
x,-9
"
            ),
            "{err}"
        );
        // validate keeps its own --json (strict JSON); it is not the output mode.
        let nj = file(
            &d,
            "n.txt",
            b"not json
",
        );
        assert_eq!(run_args(&["validate", &nj, "--json"]).0, 1);
        // Several files: JSON records name their file and are not prefixed.
        let (code, out, _) = run_args(&["filter", "ERROR", &a, &b, "--json"]);
        assert_eq!(code, 0);
        let recs: Vec<serde_json::Value> = out
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(recs.len(), 2, "{out}");
        let (_, out, _) = run_args(&["count", "ERROR", &a, &b, "--json"]);
        assert!(
            out.ends_with(
                "{\"total\":2}
"
            ),
            "{out}"
        );
        // -o with several files would keep only the last one's lines.
        let o = d.path().join("o.txt").to_string_lossy().into_owned();
        let (code, _, err) = run_args(&["filter", "ERROR", &a, &b, "-o", &o]);
        assert_eq!(code, 2, "{err}");
        assert!(err.contains("--out-dir"), "{err}");
        // --out-dir is created, and two inputs of one name get two outputs.
        let od = d.path().join("new").join("out");
        let ods = od.to_string_lossy().into_owned();
        assert_eq!(
            run_args(&["filter", "ERROR", &a, &b, "--out-dir", &ods]).0,
            0
        );
        let mut names: Vec<String> = std::fs::read_dir(&od)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        assert_eq!(names, ["a.filtered-2.log", "a.filtered.log"]);
        // count writes no file: -o is an error, not ignored.
        assert_eq!(run_args(&["count", "ERROR", &a, "-o", &o]).0, 2);
        // replace --json to the console would mix the text and the record.
        assert_eq!(run_args(&["replace", "ERROR", "E", &a, "--json"]).0, 2);
        // --fields of logfmt lines are their keys, not JSON keys.
        let lf = file(
            &d,
            "lf.log",
            b"level=error user=ann ms=5\nlevel=info user=bob ms=1\n",
        );
        let (code, out, err) =
            run_args(&["jsonl", &lf, "-q", ".level = error", "--fields", "user,ms"]);
        assert_eq!(
            (code, out.as_str()),
            (0, "{\"user\":\"ann\",\"ms\":\"5\"}\n"),
            "{err}"
        );
        let (_, out, _) = run_args(&[
            "jsonl",
            &lf,
            "-q",
            ".level = error",
            "--fields",
            "user,ms",
            "--to",
            "csv",
        ]);
        assert_eq!(out, "user,ms\nann,5\n");
    }
}