forked from ocaml/opam
/
opamArg.ml
1648 lines (1560 loc) · 66.8 KB
/
opamArg.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
(**************************************************************************)
(* *)
(* Copyright 2012-2013 OCamlPro *)
(* Copyright 2012 INRIA *)
(* *)
(* All rights reserved.This file is distributed under the terms of the *)
(* GNU Lesser General Public License version 3.0 with linking *)
(* exception. *)
(* *)
(* OPAM is distributed in the hope that it will be useful, but WITHOUT *)
(* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public *)
(* License for more details. *)
(* *)
(**************************************************************************)
open OpamTypes
open OpamTypesBase
open Cmdliner
(* Global options *)
type global_options = {
debug : bool;
debug_level: int;
verbose: bool;
quiet : bool;
color : bool;
switch : string option;
yes : bool;
strict : bool;
root : dirname;
no_base_packages: bool;
git_version : bool;
compat_mode_1_0 : bool;
external_solver : string option;
use_internal_solver : bool;
cudf_file : string option;
solver_preferences : string option;
no_self_upgrade : bool;
}
let self_upgrade_exe opamroot =
OpamFilename.OP.(opamroot // "opam", opamroot // "opam.version")
let switch_to_updated_self debug opamroot =
let updated_self, updated_self_version = self_upgrade_exe opamroot in
let updated_self_str = OpamFilename.to_string updated_self in
let updated_self_version_str = OpamFilename.to_string updated_self_version in
if updated_self_str <> Sys.executable_name &&
OpamFilename.exists updated_self &&
OpamFilename.is_exec updated_self &&
OpamFilename.exists updated_self_version
then
let no_version = OpamVersion.of_string "" in
let update_version =
try
let s = OpamSystem.read updated_self_version_str in
let s =
let len = String.length s in if len > 0 && s.[len-1] = '\n'
then String.sub s 0 (len-1) else s in
OpamVersion.of_string s
with e -> OpamMisc.fatal e; no_version in
if update_version = no_version then
OpamGlobals.error "%s exists but cannot be read, disabling self-upgrade."
updated_self_version_str
else if OpamVersion.compare update_version OpamVersion.current <= 0 then
OpamGlobals.warning "Obsolete OPAM self-upgrade package v.%s found, \
not using it (current system version is %s)."
(OpamVersion.to_string update_version)
(OpamVersion.to_string OpamVersion.current)
else (
if OpamVersion.git <> None then
OpamGlobals.warning "Using OPAM self-upgrade to %s while the system \
OPAM is a development version (%s)"
(OpamVersion.to_string update_version)
(OpamVersion.to_string OpamVersion.full);
(if debug || !OpamGlobals.debug then
Printf.eprintf "!! %s found, switching to it !!\n%!" updated_self_str;
let env =
Array.append
[|"OPAMNOSELFUPGRADE="^OpamGlobals.self_upgrade_bootstrapping_value|]
(Unix.environment ()) in
try
Unix.execve updated_self_str Sys.argv env
with e ->
OpamMisc.fatal e;
OpamGlobals.error
"Could'nt run the upgraded opam %s found at %s. \
Continuing with %s from the system."
(OpamVersion.to_string update_version)
updated_self_str
(OpamVersion.to_string OpamVersion.current)))
let create_global_options
git_version debug_level verbose quiet color switch yes strict root
no_base_packages compat_mode_1_0 external_solver use_internal_solver cudf_file solver_preferences
no_self_upgrade =
let debug = debug_level > 0 in
if not (no_self_upgrade) then
switch_to_updated_self debug root; (* do this asap, don't waste time *)
{ git_version; debug; debug_level; verbose; quiet; color; switch; yes; strict; root;
no_base_packages; compat_mode_1_0; external_solver; use_internal_solver; cudf_file; solver_preferences;
no_self_upgrade; }
let apply_global_options o =
if o.git_version then (
begin match OpamGitVersion.version with
| None -> ()
| Some v -> OpamGlobals.msg "%s\n%!" v
end;
exit 0
);
OpamGlobals.debug := !OpamGlobals.debug || o.debug;
OpamGlobals.debug_level := max !OpamGlobals.debug_level o.debug_level;
OpamMisc.debug := !OpamGlobals.debug;
OpamGlobals.verbose := (not o.quiet) && (!OpamGlobals.verbose || o.verbose);
OpamGlobals.color := !OpamGlobals.color || o.color;
begin match o.switch with
| None -> ()
| Some s -> OpamGlobals.switch := `Command_line s
end;
OpamGlobals.root_dir := OpamFilename.Dir.to_string o.root;
OpamGlobals.yes := !OpamGlobals.yes || o.yes;
OpamGlobals.strict := !OpamGlobals.strict || o.strict;
OpamGlobals.no_base_packages := !OpamGlobals.no_base_packages || o.no_base_packages;
OpamGlobals.compat_mode_1_0 := !OpamGlobals.compat_mode_1_0 || o.compat_mode_1_0;
OpamGlobals.external_solver := begin match o.external_solver with None -> !OpamGlobals.external_solver | Some v -> v end;
OpamGlobals.use_external_solver :=
!OpamGlobals.use_external_solver && not o.use_internal_solver;
OpamGlobals.cudf_file := o.cudf_file;
OpamGlobals.no_self_upgrade := !OpamGlobals.no_self_upgrade || o.no_self_upgrade;
match o.solver_preferences with
| None -> ()
| Some prefs ->
OpamGlobals.solver_preferences := prefs;
OpamGlobals.solver_upgrade_preferences := prefs
(* Build options *)
type build_options = {
keep_build_dir: bool;
make : string option;
no_checksums : bool;
build_test : bool;
build_doc : bool;
show : bool;
dryrun : bool;
fake : bool;
external_tags : string list;
jobs : int option;
json : string option;
}
let create_build_options
keep_build_dir make no_checksums build_test
build_doc show dryrun external_tags fake
jobs json = {
keep_build_dir; make; no_checksums;
build_test; build_doc; show; dryrun; external_tags;
fake; jobs; json
}
let json_update = function
| None -> ()
| Some f ->
let write str = OpamFilename.write (OpamFilename.of_string f) str in
OpamJson.set_output write
let apply_build_options b =
OpamGlobals.keep_build_dir := !OpamGlobals.keep_build_dir || b.keep_build_dir;
OpamGlobals.no_checksums := !OpamGlobals.no_checksums || b.no_checksums;
OpamGlobals.build_test := !OpamGlobals.build_test || b.build_test;
OpamGlobals.build_doc := !OpamGlobals.build_doc || b.build_doc;
OpamGlobals.show := !OpamGlobals.show || b.show;
OpamGlobals.dryrun := !OpamGlobals.dryrun || b.dryrun;
OpamGlobals.external_tags := b.external_tags;
OpamGlobals.fake := b.fake;
json_update b.json;
OpamGlobals.jobs :=
begin match b.jobs with
| None -> !OpamGlobals.jobs
| Some j -> Some j
end;
match b.make with
| None -> ()
| Some s -> OpamGlobals.makecmd := (fun () -> s)
(* Help sections common to all commands *)
let global_option_section = "COMMON OPTIONS"
let help_sections = [
`S global_option_section;
`P "These options are common to all commands.";
`S "ENVIRONMENT VARIABLES";
`P "OPAM makes use of the environment variables listed here. Boolean \
variables are considered true when set to a non-empty string.";
(* Alphabetical order *)
`P "$(i,OPAMCOLOR), when set to $(i,always) or $(i,never), sets a default \
value for the --color option.";
`P ("$(i,OPAMCRITERIA) specifies user $(i,preferences) for dependency solving.\
The default value is "^OpamGlobals.default_preferences^". \
See also option --criteria");
`P "$(i,OPAMCURL) can be used to define an alternative for the 'curl' \
command-line utility to download files.";
`P "$(i,OPAMDEBUG) see option `--debug'.";
`P "$(i,OPAMEXTERNALSOLVER) see option `--solver'.";
`P "$(i,OPAMJOBS) sets the maximum number of parallel workers to run.";
`P "$(i,OPAMNOASPCUD) see option `--no-aspcud'.";
`P "$(i,OPAMNOSELFUPGRADE) see option `--no-self-upgrade'.";
`P "$(i,OPAMROOT) see option `--root'. This is automatically set by \
`opam config env --root=DIR' when DIR is non-default.";
`P "$(i,OPAMSOLVERTIMEOUT) change the time allowance of the internal solver.";
`P "$(i,OPAMSWITCH) see option `--switch'. Automatically set by \
`opam config env --switch=SWITCH'.";
`P ("$(i,OPAMUPGRADECRITERIA) specifies user $(i,preferences) for dependency solving \
when performing an upgrade. Overrides $(i,OPAMCRITERIA) in upgrades if both are set.\
The default value is "^OpamGlobals.default_upgrade_preferences^". \
See also option --criteria");
`P "$(i,OPAMUTF8MSGS) use nice UTF8 characters in OPAM messages.";
`P "$(i,OPAMVERBOSE) see option `--verbose'.";
`P "$(i,OPAMVAR_var) overrides the contents of the variable $(i,var) when \
substituting `%{var}%` strings in `opam` files.";
`P "$(i,OPAMVAR_package_var) overrides the contents of the variable \
$(i,package:var) when substituting `%{package:var}%` strings in \
`opam` files.";
`P "$(i,OPAMUSEINTERNALSOLVER) see option `--use-internal-solver'.";
`P "$(i,OPAMYES) see option `--yes'.";
`S "FURTHER DOCUMENTATION";
`P (Printf.sprintf "See %s." OpamGlobals.default_repository_address);
`S "AUTHORS";
`P "Thomas Gazagnaire <thomas@gazagnaire.org>"; `Noblank;
`P "Anil Madhavapeddy <anil@recoil.org>"; `Noblank;
`P "Fabrice Le Fessant <Fabrice.Le_fessant@inria.fr>"; `Noblank;
`P "Frederic Tuong <tuong@users.gforge.inria.fr>"; `Noblank;
`P "Louis Gesbert <louis.gesbert@ocamlpro.com>"; `Noblank;
`P "Vincent Bernardoff <vb@luminar.eu.org>"; `Noblank;
`P "Guillem Rieu <guillem.rieu@ocamlpro.com>";
`S "BUGS";
`P "Check bug reports at https://github.com/ocaml/opam/issues.";
]
(* Converters *)
let pr_str = Format.pp_print_string
let repository_name =
let parse str = `Ok (OpamRepositoryName.of_string str) in
let print ppf name = pr_str ppf (OpamRepositoryName.to_string name) in
parse, print
let address =
let parse str = `Ok (address_of_string str) in
let print ppf address = pr_str ppf (string_of_address address) in
parse, print
let filename =
let parse str = `Ok (OpamFilename.of_string str) in
let print ppf filename = pr_str ppf (OpamFilename.to_string filename) in
parse, print
let dirname =
let parse str = `Ok (OpamFilename.Dir.of_string str) in
let print ppf dir = pr_str ppf (OpamFilename.prettify_dir dir) in
parse, print
let compiler =
let parse str = `Ok (OpamCompiler.of_string str) in
let print ppf comp = pr_str ppf (OpamCompiler.to_string comp) in
parse, print
let package_name =
let parse str = `Ok (OpamPackage.Name.of_string str) in
let print ppf pkg = pr_str ppf (OpamPackage.Name.to_string pkg) in
parse, print
(* name * version option *)
let package =
let parse str =
let re = Re_str.regexp "\\([^>=<.!]+\\)\\(\\.\\(.+\\)\\)?" in
try
if not (Re_str.string_match re str 0) then failwith "bad_format";
let name =
OpamPackage.Name.of_string (Re_str.matched_group 1 str) in
let version_opt =
try Some (OpamPackage.Version.of_string (Re_str.matched_group 3 str))
with Not_found -> None in
`Ok (name, version_opt)
with Failure _ -> `Error "bad package format"
in
let print ppf (name, version_opt) =
match version_opt with
| None -> pr_str ppf (OpamPackage.Name.to_string name)
| Some v -> pr_str ppf (OpamPackage.Name.to_string name ^"."^
OpamPackage.Version.to_string v)
in
parse, print
(* name * version constraint *)
let atom =
let parse str =
let re = Re_str.regexp "\\([^>=<.!]+\\)\\(>=?\\|<=?\\|=\\|\\.\\|!=\\)\\(.*\\)" in
try
if not (Re_str.string_match re str 0) then failwith "no_version";
let sname = Re_str.matched_group 1 str in
let sop = Re_str.matched_group 2 str in
let sversion = Re_str.matched_group 3 str in
let name = OpamPackage.Name.of_string sname in
let sop = if sop = "." then "=" else sop in
let op = OpamFormula.relop_of_string sop in (* may raise Invalid_argument *)
let version = OpamPackage.Version.of_string sversion in
`Ok (name, Some (op, version))
with Failure _ | Invalid_argument _ ->
`Ok (OpamPackage.Name.of_string str, None)
in
let print ppf atom =
pr_str ppf (OpamFormula.short_string_of_atom atom) in
parse, print
let enum_with_default sl: 'a Arg.converter =
let parse, print = Arg.enum sl in
let parse s =
match parse s with
| `Ok _ as x -> x
| _ -> `Ok (`default s) in
parse, print
(* Helpers *)
let mk_flag ?section flags doc =
let doc = Arg.info ?docs:section ~doc flags in
Arg.(value & flag & doc)
let mk_opt ?section ?vopt flags value doc conv default =
let doc = Arg.info ?docs:section ~docv:value ~doc flags in
Arg.(value & opt ?vopt conv default & doc)
let mk_tristate_opt ?section flags value doc auto default =
let doc = Arg.info ?docs:section ~docv:value ~doc flags in
let choices =
Arg.enum [ "always", `Always; "never", `Never; "auto", `Auto ] in
let arg = Arg.(value & opt choices default & doc) in
let to_bool = function
| `Always -> true
| `Never -> false
| `Auto -> auto ()
in
Term.(pure to_bool $ arg)
let mk_subdoc ?(defaults=[]) commands =
let bold s = Printf.sprintf "$(b,%s)" s in
let it s = Printf.sprintf "$(i,%s)" s in
`S "COMMANDS" ::
(List.map (function
| "", name ->
`P (Printf.sprintf "Without argument, defaults to %s."
(bold name))
| arg, default ->
`I (it arg, Printf.sprintf "With a %s argument, defaults to %s %s."
(it arg) (bold default) (it arg))
) defaults) @
List.map (fun (cs,_,args,d) ->
let cmds = String.concat ", " (List.map bold cs) ^ " " ^
String.concat " " (List.map it args) in
`I (cmds, d)
) commands @
[`S "OPTIONS"] (* Ensures options get after commands *)
let mk_subcommands_aux my_enum commands =
let command =
let doc = Arg.info ~docv:"COMMAND" [] in
let commands =
List.fold_left
(fun acc (cs,f,_,_) -> List.map (fun c -> c,f) cs @ acc)
[] commands in
Arg.(value & pos 0 (some & my_enum commands) None & doc) in
let params =
let doc = Arg.info ~doc:"Optional parameters." [] in
Arg.(value & pos_right 0 string [] & doc) in
command, params
let mk_subcommands commands =
mk_subcommands_aux Arg.enum commands
let mk_subcommands_with_default commands =
mk_subcommands_aux enum_with_default commands
let bad_subcommand command subcommands usersubcommand userparams =
match usersubcommand with
| None ->
`Error (false, Printf.sprintf "Missing subcommand. Valid subcommands are %s."
(OpamMisc.pretty_list
(List.flatten (List.map (fun (a,_,_,_) -> a) subcommands))))
| Some usersubcommand ->
let name, args =
match List.find (fun (_,cmd,_,_) -> cmd = usersubcommand) subcommands with
| name::_, _, args, _doc -> name, args
| _ -> assert false
in
let exe = Filename.basename Sys.executable_name in
let usage =
Printf.sprintf "%s %s [OPTION]... %s %s"
exe command name (String.concat " " args) in
if List.length userparams < List.length args then
`Error (false, Printf.sprintf "%s: Missing argument.\nUsage: %s\n"
exe usage)
else
`Error (false, Printf.sprintf "%s: Too many arguments.\nUsage: %s\n"
exe usage)
let term_info title ~doc ~man =
let man = man @ help_sections in
Term.info ~sdocs:global_option_section ~docs:"COMBDS" ~doc ~man title
let arg_list name doc conv =
let doc = Arg.info ~docv:name ~doc [] in
Arg.(value & pos_all conv [] & doc)
let nonempty_arg_list name doc conv =
let doc = Arg.info ~docv:name ~doc [] in
Arg.(non_empty & pos_all conv [] & doc)
(* Common flags *)
let print_short_flag =
mk_flag ["s";"short"]
"Output the names separated by one whitespace instead of using the usual formatting."
let installed_flag =
mk_flag ["i";"installed"] "List installed packages only."
let installed_roots_flag =
mk_flag ["installed-roots"] "Display only the installed roots."
let fish_flag =
mk_flag ["fish"] "Use fish-compatible mode for configuring OPAM."
let zsh_flag =
mk_flag ["zsh"] "Use zsh-compatible mode for configuring OPAM."
let csh_flag =
mk_flag ["csh"] "Use csh-compatible mode for configuring OPAM."
let sh_flag =
mk_flag ["sh"] "Use sh-compatible mode for configuring OPAM."
let dot_profile_flag =
mk_opt ["dot-profile"]
"FILENAME" "Name of the configuration file to update instead of \
$(i,~/.profile) or $(i,~/.zshrc) based on shell detection."
(Arg.some filename) None
let repo_kind_flag =
let kinds = [
(* main kinds *)
"http" , `http;
"local", `local;
"git" , `git;
"darcs" , `darcs;
"hg" , `hg;
(* aliases *)
"wget" , `http;
"curl" , `http;
"rsync", `local;
] in
mk_opt ["k";"kind"]
"KIND" "Specify the kind of the repository to be set (the main ones \
are 'http', 'local', 'git', 'darcs' or 'hg')."
Arg.(some (enum kinds)) None
let jobs_flag =
mk_opt ["j";"jobs"] "JOBS"
"Set the maximal number of concurrent jobs to use. You can also set it using \
the $(b,\\$OPAMJOBS) environment variable."
Arg.(some int) None
let pattern_list =
arg_list "PATTERNS" "List of package patterns." Arg.string
let nonempty_pattern_list =
nonempty_arg_list "PATTERNS" "List of package patterns." Arg.string
let name_list =
arg_list "PACKAGES" "List of package names." package_name
let atom_list =
arg_list "PACKAGES"
"List of package names, with an optional version or constraint, \
e.g `pkg', `pkg.1.0' or `pkg>=0.5'."
atom
let nonempty_atom_list =
nonempty_arg_list "PACKAGES"
"List of package names, with an optional version or constraint, \
e.g `pkg', `pkg.1.0' or `pkg>=0.5'."
atom
let param_list =
arg_list "PARAMS" "List of parameters." Arg.string
(* Options common to all commands *)
let global_options =
let section = global_option_section in
let git_version =
mk_flag ~section ["git-version"]
"Print the git version if it exists and exit." in
let debug =
mk_opt ~section ~vopt:1 ["debug"] "LEVEL"
"Print debug message to stderr. \
This is equivalent to setting $(b,\\$OPAMDEBUG) to a non-empty value."
Arg.int 0 in
let verbose =
mk_flag ~section ["v";"verbose"]
"Be more verbose. Show output of all sub-commands. \
This is equivalent to setting $(b,\\$OPAMVERBOSE) to a non-empty value." in
let quiet =
mk_flag ~section ["q";"quiet"] "Be quiet when installing a new compiler." in
let color =
mk_tristate_opt ~section ["color"] "WHEN"
"Colorize the output. $(docv) must be `always', `never' or `auto'."
(fun () -> Unix.isatty Unix.stdout) OpamGlobals.color_tri_state in
let switch =
mk_opt ~section ["switch"]
"SWITCH" "Use $(docv) as the current compiler switch. \
This is equivalent to setting $(b,\\$OPAMSWITCH) to $(i,SWITCH)."
Arg.(some string) None in
let yes =
mk_flag ~section ["y";"yes"]
"Disable interactive mode and answer yes \
to all questions that would otherwise be \
asked to the user. \
This is equivalent to setting $(b,\\$OPAMYES) to a non-empty string." in
let strict =
mk_flag ~section ["strict"]
"Fail whenever an error is found in a package definition \
or a configuration file. The default is to continue silently \
if possible." in
let root =
mk_opt ~section ["r";"root"]
"ROOT" "Use $(docv) as the current root path. \
This is equivalent to setting $(b,\\$OPAMROOT) to $(i,ROOT)."
dirname (OpamFilename.Dir.of_string OpamGlobals.default_opam_dir) in
let no_base_packages =
mk_flag ~section ["no-base-packages"]
"Do not install base packages (useful for testing purposes). \
This is equivalent to setting $(b,\\$OPAMNOBASEPACKAGES) to a non-empty \
string." in
let compat_mode_1_0 =
mk_flag ~section ["compat-mode-1.0"]
"Compatibility mode with OPAM 1.0" in
let use_internal_solver =
mk_flag ~section ["no-aspcud"; "use-internal-solver"]
"Force use of internal heuristics, even if an external solver is available." in
let external_solver =
mk_opt ["solver"] "CMD"
("Specify the name of the external dependency $(i,solver). \
The default value is "^OpamGlobals.default_external_solver)
Arg.(some string) None in
let solver_preferences =
mk_opt ["criteria"] "CRITERIA"
("Specify user $(i,preferences) for dependency solving for this run. \
Overrides both $(b,\\$OPAMCRITERIA) and $(b,\\$OPAMUPGRADECRITERIA). \
For details on the supported language, see \
$(i, http://opam.ocaml.org/doc/Specifying_Solver_Preferences.html). \
The default value is "^OpamGlobals.default_upgrade_preferences^
" for upgrades, and "^OpamGlobals.default_preferences^" otherwise.")
Arg.(some string) None in
let cudf_file =
mk_opt ["cudf"] "FILENAME"
"Debug option: Save the CUDF requests sent to the solver to \
$(docv)-<n>.cudf."
Arg.(some string) None in
let no_self_upgrade =
mk_flag ~section ["no-self-upgrade"]
"Opam with normally replace itself with a newer version found \
at $(b,OPAMROOT/opam). This disables this behaviour." in
Term.(pure create_global_options
$git_version $debug $verbose $quiet $color $switch $yes $strict $root
$no_base_packages $compat_mode_1_0 $external_solver $use_internal_solver $cudf_file $solver_preferences
$no_self_upgrade)
let json_flag =
mk_opt ["json"] "FILENAME"
"Save the result output of an OPAM run in a computer-readable file"
Arg.(some string) None
(* Options common to all build commands *)
let build_options =
let keep_build_dir =
mk_flag ["b";"keep-build-dir"]
"Keep the build directory. \
This is equivalent to setting $(b,\\$OPAMKEEPBUILDIR) to a non-empty string." in
let no_checksums =
mk_flag ["no-checksums"]
"Do not verify the checksum of downloaded archives.\
This is equivalent to setting $(b,\\$OPAMNOCHECKSUMS) to a non-empty string." in
let build_test =
mk_flag ["t";"build-test"]
"Build and $(b,run) the package unit-tests. \
This is equivalent to setting $(b,\\$OPAMBUILDTEST) to a non-empty string." in
let build_doc =
mk_flag ["d";"build-doc"]
"Build the package documentation. \
This is equivalent to setting $(b,\\$OPAMBUILDDOC) to a non-empty string." in
let make =
mk_opt ["m";"make"] "MAKE"
"Use $(docv) as the default 'make' command."
Arg.(some string) None in
let show =
mk_flag ["show-actions"]
"Call the solver and display the actions. Don't perform any changes." in
let dryrun =
mk_flag ["dry-run"]
"Simulate the command, but don't actually perform any changes." in
let external_tags =
mk_opt ["e";"external"] "TAGS"
"Display the external packages associated to the given tags."
Arg.(list string) [] in
let fake =
mk_flag ["fake"]
"This option registers the actions into the OPAM database, without \
actually performing them. \
WARNING: This option is dangerous and likely to break your OPAM \
environment. You probably want `--dry-run'. You've been warned." in
Term.(pure create_build_options
$keep_build_dir $make $no_checksums $build_test
$build_doc $show $dryrun $external_tags $fake
$jobs_flag $json_flag)
let init_dot_profile shell dot_profile =
match dot_profile with
| Some n -> n
| None -> OpamFilename.of_string (OpamMisc.guess_dot_profile shell)
module Client = OpamClient.SafeAPI
type command = unit Term.t * Term.info
(* INIT *)
let init_doc = "Initialize OPAM state."
let init =
let doc = init_doc in
let man = [
`S "DESCRIPTION";
`P "The $(b,init) command creates a fresh client state. This initializes OPAM \
configuration in $(i,~/.opam) and configures a default package repository.";
`P "Once the fresh client has been created, OPAM will ask the user if he wants \
$(i,~/.profile) (or $i,~/.zshrc, depending on his shell) and $(i,~/.ocamlinit) \
to be updated. \
If $(b,--auto-setup) is used, OPAM will modify the configuration files automatically, \
without asking the user. If $(b,--no-setup) is used, OPAM will *NOT* modify \
anything outside of $(i,~/.opam).";
`P "Additional repositories can be added later by using the $(b,opam repository) command.";
`P "The state of repositories can be synchronized by using $(b,opam update).";
`P "The user and global configuration files can be setup later by using $(b,opam config setup).";
] in
let jobs = mk_opt ["j";"jobs"] "JOBS" "Number of jobs to use when building packages." Arg.int OpamGlobals.default_jobs in
let compiler =
mk_opt ["comp"] "VERSION" "Which compiler version to use." compiler OpamCompiler.system in
let repo_name =
let doc = Arg.info ~docv:"NAME" ~doc:"Name of the repository." [] in
Arg.(value & pos ~rev:true 1 repository_name OpamRepositoryName.default & doc) in
let repo_address =
let doc = Arg.info ~docv:"ADDRESS" ~doc:"Address of the repository." [] in
Arg.(value & pos ~rev:true 0 address OpamRepository.default_address & doc) in
let no_setup = mk_flag ["n";"no-setup"] "Do not update the global and user configuration options to setup OPAM." in
let auto_setup = mk_flag ["a";"auto-setup"] "Automatically setup all the global and user configuration options for OPAM." in
let init global_options
build_options repo_kind repo_name repo_address compiler jobs
no_setup auto_setup sh csh zsh fish dot_profile_o =
(* Create the dir in current directory so that it can be made absolute *)
OpamFilename.mkdir global_options.root;
apply_global_options global_options;
apply_build_options build_options;
let repo_priority = 0 in
let repo_address, repo_kind2 = parse_url repo_address in
let repo_kind = OpamMisc.Option.default repo_kind2 repo_kind in
let repository = {
repo_root = OpamPath.Repository.create (OpamPath.root ()) repo_name;
repo_name; repo_kind; repo_address; repo_priority } in
let update_config =
if no_setup then `no
else if auto_setup then `yes
else `ask in
let shell =
if sh then `sh
else if csh then `csh
else if zsh then `zsh
else if fish then `fish
else OpamMisc.guess_shell_compat () in
let dot_profile = init_dot_profile shell dot_profile_o in
Client.init repository compiler ~jobs shell dot_profile update_config in
Term.(pure init
$global_options $build_options $repo_kind_flag $repo_name $repo_address $compiler $jobs
$no_setup $auto_setup $sh_flag $csh_flag $zsh_flag $fish_flag $dot_profile_flag),
term_info "init" ~doc ~man
(* LIST *)
let list_doc = "Display the list of available packages."
let list =
let doc = list_doc in
let man = [
`S "DESCRIPTION";
`P "This command displays the list of installed packages, or the list of \
all the available packages if the $(b,--all) flag is used.";
`P "Unless the $(b,--short) switch is used, the output format displays one \
package per line, and each line contains the name of the package, the \
installed version or -- if the package is not installed, and a short \
description. In color mode, root packages (eg. manually installed) are \
underlined.";
`P " The full description can be obtained by doing $(b,opam info <package>). \
You can search through the package descriptions using the $(b,opam search) \
command."
] in
let all =
mk_flag ["a";"all"]
"List all the packages which can be installed on the system." in
let sort = mk_flag ["sort";"S"] "Sort the packages in dependency order." in
let depends_on =
let doc = "List only packages that depend on $(docv)." in
Arg.(value & opt_all package [] & info ~doc ~docv:"PACKAGE" ["depends-on"])
in
let list global_options print_short all installed
installed_roots sort depends_on packages =
apply_global_options global_options;
let filter =
match all, installed, installed_roots, depends_on, packages with
| true, _, _, _, _ -> `installable
| _, _, true, _, _ -> `roots
| _, true, _, _, _ -> `installed
| _, _, _, [], [] -> `installed
| _ -> `installable in
let order = if sort then `depends else `normal in
Client.list
~print_short ~filter ~order ~depends_on
~exact_name:true ~case_sensitive:false
packages in
Term.(pure list $global_options
$print_short_flag $all $installed_flag $installed_roots_flag
$sort $depends_on
$pattern_list),
term_info "list" ~doc ~man
(* SEARCH *)
let search =
let doc = "Search into the package list." in
let man = [
`S "DESCRIPTION";
`P "This command displays the list of available packages that match one of \
the package patterns specified as arguments.";
`P "Unless the $(b,--short) flag is used, the output format is the same as the \
$(b,opam list) command. It displays one package per line, and each line \
contains the name of the package, the installed version or -- if the package \
is not installed, and a short description.";
`P "The full description can be obtained by doing $(b,opam show <package>).";
] in
let case_sensitive =
mk_flag ["c";"case-sensitive"] "Force the search in case sensitive mode." in
let search global_options print_short installed installed_roots case_sensitive pkgs =
apply_global_options global_options;
let filter = match installed, installed_roots with
| _, true -> `roots
| true, _ -> `installed
| _ -> `all in
let order = `normal in
Client.list ~print_short ~filter ~depends_on:[] ~order
~exact_name:false ~case_sensitive pkgs in
Term.(pure search $global_options
$print_short_flag $installed_flag $installed_roots_flag $case_sensitive
$pattern_list),
term_info "search" ~doc ~man
(* SHOW *)
let show_doc = "Display information about specific packages."
let show =
let doc = show_doc in
let man = [
`S "DESCRIPTION";
`P "This command displays the information block for the selected \
package(s).";
`P "The information block consists in the name of the package, \
the installed version if this package is installed in the currently \
selected compiler, the list of available (installable) versions, and a \
complete description.";
`P "$(b,opam list) can be used to display the list of \
available packages as well as a short description for each.";
] in
let fields =
let doc =
Arg.info
~docv:"FIELDS"
~doc:"Only display these fields. You can specify multiple fields by separating them with commas."
["f";"field"] in
Arg.(value & opt (list string) [] & doc) in
let raw =
mk_flag ["raw"] "Print the raw opam file for this package" in
let depends =
mk_flag ["d";"depends"] "Print the list of packages these ones \
transitively depend on (latest versions only)" in
let depexts =
mk_opt ["e";"external"] "TAGS"
"Display the external package dependencies associated to the given \
$(i,TAGS) (OS, distribution...). With `--depends', display them for \
the set of dependencies."
Arg.(list string) [] in
let pkg_info global_options fields raw depends depexts packages =
apply_global_options global_options;
if depends || depexts <> [] then
if raw || fields <> [] then
`Error (true, "Incompatible options specified")
else
`Ok (Client.depends ~depends ~depexts packages)
else
`Ok (Client.info ~fields ~raw_opam:raw packages) in
Term.ret
Term.(pure pkg_info $global_options $fields $raw $depends $depexts
$nonempty_atom_list),
term_info "show" ~doc ~man
(* CONFIG *)
let config_doc = "Display configuration options for packages."
let config =
let doc = config_doc in
let commands = [
["env"] , `env , [],
"Return the environment variables PATH, MANPATH, OCAML_TOPLEVEL_PATH \
and CAML_LD_LIBRARY_PATH according to the currently selected \
compiler. The output of this command is meant to be evaluated by a \
shell, for example by doing $(b,eval `opam config env`).";
["setup"] , `setup , [],
"Configure global and user parameters for OPAM. Use $(b, opam config setup) \
to display more options. Use $(b,--list) to display the current configuration \
options. You can use this command to automatically update: (i) user-configuration \
files such as ~/.profile and ~/.ocamlinit; and (ii) global-configaration files \
controlling which shell scripts are loaded on startup, such as auto-completion. \
These configuration options can be updated using: $(b,opam config setup --global) \
to setup the global configuration files stored in $(b,~/.opam/opam-init/) and \
$(b,opam config setup --user) to setup the user ones. \
To modify both the global and user configuration, use $(b,opam config setup --all).";
["exec"] , `exec , ["[--] COMMAND"; "[ARG]..."],
"Execute $(i,CMD) with the correct environment variables. \
This command can be used to cross-compile between switches using \
$(b,opam config exec --switch=SWITCH -- COMMAND ARG1 ... ARGn)";
["var"] , `var , ["VAR"],
"Return the value associated with variable $(i,VAR). Package variables can \
be accessed with the syntax $(i,pkg:var).";
["list"] , `list , ["[PACKAGE]..."],
"Without argument, prints a documented list of all available variables. With \
$(i,PACKAGE), lists all the variables available for these packages.";
["subst"] , `subst , ["FILE..."],
"Substitute variables in the given files. The strings $(i,%{var}%) are \
replaced by the value of variable $(i,var) (see $(b,var)).";
["report"] , `report , [],
"Prints a summary of your setup, useful for bug-reports.";
["cudf-universe"], `cudf, ["[FILE]"],
"Outputs the current available package universe in CUDF format.";
] in
let man = [
`S "DESCRIPTION";
`P "This command uses OPAM state to output information on how to use \
installed libraries, update the $(b,PATH), and substitute \
variables used in OPAM packages.";
`P "Apart from $(b,opam config env), most of these commands are used \
by OPAM internally, and are of limited interest for the casual \
user.";
] @ mk_subdoc commands in
let command, params = mk_subcommands commands in
let all_doc = "Enable all the global and user configuration options." in
let global_doc = "Enable all the global configuration options." in
let user_doc = "Enable all the user configuration options." in
let ocamlinit_doc = "Modify ~/.ocamlinit to make `#use \"topfind\"` works in the toplevel." in
let profile_doc = "Modify ~/.profile (or ~/.zshrc if running zsh) to \
setup an OPAM-friendly environment when starting a new shell." in
let no_complete_doc = "Do not load the auto-completion scripts in the environment." in
let no_eval_doc = "Do not install `opam-switch-eval` to switch & eval using a single command." in
let dot_profile_doc = "Select which configuration file to update (default is ~/.profile)." in
let list_doc = "List the current configuration." in
let sexp_doc = "Display environment variables as an s-expression" in
let profile = mk_flag ["profile"] profile_doc in
let ocamlinit = mk_flag ["ocamlinit"] ocamlinit_doc in
let no_complete = mk_flag ["no-complete"] no_complete_doc in
let no_switch_eval = mk_flag ["no-switch-eval"] no_eval_doc in
let all = mk_flag ["a";"all"] all_doc in
let user = mk_flag ["u";"user"] user_doc in
let global = mk_flag ["g";"global"] global_doc in
let list = mk_flag ["l";"list"] list_doc in
let sexp = mk_flag ["sexp"] sexp_doc in
let config global_options
command sh csh zsh fish sexp
dot_profile_o list all global user
profile ocamlinit no_complete no_switch_eval
params =
apply_global_options global_options;
let csh, fish =
match sh, csh, sexp, fish with
| false, false, false, false ->
(* No overrides have been provided, so guess which shell is active *)
(match OpamMisc.guess_shell_compat () with
| `csh -> true , false
| `fish -> false, true
| `sh | `bash | `zsh -> false, false)
| _ -> csh, fish
in
match command, params with
| Some `env, [] -> `Ok (Client.CONFIG.env ~csh ~sexp ~fish)
| Some `setup, [] ->
let user = all || user in
let global = all || global in
let profile = user || profile in
let ocamlinit = user || ocamlinit in
let complete = global && not no_complete in
let switch_eval = global && not no_switch_eval in
let shell =
if sh then `sh
else if csh then `csh
else if zsh then `zsh
else if fish then `fish
else OpamMisc.guess_shell_compat () in
let dot_profile = init_dot_profile shell dot_profile_o in
if list then
`Ok (Client.CONFIG.setup_list shell dot_profile)
else if profile || ocamlinit || complete || switch_eval then
let dot_profile = if profile then Some dot_profile else None in
let user = if user then Some { shell; ocamlinit; dot_profile } else None in
let global = if global then Some { complete; switch_eval } else None in
`Ok (Client.CONFIG.setup user global)
else
`Ok (OpamGlobals.msg
"usage: opam config setup [options]\n\
\n\
Main options\n\
\ -l, --list %s\n\
\ -a, --all %s\n\
\ --sh,--csh,--zsh,--fish Force the configuration mode to a given shell.\n\
\n\
User configuration\n\
\ -u, --user %s\n\
\ --ocamlinit %s\n\
\ --profile %s\n\
\ --dot-profile FILE %s\n\
\n\
Global configuration\n\
\ -g,--global %s\n\
\ --no-complete %s\n\
\ --no-switch-eval %s\n\n"
list_doc all_doc
user_doc ocamlinit_doc profile_doc dot_profile_doc
global_doc no_complete_doc no_eval_doc)
| Some `exec, (_::_ as c) -> `Ok (Client.CONFIG.exec c)
| Some `list, [] ->
`Ok (Client.CONFIG.list (List.map OpamPackage.Name.of_string params))
| Some `var, [var] ->
`Ok (Client.CONFIG.variable (OpamVariable.Full.of_string var))
| Some `subst, (_::_ as files) ->
`Ok (Client.CONFIG.subst (List.map OpamFilename.Base.of_string files))
| Some `cudf, params ->
let opam_state = OpamState.load_state "config-universe" in
let opam_univ = OpamState.universe opam_state Depends in
let version_map =
OpamSolver.cudf_versions_map opam_univ opam_state.OpamState.Types.packages in
let cudf_univ =
OpamSolver.load_cudf_universe ~depopts:false opam_univ ~version_map
opam_univ.u_available in
let dump oc =
OpamCudf.dump_universe oc cudf_univ;
(* Add explicit bindings to retrieve original versions of non-available packages *)
OpamPackage.Map.iter (fun nv i ->
if not (OpamPackage.Set.mem nv opam_univ.u_available) then
Printf.printf "#v2v:%s:%d=%s\n"
(OpamPackage.name_to_string nv) i (OpamPackage.version_to_string nv)
) version_map in
(match params with
| [] -> `Ok (dump stdout)
| [file] -> let oc = open_out file in dump oc; close_out oc; `Ok ()
| _ -> bad_subcommand "config" commands command params)
| Some `report, [] -> (
let print label fmt = Printf.printf ("# %-15s "^^fmt^^"\n") label in
Printf.printf "# OPAM status report\n";
let version = OpamVersion.to_string OpamVersion.current in
let version = match OpamVersion.git with
| None -> version
| Some v -> Printf.sprintf "%s (%s)" version (OpamVersion.to_string v)
in
print "opam-version" "%s" version;
print "self-upgrade" "%s"
(if OpamGlobals.is_self_upgrade
then OpamFilename.prettify (fst (self_upgrade_exe (OpamPath.root())))
else "no");
print "os" "%s" (OpamGlobals.os_string ());
print "external-solver" "%b" (OpamCudf.external_solver_available ());
try
let state = OpamState.load_state "config-report" in
let open OpamState.Types in
let nprint label n =
if n <> 0 then [Printf.sprintf "%d (%s)" n label]
else [] in
print "jobs" "%d" (OpamState.jobs state);