Source file tezos_clic.ml
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
open Error_monad
module StringMap = Map.Make (String)
module StringSet = Set.Make (String)
type ('p, 'ctx) parameter = {
converter : 'ctx -> string -> 'p tzresult Lwt.t;
autocomplete : ('ctx -> string list tzresult Lwt.t) option;
}
let parameter ?autocomplete converter = {converter; autocomplete}
let compose_parameters {converter = c1; autocomplete = a1'}
{converter = c2; autocomplete = a2'} =
let open Lwt_result_syntax in
{
converter =
(fun ctx s ->
let*! r = c1 ctx s in
match r with Ok r -> return r | Error _ -> c2 ctx s);
autocomplete =
(match a1' with
| None -> a2'
| Some a1 -> (
match a2' with
| None -> a1'
| Some a2 ->
Some
(fun ctx ->
let* r1 = a1 ctx in
let* r2 = a2 ctx in
return (List.concat [r1; r2]))));
}
let map_parameter ~f {converter; autocomplete} =
let open Lwt_result_syntax in
{
converter =
(fun ctx s ->
let+ v = converter ctx s in
f v);
autocomplete;
}
let map_es_parameter ~f {converter; autocomplete} =
let open Lwt_result_syntax in
{
converter =
(fun ctx s ->
let* v = converter ctx s in
f ctx v);
autocomplete;
}
type label = {long : string; short : char option}
type ('a, 'ctx) arg =
| Arg : {
doc : string;
label : label;
placeholder : string;
kind : ('p, 'ctx) parameter;
}
-> ('p option, 'ctx) arg
| MultipleArg : {
doc : string;
label : label;
placeholder : string;
kind : ('p, 'ctx) parameter;
}
-> ('p list option, 'ctx) arg
| DefArg : {
doc : string;
label : label;
placeholder : string;
kind : ('p, 'ctx) parameter;
default : string;
}
-> ('p, 'ctx) arg
| Switch : {label : label; doc : string} -> (bool, 'ctx) arg
| Constant : 'a -> ('a, 'ctx) arg
| Map : {
spec : ('a, 'ctx) arg;
converter : 'ctx -> 'a -> 'b tzresult Lwt.t;
}
-> ('b, 'ctx) arg
| Pair : ('a, 'ctx) arg * ('b, 'ctx) arg -> ('a * 'b, 'ctx) arg
type ('a, 'ctx) params =
| Prefix : string * ('a, 'ctx) params -> ('a, 'ctx) params
| Param :
string * string * ('p, 'ctx) parameter * ('a, 'ctx) params
-> ('p -> 'a, 'ctx) params
| Stop : ('ctx -> unit tzresult Lwt.t, 'ctx) params
| Seq :
string * string * ('p, 'ctx) parameter
-> ('p list -> 'ctx -> unit tzresult Lwt.t, 'ctx) params
| NonTerminalSeq :
string
* string
* ('p, 'ctx) parameter
* string list
* ('a -> 'b, 'ctx) params
-> ('p list -> 'a -> 'b, 'ctx) params
type ('a, 'ctx) options = ('a, 'ctx) arg
let aggregate spec = spec
type group = {name : string; title : string}
type 'arg command =
| Command : {
params : ('a, 'iarg) params;
options : ('b, 'iarg) options;
handler : 'b -> 'a;
desc : string;
group : group option;
conv : 'arg -> 'iarg;
}
-> 'arg command
type error += Bad_argument of int * string
type error += Unterminated_command : string list * 'ctx command list -> error
type error += Command_not_found : string list * 'ctx command list -> error
type error += Unknown_option : string * 'ctx command option -> error
type error += Option_expected_argument : string * 'ctx command option -> error
type error += Bad_option_argument : string * 'ctx command option -> error
type error += Multiple_occurrences : string * 'ctx command option -> error
type error +=
let trim s =
TzString.split_no_empty '\n' s |> List.map String.trim |> String.concat "\n"
let print_desc ppf doc =
let short, long =
match String.index_opt doc '\n' with
| None -> (doc, None)
| Some len ->
( String.sub doc 0 len,
Some (String.sub doc (len + 1) (String.length doc - len - 1)) )
in
match long with
| None -> Format.fprintf ppf "%s" short
| Some doc ->
Format.fprintf
ppf
"%s@{<full>@\n @[<hov 0>%a@]@}"
short
Format.pp_print_text
doc
let print_label ppf = function
| {long; short = None} -> Format.fprintf ppf "--%s" long
| {long; short = Some short} -> Format.fprintf ppf "-%c --%s" short long
let rec print_options_detailed :
type ctx a. Format.formatter -> (a, ctx) options -> unit =
fun ppf -> function
| Arg {label; placeholder; doc; _} ->
Format.fprintf
ppf
"@{<opt>%a <%s>@}: %a"
print_label
label
placeholder
print_desc
doc
| MultipleArg {label; placeholder; doc; _} ->
Format.fprintf
ppf
"@{<opt>%a <%s>@}: %a"
print_label
label
placeholder
print_desc
doc
| DefArg {label; placeholder; doc; default; _} ->
Format.fprintf
ppf
"@{<opt>%a <%s>@}: %a"
print_label
label
placeholder
print_desc
(doc ^ "\nDefaults to `" ^ default ^ "`.")
| Switch {label; doc} ->
Format.fprintf ppf "@{<opt>%a@}: %a" print_label label print_desc doc
| Constant _ -> ()
| Pair (speca, specb) ->
Format.fprintf
ppf
"%a@,%a"
print_options_detailed
speca
print_options_detailed
specb
| Map {spec; converter = _} -> print_options_detailed ppf spec
let rec has_args : type a ctx. (a, ctx) arg -> bool = function
| Constant _ -> false
| Arg _ | MultipleArg _ | DefArg _ | Switch _ -> true
| Pair (speca, specb) -> has_args speca || has_args specb
| Map {spec; _} -> has_args spec
let rec print_options_brief :
type ctx a. Format.formatter -> (a, ctx) arg -> unit =
fun ppf -> function
| DefArg {label; placeholder; _} ->
Format.fprintf ppf "[@{<opt>%a <%s>@}]" print_label label placeholder
| Arg {label; placeholder; _} ->
Format.fprintf ppf "[@{<opt>%a <%s>@}]" print_label label placeholder
| MultipleArg {label; placeholder; _} ->
Format.fprintf ppf "[@{<opt>%a <%s>@}]" print_label label placeholder
| Switch {label; _} -> Format.fprintf ppf "[@{<opt>%a@}]" print_label label
| Constant _ -> ()
| Pair (speca, specb) ->
Format.fprintf
ppf
"%a@ %a"
print_options_brief
speca
print_options_brief
specb
| Map {spec; converter = _} -> print_options_brief ppf spec
let print_highlight highlight_strings formatter str =
let rec print_string = function
| [] -> Format.fprintf formatter "%s" str
| regex :: tl -> (
match Re.Str.full_split regex str with
| [] | [Re.Str.Text _] -> print_string tl
| list ->
List.iter
(function
| Re.Str.Text text -> Format.fprintf formatter "%s" text
| Re.Str.Delim delimiter ->
Format.fprintf formatter "@{<hilight>%s@}" delimiter)
list)
in
print_string (List.map Re.Str.regexp_string highlight_strings)
let print_commandline ppf (highlights, options, args) =
let print_suffix =
Format.(pp_print_list ~pp_sep:pp_print_space (print_highlight highlights))
in
let rec print : type a ctx. Format.formatter -> (a, ctx) params -> unit =
fun ppf -> function
| Stop -> Format.fprintf ppf "%a" print_options_brief options
| Seq (n, _, _) when not (has_args options) ->
Format.fprintf ppf "[@{<arg>%s@}...]" n
| Seq (n, _, _) ->
Format.fprintf ppf "[@{<arg>%s@}...] %a" n print_options_brief options
| NonTerminalSeq (n, _, _, suffix, Stop) when not (has_args options) ->
Format.fprintf ppf "[@{<arg>%s@}...] @{<kwd>%a@}" n print_suffix suffix
| NonTerminalSeq (n, _, _, suffix, next) ->
Format.fprintf
ppf
"[@{<arg>%s@}...] @{<kwd>%a@} %a %a"
n
print_suffix
suffix
print
next
print_options_brief
options
| Prefix (n, Stop) when not (has_args options) ->
Format.fprintf ppf "@{<kwd>%a@}" (print_highlight highlights) n
| Prefix (n, next) ->
Format.fprintf
ppf
"@{<kwd>%a@} %a"
(print_highlight highlights)
n
print
next
| Param (n, _, _, Stop) when not (has_args options) ->
Format.fprintf ppf "@{<arg>%s@}" n
| Param (n, _, _, next) -> Format.fprintf ppf "@{<arg>%s@} %a" n print next
in
Format.fprintf ppf "@{<commandline>%a@}" print args
let rec print_params_detailed :
type a b ctx. (b, ctx) arg -> Format.formatter -> (a, ctx) params -> unit =
fun spec ppf -> function
| Stop -> print_options_detailed ppf spec
| Seq (n, desc, _) ->
Format.fprintf ppf "@{<arg>%s@}: %a" n print_desc (trim desc) ;
if has_args spec then
Format.fprintf ppf "@,%a" print_options_detailed spec
| NonTerminalSeq (n, desc, _, _, next) ->
Format.fprintf ppf "@{<arg>%s@}: %a" n print_desc (trim desc) ;
if has_args spec then
Format.fprintf ppf "@,%a" (print_params_detailed spec) next
| Prefix (_, next) -> print_params_detailed spec ppf next
| Param (n, desc, _, Stop) ->
Format.fprintf ppf "@{<arg>%s@}: %a" n print_desc (trim desc) ;
if has_args spec then
Format.fprintf ppf "@,%a" print_options_detailed spec
| Param (n, desc, _, next) ->
Format.fprintf
ppf
"@{<arg>%s@}: %a@,%a"
n
print_desc
(trim desc)
(print_params_detailed spec)
next
let contains_params_args : type a ctx. (a, ctx) params -> (_, ctx) arg -> bool =
fun params args ->
let rec help : (a, ctx) params -> bool = function
| Stop -> has_args args
| Seq (_, _, _) -> true
| NonTerminalSeq (_, _, _, _, _) -> true
| Prefix (_, next) -> help next
| Param (_, _, _, _) -> true
in
help params
let print_command :
type ctx.
?prefix:(Format.formatter -> unit -> unit) ->
?highlights:string list ->
Format.formatter ->
ctx command ->
unit =
fun ?(prefix = fun _ () -> ())
?(highlights = [])
ppf
(Command {params; desc; options; _}) ->
if contains_params_args params options then
Format.fprintf
ppf
"@{<command>%a%a@{<short>@,@{<commanddoc>%a@,%a@}@}@}"
prefix
()
print_commandline
(highlights, options, params)
print_desc
desc
(print_params_detailed options)
params
else
Format.fprintf
ppf
"@{<command>%a%a@{<short>@,@{<commanddoc>%a@}@}@}"
prefix
()
print_commandline
(highlights, options, params)
print_desc
desc
type ex_command = Ex : _ command -> ex_command
let group_commands commands =
let grouped, ungrouped =
List.fold_left
(fun (grouped, ungrouped) (Ex (Command {group; _}) as command) ->
match group with
| None -> (grouped, command :: ungrouped)
| Some group -> (
match
List.find_opt (fun ({name; _}, _) -> group.name = name) grouped
with
| None -> ((group, ref [command]) :: grouped, ungrouped)
| Some ({title; _}, r) ->
if title <> group.title then
invalid_arg "Tezos_clic.usage: duplicate group name" ;
r := command :: !r ;
(grouped, ungrouped)))
([], [])
commands
in
List.map
(fun (g, c) -> (g, List.rev !c))
(match ungrouped with
| [] -> grouped
| l ->
grouped @ [({name = "misc"; title = "Miscellaneous commands"}, ref l)])
let print_group print_command ppf ({title; _}, commands) =
Format.fprintf
ppf
"@{<title>%s@}@,@{<list>%a@}"
title
(Format.pp_print_list print_command)
commands
type formatter_state =
Format.formatter_out_functions * Format.formatter_stag_functions * bool
type format = Plain | Ansi | Html
type verbosity = Terse | Short | Details | Full
let setup_formatter ppf format verbosity =
let skip = ref false in
let ((orig_out_functions, _, _) as orig_state) =
( Format.pp_get_formatter_out_functions ppf (),
Format.pp_get_formatter_stag_functions ppf (),
Format.pp_get_print_tags ppf () )
in
(Format.pp_print_flush ppf () ;
Format.pp_set_formatter_out_functions
ppf
{
out_string =
(fun s b a ->
if s = "\000\000\000" then skip := true
else if s = "\255\255\255" then skip := false
else if not !skip then orig_out_functions.out_string s b a);
out_spaces = (fun n -> if not !skip then orig_out_functions.out_spaces n);
out_newline =
(fun () -> if not !skip then orig_out_functions.out_newline ());
out_flush = (fun () -> if not !skip then orig_out_functions.out_flush ());
out_indent = orig_out_functions.out_indent;
} ;
let levels = ref [] in
let setup_level (level, op) =
if op level verbosity then Format.fprintf ppf "@<0>%s" "\255\255\255"
else Format.fprintf ppf "@<0>%s" "\000\000\000"
in
let push_level level =
levels := level :: !levels ;
setup_level level
in
let pop_level () =
match !levels with
| _ :: level :: rest ->
levels := level :: rest ;
setup_level level
| [_] | [] -> Stdlib.failwith "Tezos_clic: unclosed verbosity tag"
in
push_level (Terse, ( <= )) ;
let push_level_tag = function
| Format.String_tag tag ->
let push op = function
| "full" -> push_level (Full, op)
| "details" -> push_level (Details, op)
| "short" -> push_level (Short, op)
| "terse" -> push_level (Terse, op)
| tag ->
Stdlib.failwith
("Tezos_clic: invalid semantic string tag <" ^ tag ^ ">")
in
if String.length tag > 0 && tag.[0] = '=' then
push ( = ) (String.sub tag 1 (String.length tag - 1))
else if String.length tag > 0 && tag.[0] = '-' then
push ( > ) (String.sub tag 1 (String.length tag - 1))
else push ( <= ) tag
| _stag -> Stdlib.failwith "Tezos_clic: invalid semantic tag"
in
let pop_level_tag = function
| Format.String_tag "full"
| Format.String_tag "details"
| Format.String_tag "short"
| Format.String_tag "terse"
| Format.String_tag "-full"
| Format.String_tag "-details"
| Format.String_tag "-short"
| Format.String_tag "-terse"
| Format.String_tag "=full"
| Format.String_tag "=details"
| Format.String_tag "=short"
| Format.String_tag "=terse" ->
pop_level ()
| Format.String_tag tag ->
Stdlib.failwith
("Tezos_clic: invalid semantic string tag <" ^ tag ^ ">")
| _stag -> Stdlib.failwith "Tezos_clic: invalid semantic tag"
in
match format with
| Ansi ->
let color_num = function
| `Auto -> None
| `Black -> Some 0
| `Red -> Some 1
| `Green -> Some 2
| `Yellow -> Some 3
| `Blue -> Some 4
| `Magenta -> Some 5
| `Cyan -> Some 6
| `White -> Some 7
in
let ansi_format ppf (fg, bg, b, u) =
Format.fprintf ppf "@<0>%s" "\027[0m" ;
match
(match color_num fg with
| Some n -> [string_of_int (30 + n)]
| None -> [])
@ (match color_num bg with
| Some n -> [string_of_int (40 + n)]
| None -> [])
@ (if b then ["1"] else [])
@ if u then ["4"] else []
with
| [] -> ()
| l -> Format.fprintf ppf "@<0>%s" ("\027[" ^ String.concat ";" l ^ "m")
in
let ansi_stack = ref [(`Auto, `Auto, false, false)] in
let push_ansi_format (fg, bg, b, u) =
let format =
match !ansi_stack with
| (pfg, pbg, pb, pu) :: _ ->
( Option.value ~default:pfg fg,
Option.value ~default:pbg bg,
pb || b,
pu || u )
| [] -> assert false
in
ansi_stack := format :: !ansi_stack ;
Format.fprintf ppf "@<0>%a" ansi_format format
in
let pop_ansi_format () =
Format.fprintf ppf "@<0>%s" "\027[0m" ;
match !ansi_stack with
| _ :: format :: rest ->
ansi_stack := format :: rest ;
Format.fprintf ppf "@<0>%a" ansi_format format
| [_] | [] -> Stdlib.failwith "Tezos_clic: unclosed ansi format"
in
Format.pp_set_formatter_stag_functions
ppf
{
mark_open_stag = (fun _ -> "");
mark_close_stag = (fun _ -> "");
print_open_stag =
(function
| Format.String_tag "title" ->
push_ansi_format (None, None, true, true)
| Format.String_tag "commandline" -> Format.fprintf ppf "@[<hov 4>"
| Format.String_tag "commanddoc" -> Format.fprintf ppf " @[<v 0>"
| Format.String_tag "opt" ->
push_ansi_format (Some `Green, None, false, false)
| Format.String_tag "arg" ->
push_ansi_format (Some `Yellow, None, false, false) ;
Format.fprintf ppf "<"
| Format.String_tag "kwd" ->
push_ansi_format (None, None, false, true)
| Format.String_tag "error" ->
push_ansi_format (Some `Red, None, true, true)
| Format.String_tag "warning" ->
push_ansi_format (Some `Yellow, None, true, true)
| Format.String_tag "hilight" ->
push_ansi_format (Some `White, Some `Yellow, true, true)
| Format.String_tag "list" -> Format.fprintf ppf " @[<v 0>"
| Format.String_tag "command" -> Format.fprintf ppf "@[<v 0>"
| Format.String_tag "document" -> Format.fprintf ppf "@[<v 0>"
| other -> push_level_tag other);
print_close_stag =
(function
| Format.String_tag "title" ->
Format.fprintf ppf ":" ;
pop_ansi_format ()
| Format.String_tag "commandline" -> Format.fprintf ppf "@]"
| Format.String_tag "commanddoc" -> Format.fprintf ppf "@]"
| Format.String_tag "opt" -> pop_ansi_format ()
| Format.String_tag "arg" ->
Format.fprintf ppf ">" ;
pop_ansi_format ()
| Format.String_tag "kwd" -> pop_ansi_format ()
| Format.String_tag "error" -> pop_ansi_format ()
| Format.String_tag "warning" -> pop_ansi_format ()
| Format.String_tag "hilight" -> pop_ansi_format ()
| Format.String_tag "command" | Format.String_tag "list" ->
Format.fprintf ppf "@]"
| Format.String_tag "document" -> Format.fprintf ppf "@]"
| other -> pop_level_tag other);
} ;
Format.pp_set_print_tags ppf true
| Plain ->
Format.pp_set_formatter_stag_functions
ppf
{
mark_open_stag = (fun _ -> "");
mark_close_stag = (fun _ -> "");
print_open_stag =
(function
| Format.String_tag "title" -> ()
| Format.String_tag "commandline" -> Format.fprintf ppf "@[<hov 4>"
| Format.String_tag "commanddoc" -> Format.fprintf ppf " @[<v 0>"
| Format.String_tag "opt" -> ()
| Format.String_tag "arg" -> Format.fprintf ppf "<"
| Format.String_tag "kwd" -> ()
| Format.String_tag "hilight" -> ()
| Format.String_tag "error" -> ()
| Format.String_tag "warning" -> ()
| Format.String_tag "list" -> Format.fprintf ppf " @[<v 0>"
| Format.String_tag "command" -> Format.fprintf ppf "@[<v 0>"
| Format.String_tag "document" -> Format.fprintf ppf "@[<v 0>"
| other -> push_level_tag other);
print_close_stag =
(function
| Format.String_tag "title" -> Format.fprintf ppf ":"
| Format.String_tag "commandline" -> Format.fprintf ppf "@]"
| Format.String_tag "commanddoc" -> Format.fprintf ppf "@]"
| Format.String_tag "opt" -> ()
| Format.String_tag "arg" -> Format.fprintf ppf ">"
| Format.String_tag "kwd" -> ()
| Format.String_tag "error" -> ()
| Format.String_tag "warning" -> ()
| Format.String_tag "hilight" -> ()
| Format.String_tag "command" | Format.String_tag "list" ->
Format.fprintf ppf "@]"
| Format.String_tag "document" -> Format.fprintf ppf "@]"
| other -> pop_level_tag other);
} ;
Format.pp_set_print_tags ppf true
| Html ->
Format.pp_set_formatter_stag_functions
ppf
{
mark_open_stag = (fun _ -> "");
mark_close_stag = (fun _ -> "");
print_open_stag =
(function
| Format.String_tag "title" -> Format.fprintf ppf "\003h3\004"
| Format.String_tag "commandline" ->
Format.fprintf ppf "\003div class='cmdline'\004@[<h>"
| Format.String_tag "commanddoc" ->
Format.fprintf ppf "\003div class='cmddoc'\004"
| Format.String_tag "opt" ->
Format.fprintf ppf "\003span class='opt'\004"
| Format.String_tag "arg" ->
Format.fprintf ppf "\003span class='arg'\004"
| Format.String_tag "kwd" ->
Format.fprintf ppf "\003span class='kwd'\004"
| Format.String_tag "hilight" -> ()
| Format.String_tag "error" -> ()
| Format.String_tag "warning" -> ()
| Format.String_tag "list" -> Format.fprintf ppf "\003ul\004@\n"
| Format.String_tag "command" -> Format.fprintf ppf "\003li\004@\n"
| Format.String_tag "document" ->
Format.fprintf
ppf
"@[<v 0>\003style\004.cmdline { font-family: monospace \
}.cmddoc { white-space: pre-wrap ; font-family: monospace; \
line-height: 170%%; margin: 0 0 20px 0 }.cmdline { \
background: #343131; padding: 2px 8px; border-radius:10px; \
color: white; margin: 5px; }.cmdline+.cmddoc { margin: \
-5px 5px 0 20px; padding: 5px }.opt,.arg { background: \
#343131; font-weight: bold; padding: 2px 4px; \
border-radius:5px; }.kwd { font-weight: bold; } .opt { \
color:#CF0; background: #460; } .arg { color: #CEF; \
background: #369; }\003/style\004@\n"
| other -> push_level_tag other);
print_close_stag =
(function
| Format.String_tag "title" -> Format.fprintf ppf "\003/h3\004@\n"
| Format.String_tag "commandline" ->
Format.fprintf ppf "@]\003/div\004@\n"
| Format.String_tag "commanddoc" ->
Format.fprintf ppf "\003/div\004@\n"
| Format.String_tag "opt"
| Format.String_tag "arg"
| Format.String_tag "kwd" ->
Format.fprintf ppf "\003/span\004"
| Format.String_tag "error"
| Format.String_tag "warning"
| Format.String_tag "hilight" ->
()
| Format.String_tag "list" -> Format.fprintf ppf "\003/ul\004@\n"
| Format.String_tag "command" ->
Format.fprintf ppf "\003/li\004@\n"
| Format.String_tag "document" -> Format.fprintf ppf "@]"
| other -> pop_level_tag other);
} ;
let orig_out_functions = Format.pp_get_formatter_out_functions ppf () in
Format.pp_set_formatter_out_functions
ppf
{
orig_out_functions with
out_string =
(fun s i j ->
let buf = Buffer.create (j - i) in
for n = i to j - 1 do
match s.[n] with
| '\003' -> Buffer.add_char buf '<'
| '\004' -> Buffer.add_char buf '>'
| '>' -> Buffer.add_string buf ">"
| '<' -> Buffer.add_string buf "<"
| c -> Buffer.add_char buf c
done ;
let s' = Buffer.contents buf in
orig_out_functions.out_string s' 0 (String.length s'));
} ;
Format.pp_set_print_tags ppf true) ;
orig_state
let restore_formatter ppf (out_functions, tag_functions, tags) =
Format.pp_print_flush ppf () ;
Format.pp_set_formatter_out_functions ppf out_functions ;
Format.pp_set_formatter_stag_functions ppf tag_functions ;
Format.pp_set_print_tags ppf tags
let usage_internal ppf ~executable_name ~global_options ?(highlights = [])
commands =
let by_group = group_commands commands in
let print_groups =
Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf "@,@,")
(print_group (fun ppf (Ex command) ->
print_command ?prefix:None ~highlights ppf command))
in
Format.fprintf
ppf
"@{<document>@{<title>Usage@}@,\
@{<list>@{<command>@{<commandline>%s [@{<opt>global options@}] \
@{<kwd>command@} [@{<opt>command options@}]@}@}@,\
@{<command>@{<commandline>%s @{<opt>--help@} (for global options)@}@}@,\
@{<command>@{<commandline>%s [@{<opt>global options@}] @{<kwd>command@} \
@{<opt>--help@} (for command options)@}@}@,\
@{<command>@{<commandline>%s @{<opt>--version@} (for version \
information)@}@}@}@,\
@,\
@{<title>To browse the documentation@}@,\
@{<list>@{<command>@{<commandline>%s [@{<opt>global options@}] \
@{<kwd>man@} (for a list of commands)@}@}@,\
@{<command>@{<commandline>%s [@{<opt>global options@}] @{<kwd>man@} \
@{<opt>-v 3@} (for the full manual)@}@}@}@,\
@,\
@{<title>Global options (must come before the command)@}@,\
@{<commanddoc>%a@}%a%a@}@."
executable_name
executable_name
executable_name
executable_name
executable_name
executable_name
print_options_detailed
global_options
(fun ppf () -> if by_group <> [] then Format.fprintf ppf "@,@,")
()
print_groups
by_group
let constant c = Constant c
let arg ~doc ?short ~long ~placeholder kind =
Arg {doc; label = {long; short}; placeholder; kind}
let multiple_arg ~doc ?short ~long ~placeholder kind =
MultipleArg {doc; label = {long; short}; placeholder; kind}
let default_arg ~doc ?short ~long ~placeholder ~default kind =
DefArg {doc; placeholder; label = {long; short}; kind; default}
let map_arg ~f:converter spec = Map {spec; converter}
let args1 a = a
let args2 a b = Pair (a, b)
let merge_options = args2
let args3 a b c =
map_arg
~f:(fun _ ((a, b), c) -> Lwt_result_syntax.return (a, b, c))
(args2 (args2 a b) c)
let args4 a b c d =
map_arg
~f:(fun _ ((a, b), (c, d)) -> Lwt_result_syntax.return (a, b, c, d))
(args2 (args2 a b) (args2 c d))
let args5 a b c d e =
map_arg
~f:(fun _ ((a, b, c, d), e) -> Lwt_result_syntax.return (a, b, c, d, e))
(args2 (args4 a b c d) e)
let args6 a b c d e f =
map_arg
~f:(fun _ ((a, b, c, d), (e, f)) ->
Lwt_result_syntax.return (a, b, c, d, e, f))
(args2 (args4 a b c d) (args2 e f))
let args7 a b c d e f g =
map_arg
~f:(fun _ ((a, b, c, d), (e, f, g)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g))
(args2 (args4 a b c d) (args3 e f g))
let args8 a b c d e f g h =
map_arg
~f:(fun _ ((a, b, c, d), (e, f, g, h)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h))
(args2 (args4 a b c d) (args4 e f g h))
let args9 a b c d e f g h i =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), i) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i))
(args2 (args8 a b c d e f g h) i)
let args10 a b c d e f g h i j =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j))
(args2 (args8 a b c d e f g h) (args2 i j))
let args11 a b c d e f g h i j k =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k))
(args2 (args8 a b c d e f g h) (args3 i j k))
let args12 a b c d e f g h i j k l =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k, l)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k, l))
(args2 (args8 a b c d e f g h) (args4 i j k l))
let args13 a b c d e f g h i j k l m =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k, l, m)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k, l, m))
(args2 (args8 a b c d e f g h) (args5 i j k l m))
let args14 a b c d e f g h i j k l m n =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k, l, m, n)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k, l, m, n))
(args2 (args8 a b c d e f g h) (args6 i j k l m n))
let args15 a b c d e f g h i j k l m n o =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k, l, m, n, o)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o))
(args2 (args8 a b c d e f g h) (args7 i j k l m n o))
let args16 a b c d e f g h i j k l m n o p =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h), (i, j, k, l, m, n, o, p)) ->
Lwt_result_syntax.return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p))
(args2 (args8 a b c d e f g h) (args8 i j k l m n o p))
let args17 a b c d e f g h i j k l m n o p q =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), q) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q))
(args2 (args16 a b c d e f g h i j k l m n o p) q)
let args18 a b c d e f g h i j k l m n o p q r =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), (q, r)) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r))
(args2 (args16 a b c d e f g h i j k l m n o p) (args2 q r))
let args19 a b c d e f g h i j k l m n o p q r s =
map_arg
~f:(fun _ ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), (q, r, s)) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s))
(args2 (args16 a b c d e f g h i j k l m n o p) (args3 q r s))
let args20 a b c d e f g h i j k l m n o p q r s t =
map_arg
~f:
(fun _ ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), (q, r, s, t)) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t))
(args2 (args16 a b c d e f g h i j k l m n o p) (args4 q r s t))
let args21 a b c d e f g h i j k l m n o p q r s t u =
map_arg
~f:
(fun _ ((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), (q, r, s, t, u)) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u))
(args2 (args16 a b c d e f g h i j k l m n o p) (args5 q r s t u))
let args22 a b c d e f g h i j k l m n o p q r s t u v =
map_arg
~f:
(fun _
((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p), (q, r, s, t, u, v))
->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v))
(args2 (args16 a b c d e f g h i j k l m n o p) (args6 q r s t u v))
let args23 a b c d e f g h i j k l m n o p q r s t u v w =
map_arg
~f:
(fun _
( (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p),
(q, r, s, t, u, v, w) ) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w))
(args2 (args16 a b c d e f g h i j k l m n o p) (args7 q r s t u v w))
let args24 a b c d e f g h i j k l m n o p q r s t u v w x =
map_arg
~f:
(fun _
( (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p),
(q, r, s, t, u, v, w, x) ) ->
Lwt_result_syntax.return
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x))
(args2 (args16 a b c d e f g h i j k l m n o p) (args8 q r s t u v w x))
let args25 a b c d e f g h i j k l m n o p q r s t u v w x y =
map_arg
~f:
(fun _
( (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p),
(q, r, s, t, u, v, w, x, y) ) ->
Lwt_result_syntax.return
( a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x,
y ))
(args2 (args16 a b c d e f g h i j k l m n o p) (args9 q r s t u v w x y))
let switch ~doc ?short ~long () = Switch {doc; label = {long; short}}
let rec parse_arg :
type a ctx.
?command:_ command ->
(a, ctx) arg ->
string list StringMap.t ->
ctx ->
a tzresult Lwt.t =
fun ?command spec args_dict ctx ->
let open Lwt_result_syntax in
match spec with
| Arg {label = {long; short = _}; kind = {converter; _}; _} -> (
match StringMap.find_opt long args_dict with
| None | Some [] -> return_none
| Some [s] ->
let+ x =
trace_eval (fun () -> Bad_option_argument ("--" ^ long, command))
@@ converter ctx s
in
Some x
| Some (_ :: _) -> tzfail (Multiple_occurrences ("--" ^ long, command)))
| MultipleArg {label = {long; short = _}; kind = {converter; _}; _} -> (
match StringMap.find_opt long args_dict with
| None | Some [] -> return_none
| Some l ->
let+ x =
List.map_es
(fun s ->
trace_eval (fun () ->
Bad_option_argument ("--" ^ long, command))
@@ converter ctx s)
l
in
Some x)
| DefArg {label = {long; short = _}; kind = {converter; _}; default; _} -> (
let*! r = converter ctx default in
match r with
| Error _ ->
invalid_arg
(Format.sprintf
"Value provided as default for '%s' could not be parsed by \
converter function."
long)
| Ok default -> (
match StringMap.find_opt long args_dict with
| None | Some [] -> return default
| Some [s] ->
trace (Bad_option_argument (long, command)) (converter ctx s)
| Some (_ :: _) -> tzfail (Multiple_occurrences (long, command))))
| Switch {label = {long; short = _}; _} -> (
match StringMap.find_opt long args_dict with
| None | Some [] -> return_false
| Some [_] -> return_true
| Some (_ :: _) -> tzfail (Multiple_occurrences (long, command)))
| Constant c -> return c
| Pair (speca, specb) ->
let* arga = parse_arg ?command speca args_dict ctx in
let* argb = parse_arg ?command specb args_dict ctx in
return (arga, argb)
| Map {spec; converter} ->
let* arg = parse_arg ?command spec args_dict ctx in
converter ctx arg
let empty_args_dict = StringMap.empty
let rec make_arities_dict :
type a b.
(a, b) arg -> (int * string) StringMap.t -> (int * string) StringMap.t =
fun arg acc ->
let add {long; short} num =
(match short with
| None -> acc
| Some c -> StringMap.add ("-" ^ String.make 1 c) (num, long) acc)
|> StringMap.add ("-" ^ long) (num, long)
|> StringMap.add ("--" ^ long) (num, long)
in
match arg with
| Arg {label; _} -> add label 1
| MultipleArg {label; _} -> add label 1
| DefArg {label; _} -> add label 1
| Switch {label; _} -> add label 0
| Constant _c -> acc
| Pair (speca, specb) ->
let acc = make_arities_dict speca acc in
let acc = make_arities_dict specb acc in
acc
| Map {spec; _} -> make_arities_dict spec acc
type error += Version : error
type error += Help : 'a command option -> error
let check_help_flag ?command =
let open Lwt_result_syntax in
function ("-h" | "--help") :: _ -> tzfail (Help command) | _ -> return_unit
let check_version_flag =
let open Lwt_result_syntax in
function
| "--version" :: _ -> tzfail Version
| _ -> return_unit
let add_occurrence long value acc =
StringMap.update
long
(function Some v -> Some (v @ [value]) | None -> Some [value])
acc
let make_args_dict_consume ?command spec args =
let open Lwt_result_syntax in
let rec make_args_dict completing arities acc args =
let* () = check_help_flag ?command args in
let* () = check_version_flag args in
match args with
| [] -> return (acc, [])
| arg :: tl ->
if String.length arg > 0 && arg.[0] = '-' then
match StringMap.find arg arities with
| Some (arity, long) -> (
let* () = check_help_flag ?command tl in
match (arity, tl) with
| 0, tl' ->
make_args_dict
completing
arities
(add_occurrence long "" acc)
tl'
| 1, value :: tl' ->
make_args_dict
completing
arities
(add_occurrence long value acc)
tl'
| 1, [] when completing -> return (acc, [])
| 1, [] -> tzfail (Option_expected_argument (arg, None))
| _, _ ->
Stdlib.failwith
"cli_entries: Arguments with arity not equal to 1 or 0 \
unsupported")
| None -> tzfail (Unknown_option (arg, None))
else return (acc, args)
in
make_args_dict
false
(make_arities_dict spec StringMap.empty)
StringMap.empty
args
let make_args_dict_filter ?command spec args =
let open Lwt_result_syntax in
let rec make_args_dict arities (dict, other_args) args =
let* () = check_help_flag ?command args in
match args with
| [] -> return (dict, other_args)
| arg :: tl -> (
match StringMap.find arg arities with
| Some (arity, long) -> (
let* () = check_help_flag ?command tl in
match (arity, tl) with
| 0, tl ->
make_args_dict
arities
(add_occurrence long "" dict, other_args)
tl
| 1, value :: tl' ->
make_args_dict
arities
(add_occurrence long value dict, other_args)
tl'
| 1, [] -> tzfail (Option_expected_argument (arg, command))
| _, _ ->
Stdlib.failwith
"cli_entries: Arguments with arity not equal to 1 or 0 \
unsupported")
| None -> make_args_dict arities (dict, arg :: other_args) tl)
in
let+ dict, remaining =
make_args_dict
(make_arities_dict spec StringMap.empty)
(StringMap.empty, [])
args
in
(dict, List.rev remaining)
let param ~name ~desc kind next = Param (name, desc, kind, next)
let seq_of_param param =
match param Stop with
| Param (n, desc, parameter, Stop) -> Seq (n, desc, parameter)
| _ -> invalid_arg "Tezos_clic.seq_of_param"
let non_terminal_seq ~suffix param next =
match (suffix, param Stop) with
| [], _ -> invalid_arg "Tezos_clic.non_terminal_seq: empty suffix"
| _, Param (n, desc, parameter, Stop) ->
NonTerminalSeq (n, desc, parameter, suffix, next)
| _ -> invalid_arg "Tezos_clic.non_terminal_seq"
let prefix keyword next = Prefix (keyword, next)
let rec fixed = function [] -> Stop | n :: r -> Prefix (n, fixed r)
let rec prefixes p next =
match p with [] -> next | n :: r -> Prefix (n, prefixes r next)
let stop = Stop
let no_options = Constant ()
let command ?group ~desc options params handler =
Command {params; options; handler; desc; group; conv = (fun x -> x)}
let string ~name ~desc next =
param
~name
~desc
{converter = (fun _ s -> Lwt.return_ok s); autocomplete = None}
next
let string_contains ~needle ~haystack =
Option.catch
~catch_only:(function Not_found -> true | _ -> false)
(fun () -> Re.Str.search_forward (Re.Str.regexp_string needle) haystack 0)
let rec search_params_prefix : type a arg. string -> (a, arg) params -> bool =
fun prefix -> function
| Prefix (keyword, next) -> (
match string_contains ~needle:prefix ~haystack:keyword with
| None -> search_params_prefix prefix next
| Some _ -> true)
| Param (_, _, _, next) -> search_params_prefix prefix next
| Stop -> false
| Seq _ -> false
| NonTerminalSeq (_, _, _, suffix, next) ->
List.exists
(fun keyword ->
match string_contains ~needle:prefix ~haystack:keyword with
| None -> false
| Some _ -> true)
suffix
|| search_params_prefix prefix next
let search_command keyword (Command {params; _}) =
search_params_prefix keyword params
let exec (type ctx)
(Command {options = options_spec; params = spec; handler; conv; _} as
command) (ctx : ctx) params args_dict =
let open Lwt_result_syntax in
let rec exec :
type ctx a.
int -> ctx -> (a, ctx) params -> a -> string list -> unit tzresult Lwt.t =
fun i ctx spec cb params ->
match (spec, params) with
| Stop, _ -> cb ctx
| Seq (_, _, {converter; _}), seq ->
let rec do_seq i acc = function
| [] -> return (List.rev acc)
| p :: rest ->
let* v =
Error_monad.catch_es (fun () -> converter ctx p)
|> trace (Bad_argument (i, p))
in
do_seq (succ i) (v :: acc) rest
in
let* parsed = do_seq i [] seq in
cb parsed ctx
| NonTerminalSeq (_, _, {converter; _}, suffix, next), seq ->
let rec do_seq i acc = function
| [] -> return (List.rev acc, [])
| p :: rest as params ->
let rec match_suffix = function
| param :: params, suffix :: suffixes when param = suffix ->
match_suffix (params, suffixes)
| params, [] ->
(params, true)
| _, _ -> (params, false)
in
let unmatched_rest, matched = match_suffix (params, suffix) in
if matched then return (List.rev acc, unmatched_rest)
else
Error_monad.catch_es (fun () ->
let* v = converter ctx p in
do_seq (succ i) (v :: acc) rest)
in
let* parsed, rest = do_seq i [] seq in
exec (succ i) ctx next (cb parsed) rest
| Prefix (n, next), p :: rest when n = p -> exec (succ i) ctx next cb rest
| Param (_, _, {converter; _}, next), p :: rest ->
let* v =
Error_monad.catch_es (fun () -> converter ctx p)
|> trace (Bad_argument (i, p))
in
exec (succ i) ctx next (cb v) rest
| _ -> Stdlib.failwith "cli_entries internal error: exec no case matched"
in
let ctx = conv ctx in
let* parsed_options = parse_arg ~command options_spec args_dict ctx in
exec 1 ctx spec (handler parsed_options) params
[@@@ocaml.warning "-30"]
type 'arg level = {
stop : 'arg command option;
prefix : (string * 'arg tree) list;
}
and 'arg param_level = {
stop : 'arg command option;
autocomplete : ('arg -> string list tzresult Lwt.t) option;
tree : 'arg tree;
}
and 'arg non_terminal_seq_level = {
stop : 'arg command option;
autocomplete : ('arg -> string list tzresult Lwt.t) option;
tree : 'arg tree;
name : string;
desc : string;
suffix : string list;
}
and 'ctx tree =
| TPrefix : 'ctx level -> 'ctx tree
| TParam : 'ctx param_level -> 'ctx tree
| TStop : 'ctx command -> 'ctx tree
| TSeq :
'ctx command * ('ctx -> string list tzresult Lwt.t) option
-> 'ctx tree
| TNonTerminalSeq : 'ctx non_terminal_seq_level -> 'ctx tree
| TEmpty : 'ctx tree
let insert_in_dispatch_tree : type ctx. ctx tree -> ctx command -> ctx tree =
fun root (Command {params; conv; _} as command) ->
let rec insert_tree :
type a ictx. (ctx -> ictx) -> ctx tree -> (a, ictx) params -> ctx tree =
fun conv t c ->
let insert_tree t c = insert_tree conv t c in
let rec suffix_to_params suffix next =
match suffix with
| suffix :: suffixes -> Prefix (suffix, suffix_to_params suffixes next)
| [] -> next
in
let suffix_to_tree suffix next =
insert_tree TEmpty (suffix_to_params suffix next)
in
let conv_autocomplete = Option.map (fun a c -> a (conv c)) in
match (t, c) with
| TEmpty, Stop -> TStop command
| TEmpty, Seq (_, _, {autocomplete; _}) ->
TSeq (command, conv_autocomplete autocomplete)
| TEmpty, Param (_, _, {autocomplete; _}, next) ->
let autocomplete = conv_autocomplete autocomplete in
TParam {tree = insert_tree TEmpty next; stop = None; autocomplete}
| TEmpty, NonTerminalSeq (name, desc, {autocomplete; _}, suffix, next) ->
let autocomplete = conv_autocomplete autocomplete in
let tree = suffix_to_tree suffix next in
TNonTerminalSeq {stop = None; tree; autocomplete; suffix; name; desc}
| TEmpty, Prefix (n, next) ->
TPrefix {stop = None; prefix = [(n, insert_tree TEmpty next)]}
| TStop cmd, Param (_, _, {autocomplete; _}, next) ->
let autocomplete = conv_autocomplete autocomplete in
TParam {tree = insert_tree TEmpty next; stop = Some cmd; autocomplete}
| TStop cmd, Prefix (n, next) ->
TPrefix {stop = Some cmd; prefix = [(n, insert_tree TEmpty next)]}
| TStop cmd, NonTerminalSeq (name, desc, {autocomplete; _}, suffix, next) ->
let autocomplete = conv_autocomplete autocomplete in
let tree = suffix_to_tree suffix next in
TNonTerminalSeq
{stop = Some cmd; tree; autocomplete; suffix; name; desc}
| TParam t, Param (_, _, _, next) ->
TParam {t with tree = insert_tree t.tree next}
| TPrefix ({prefix; _} as l), Prefix (n, next) ->
let rec insert_prefix = function
| [] -> [(n, insert_tree TEmpty next)]
| (n', t) :: rest when n = n' -> (n, insert_tree t next) :: rest
| item :: rest -> item :: insert_prefix rest
in
TPrefix {l with prefix = insert_prefix prefix}
| TPrefix ({stop = None; _} as l), Stop ->
TPrefix {l with stop = Some command}
| TParam ({stop = None; _} as l), Stop ->
TParam {l with stop = Some command}
| TParam t, Prefix (_n, next) ->
TParam {t with tree = insert_tree t.tree next}
| TNonTerminalSeq t, NonTerminalSeq (n, desc, _, suffix, next) ->
if
n <> t.name || desc <> t.desc || t.suffix <> suffix
then
Stdlib.failwith
"Command cannot have different non_terminal_seq_level at the same \
position"
else
let params = suffix_to_params suffix next in
TNonTerminalSeq {t with tree = insert_tree t.tree params}
| _, _ ->
Stdlib.failwith
(Format.asprintf
"Tezos_clic.Command_tree.insert: conflicting commands \"%a\""
(fun ppf (Command {params; options; _}) ->
print_commandline ppf ([], options, params))
command)
in
insert_tree conv root params
let make_dispatch_tree commands =
List.fold_left insert_in_dispatch_tree TEmpty commands
let rec gather_commands ?(acc = []) tree =
match tree with
| TEmpty -> acc
| TSeq (c, _) | TStop c -> c :: acc
| TPrefix {stop; prefix} ->
gather_assoc
~acc:(match stop with None -> acc | Some c -> c :: acc)
prefix
| TParam {tree; stop; _} | TNonTerminalSeq {tree; stop; _} ->
gather_commands
tree
~acc:(match stop with None -> acc | Some c -> c :: acc)
and gather_assoc ?(acc = []) trees =
List.fold_left (fun acc (_, tree) -> gather_commands tree ~acc) acc trees
let find_command tree initial_arguments =
let open Lwt_result_syntax in
let is_short_option s =
String.length s = 2
&& s.[0] = '-'
&& match s.[1] with 'a' .. 'z' | 'A' .. 'Z' -> true | _ -> false
in
let is_long_option s = String.length s >= 2 && s.[0] = '-' && s.[1] = '-' in
let is_option s = is_short_option s || is_long_option s in
let rec traverse tree arguments acc =
match (tree, arguments) with
| ( ( TStop _ | TSeq _
| TNonTerminalSeq {stop = Some _; _}
| TPrefix {stop = Some _; _}
| TParam {stop = Some _; _} ),
("-h" | "--help") :: _ ) -> (
match gather_commands tree with
| [] -> assert false
| [command] -> tzfail (Help (Some command))
| more -> tzfail (Unterminated_command (initial_arguments, more)))
| TStop c, [] -> return (c, empty_args_dict, initial_arguments)
| TStop (Command {options; _} as command), remaining -> (
let* args_dict, unparsed =
make_args_dict_filter ~command options remaining
in
match unparsed with
| [] -> return (command, args_dict, initial_arguments)
| hd :: _ ->
if String.length hd > 0 && hd.[0] = '-' then
tzfail (Unknown_option (hd, Some command))
else tzfail (Extra_arguments (unparsed, command)))
| TSeq ((Command {options; _} as command), _), remaining ->
if
List.exists
(function "-h" | "--help" -> true | _ -> false)
remaining
then tzfail (Help (Some command))
else
let+ dict, remaining =
make_args_dict_filter ~command options remaining
in
(command, dict, List.rev_append acc remaining)
| TNonTerminalSeq {stop = None; _}, ([] | ("-h" | "--help") :: _) ->
tzfail (Unterminated_command (initial_arguments, gather_commands tree))
| TNonTerminalSeq {stop = Some c; _}, [] ->
return (c, empty_args_dict, initial_arguments)
| ( (TNonTerminalSeq {tree; suffix; _} as nts),
(parameter :: arguments' as remaining) ) ->
let rec match_suffix matched_acc = function
| param :: params, suffix :: suffixes when param = suffix ->
match_suffix (param :: matched_acc) (params, suffixes)
| _, [] ->
true
| _, _ -> false
in
let matched = match_suffix [] (remaining, suffix) in
if matched then
traverse tree remaining acc
else
traverse nts arguments' (parameter :: acc)
| TPrefix {stop = Some cmd; _}, [] ->
return (cmd, empty_args_dict, initial_arguments)
| TPrefix {stop = None; prefix}, ([] | ("-h" | "--help") :: _) ->
tzfail (Unterminated_command (initial_arguments, gather_assoc prefix))
| TPrefix {prefix; _}, hd_arg :: tl -> (
match List.assoc ~equal:String.equal hd_arg prefix with
| None -> tzfail (Command_not_found (List.rev acc, gather_assoc prefix))
| Some tree' -> traverse tree' tl (hd_arg :: acc))
| TParam {stop = None; _}, ([] | ("-h" | "--help") :: _) ->
tzfail (Unterminated_command (initial_arguments, gather_commands tree))
| TParam {stop = Some c; _}, hd :: _ when is_option hd ->
traverse (TStop c) arguments acc
| TParam {stop = Some c; _}, [] ->
return (c, empty_args_dict, initial_arguments)
| TParam {tree; _}, parameter :: arguments' ->
traverse tree arguments' (parameter :: acc)
| TEmpty, _ -> tzfail (Command_not_found (List.rev acc, []))
in
traverse tree initial_arguments []
let get_arg {long; short} =
("--" ^ long)
:: (match short with None -> [] | Some c -> ["-" ^ String.make 1 c])
let rec list_args : type a ctx. (a, ctx) arg -> string list = function
| Constant _ -> []
| Arg {label; _}
| MultipleArg {label; _}
| DefArg {label; _}
| Switch {label; _} ->
get_arg label
| Pair (speca, specb) -> list_args speca @ list_args specb
| Map {spec; _} -> list_args spec
let complete_func autocomplete cctxt =
let open Lwt_result_syntax in
match autocomplete with
| None -> return_nil
| Some autocomplete -> autocomplete cctxt
let list_command_args (Command {options; _}) = list_args options
let rec remaining_spec : type a ctx. StringSet.t -> (a, ctx) arg -> string list
=
fun seen -> function
| Constant _ -> []
| Arg {label; _}
| MultipleArg {label; _}
| DefArg {label; _}
| Switch {label; _} ->
if StringSet.mem label.long seen then [] else get_arg label
| Pair (speca, specb) -> remaining_spec seen speca @ remaining_spec seen specb
| Map {spec; _} -> remaining_spec seen spec
let complete_options (type ctx) continuation args args_spec ind (ctx : ctx) =
let arities = make_arities_dict args_spec StringMap.empty in
let rec complete_spec :
type a. string -> (a, ctx) arg -> string list option tzresult Lwt.t =
fun name ->
let open Lwt_result_syntax in
function
| Constant _ -> return_none
| DefArg {kind = {autocomplete; _}; label; _}
| Arg {kind = {autocomplete; _}; label; _}
when label.long = name ->
let* p = complete_func autocomplete ctx in
return_some p
| MultipleArg {kind = {autocomplete; _}; label; _} when label.long = name ->
let* p = complete_func autocomplete ctx in
return_some p
| Switch {label; _} when label.long = name -> return_some []
| Arg _ | MultipleArg _ | DefArg _ | Switch _ -> return_none
| Pair (speca, specb) -> (
let* resa = complete_spec name speca in
match resa with
| Some _ -> return resa
| None -> complete_spec name specb)
| Map {spec; _} -> complete_spec name spec
in
let rec help args ind seen =
let open Lwt_result_syntax in
match args with
| _ when ind = 0 ->
let+ cont_args = continuation args 0 in
cont_args @ remaining_spec seen args_spec
| [] -> Stdlib.failwith "cli_entries internal autocomplete error"
| arg :: tl -> (
match StringMap.find arg arities with
| Some (arity, long) -> (
let seen = StringSet.add long seen in
match (arity, tl) with
| 0, args when ind = 0 ->
let+ cont_args = continuation args 0 in
remaining_spec seen args_spec @ cont_args
| 0, args -> help args (ind - 1) seen
| 1, _ when ind = 1 ->
let* res = complete_spec arg args_spec in
return (Option.value ~default:[] res)
| 1, _ :: tl -> help tl (ind - 2) seen
| _ -> Stdlib.failwith "cli_entries internal error, invalid arity")
| None -> continuation args ind)
in
help args ind StringSet.empty
let complete_next_tree cctxt =
let open Lwt_result_syntax in
function
| TPrefix {stop; prefix} ->
return
((match stop with
| None -> []
| Some command -> list_command_args command)
@ List.map fst prefix)
| TSeq (command, autocomplete) ->
let+ completions = complete_func autocomplete cctxt in
completions @ list_command_args command
| TNonTerminalSeq {autocomplete; suffix; _} ->
let+ completions = complete_func autocomplete cctxt in
completions @ [WithExceptions.Option.get ~loc:__LOC__ @@ List.hd suffix]
| TParam {autocomplete; _} -> complete_func autocomplete cctxt
| TStop command -> return (list_command_args command)
| TEmpty -> return_nil
let rec args_starting_from_suffix original_suffix ind matched_args = function
| (s :: s_rest as suffix), a :: a_rest ->
if s = a then
args_starting_from_suffix
original_suffix
ind
(matched_args @ [a])
(s_rest, a_rest)
else if matched_args = [] then
args_starting_from_suffix
original_suffix
(ind - 1)
matched_args
(suffix, a_rest)
else
None
| unmatched_suffix, args
when Compare.List_lengths.(unmatched_suffix < original_suffix) ->
Some (matched_args @ args, ind)
| _ -> None
let complete_tree cctxt tree index args =
let rec help tree args ind =
let open Lwt_result_syntax in
if ind = 0 then complete_next_tree cctxt tree
else
match (tree, args) with
| TSeq _, _ -> complete_next_tree cctxt tree
| (TNonTerminalSeq {tree; suffix; _} as this_tree), _ :: _tl -> (
match args_starting_from_suffix suffix ind [] (suffix, args) with
| Some (args, ind) -> help tree args ind
| _ -> complete_next_tree cctxt this_tree)
| TPrefix {prefix; _}, hd :: tl -> (
match List.assoc ~equal:String.equal hd prefix with
| None -> return_nil
| Some p -> help p tl (ind - 1))
| TParam {tree; _}, _ :: tl -> help tree tl (ind - 1)
| TStop (Command {options; conv; _}), args ->
complete_options (fun _ _ -> return_nil) args options ind (conv cctxt)
| (TParam _ | TPrefix _ | TNonTerminalSeq _), [] | TEmpty, _ -> return_nil
in
help tree args index
let autocompletion ~script ~cur_arg ~prev_arg ~args ~global_options commands
cctxt =
let open Lwt_result_syntax in
let tree = make_dispatch_tree commands in
let rec ind n = function
| [] -> None
| hd :: tl ->
if hd = prev_arg then
Some (Option.value ~default:(n + 1) (ind (n + 1) tl))
else ind (n + 1) tl
in
let+ completions =
if prev_arg = script then
let+ command_completions = complete_next_tree cctxt tree in
list_args global_options @ command_completions
else
match ind 0 args with
| None -> return_nil
| Some index ->
complete_options
(fun args ind -> complete_tree cctxt tree ind args)
args
global_options
index
cctxt
in
List.filter
(fun completion ->
Re.Str.(string_match (regexp_string cur_arg) completion 0))
completions
let parse_global_options global_options ctx args =
let open Lwt_result_syntax in
let* dict, remaining = make_args_dict_consume global_options args in
let* nested = parse_arg global_options dict ctx in
return (nested, remaining)
let dispatch commands ctx args =
let open Lwt_result_syntax in
let tree = make_dispatch_tree commands in
match args with
| []
when match tree with
| TPrefix {stop; _} -> stop = None
| TParam {stop; _} -> stop = None
| TStop _ -> false
| TSeq (_, _) -> false
| TNonTerminalSeq {stop; _} -> stop = None
| TEmpty -> true ->
tzfail (Help None)
| [("-h" | "--help")] -> tzfail (Help None)
| _ ->
let* command, args_dict, filtered_args = find_command tree args in
exec command ctx filtered_args args_dict
type error += No_manual_entry of string list
let manual_group = {name = "man"; title = "Access the documentation"}
let add_manual ~executable_name ~global_options format ppf commands =
let rec with_manual =
lazy
(commands
@ [
command
~group:manual_group
~desc:
"Print documentation of commands.\n\
Add search keywords to narrow list.\n\
Will display only the commands by default, unless [-verbosity \
<2|3>] is passed or the list of matching commands if less than \
3."
(args2
(arg
~doc:
"level of details\n\
0. Only shows command mnemonics, without documentation.\n\
1. Shows command mnemonics with short descriptions.\n\
2. Show commands and arguments with short descriptions\n\
3. Show everything"
~long:"verbosity"
~short:'v'
~placeholder:"0|1|2|3"
(parameter
~autocomplete:(fun _ -> Lwt.return_ok ["0"; "1"; "2"; "3"])
(fun _ arg ->
let open Lwt_result_syntax in
match arg with
| "0" -> return Terse
| "1" -> return Short
| "2" -> return Details
| "3" -> return Full
| _ -> failwith "Level of details out of range")))
(default_arg
~doc:"the manual's output format"
~placeholder:"plain|colors|html"
~long:"format"
~default:
(match format with
| Ansi -> "colors"
| Plain -> "plain"
| Html -> "html")
(parameter
~autocomplete:(fun _ ->
Lwt.return_ok ["colors"; "plain"; "html"])
(fun _ arg ->
let open Lwt_result_syntax in
match arg with
| "colors" -> return Ansi
| "plain" -> return Plain
| "html" -> return Html
| _ -> failwith "Unknown manual format"))))
(prefix
"man"
(seq_of_param
(string
~name:"keyword"
~desc:
"keyword to search for\n\
If several are given they must all appear in the \
command.")))
(fun (verbosity, format) keywords _ ->
let commands =
List.fold_left
(fun commands keyword ->
List.filter (search_command keyword) commands)
(Lazy.force with_manual)
keywords
in
let verbosity =
match verbosity with
| Some verbosity -> verbosity
| None when Compare.List_length_with.(commands <= 3) -> Full
| None -> Short
in
let open Lwt_result_syntax in
match commands with
| [] -> tzfail (No_manual_entry keywords)
| _ ->
let state = setup_formatter ppf format verbosity in
let commands = List.map (fun c -> Ex c) commands in
usage_internal
ppf
~executable_name
~global_options
~highlights:keywords
commands ;
restore_formatter ppf state ;
return_unit);
])
in
Lazy.force with_manual
let pp_cli_errors ppf ~executable_name ~global_options ~default errs =
let pp_one = function
| Bad_argument (i, v) ->
Format.fprintf ppf "Erroneous command line argument %d (%s)." i v ;
Some []
| Option_expected_argument (arg, command) ->
Format.fprintf
ppf
"Command line option @{<opt>%s@} expects an argument."
arg ;
Some (Option.fold ~some:(fun command -> [Ex command]) ~none:[] command)
| Bad_option_argument (arg, command) ->
Format.fprintf
ppf
"Wrong value for command line option @{<opt>%s@}."
arg ;
Some (Option.fold ~some:(fun command -> [Ex command]) ~none:[] command)
| Multiple_occurrences (arg, command) ->
Format.fprintf
ppf
"Command line option @{<opt>%s@} appears multiple times."
arg ;
Some (Option.fold ~some:(fun command -> [Ex command]) ~none:[] command)
| No_manual_entry [keyword] ->
Format.fprintf ppf "No manual entry that match @{<hilight>%s@}." keyword ;
Some []
| No_manual_entry (keyword :: keywords) ->
Format.fprintf
ppf
"No manual entry that match %a and @{<hilight>%s@}."
(Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf ", ")
(fun ppf keyword -> Format.fprintf ppf "@{<hilight>%s@}" keyword))
keywords
keyword ;
Some []
| Unknown_option (option, command) ->
Format.fprintf ppf "Unexpected command line option @{<opt>%s@}." option ;
Some (Option.fold ~some:(fun command -> [Ex command]) ~none:[] command)
| Extra_arguments (, command) ->
Format.(
fprintf
ppf
"Extra command line arguments:@, @[<h>%a@]."
(pp_print_list ~pp_sep:pp_print_space pp_print_string)
extra) ;
Some [Ex command]
| Unterminated_command (_, commands) ->
Format.fprintf
ppf
"@[<v 2>Unterminated command, here are possible completions.@,%a@]"
(Format.pp_print_list (fun ppf (Command {params; options; _}) ->
print_commandline ppf ([], options, params)))
commands ;
Some (List.map (fun c -> Ex c) commands)
| Command_not_found ([], _all_commands) ->
Format.fprintf
ppf
"@[<v 0>Unrecognized command.@,\
Try using the @{<kwd>man@} command to get more information.@]" ;
Some []
| Command_not_found (_, commands) ->
Format.fprintf
ppf
"@[<v 0>Unrecognized command.@,\
Did you mean one of the following?@,\
\ @[<v 0>%a@]@]"
(Format.pp_print_list (fun ppf (Command {params; options; _}) ->
print_commandline ppf ([], options, params)))
commands ;
Some (List.map (fun c -> Ex c) commands)
| err ->
default ppf err ;
None
in
let rec pp acc errs =
let return command =
match (command, acc) with
| None, _ -> acc
| Some command, Some commands -> Some (command @ commands)
| Some command, None -> Some command
in
match errs with
| [] -> None
| [last] -> return (pp_one last)
| err :: errs ->
let acc = return (pp_one err) in
Format.fprintf ppf "@," ;
pp acc errs
in
Format.fprintf ppf "@[<v 2>@{<error>@{<title>Error@}@}@," ;
match pp None errs with
| None -> Format.fprintf ppf "@]@\n"
| Some commands ->
Format.fprintf
ppf
"@]@\n@\n@[<v 0>%a@]"
(fun ppf commands ->
usage_internal ppf ~executable_name ~global_options commands)
commands
let usage ppf ~executable_name ~global_options commands =
usage_internal
ppf
~executable_name
~global_options
(List.map (fun c -> Ex c) commands)
let map_command f (Command c) = Command {c with conv = (fun x -> c.conv (f x))}