forked from ocaml/opam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopamCommands.ml
4499 lines (4442 loc) · 186 KB
/
opamCommands.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-2020 OCamlPro *)
(* Copyright 2012 INRIA *)
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
(* GNU Lesser General Public License version 2.1, with the special *)
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Cmdliner
open OpamArg
open OpamTypes
open OpamStateTypes
open OpamStd.Op
let self_upgrade_exe opamroot =
OpamFilename.Op.(opamroot // "opam", opamroot // "opam.version")
let self_upgrade_bootstrapping_value = "bootstrapping"
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 -> OpamStd.Exn.fatal e; no_version in
if update_version = no_version then
OpamConsole.error "%s exists but cannot be read, disabling self-upgrade."
updated_self_version_str
else if OpamVersion.compare update_version OpamVersion.current <= 0 then
OpamConsole.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.is_dev_version () then
OpamConsole.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 || (OpamConsole.debug ()) then
OpamConsole.errmsg "!! %s found, switching to it !!\n"
updated_self_str;
let env =
Array.append
[|"OPAMNOSELFUPGRADE="^ self_upgrade_bootstrapping_value|]
(Unix.environment ()) in
try
OpamStd.Sys.exec_at_exit ();
Unix.execve updated_self_str Sys.argv env
with e ->
OpamStd.Exn.fatal e;
OpamConsole.error
"Couldn't 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 global_options cli =
let no_self_upgrade =
mk_flag ~cli cli_original ~section:global_option_section ["no-self-upgrade"]
(Printf.sprintf
"Opam will replace itself with a newer binary found \
at $(b,OPAMROOT%sopam) if present. This disables this behaviour."
OpamArg.dir_sep) in
let self_upgrade no_self_upgrade options =
let self_upgrade_status =
if OpamClientConfig.E.noselfupgrade () =
Some self_upgrade_bootstrapping_value
then `Running
else if no_self_upgrade then `Disable
else if OpamStd.Option.Op.((OpamClientConfig.E.noselfupgrade ())
>>= OpamStd.Config.bool_of_string)
= Some true
then `Disable
else `None
in
if self_upgrade_status = `None then
switch_to_updated_self
OpamStd.Option.Op.(options.debug_level ++
OpamCoreConfig.E.debug () +! 0 |> abs > 0)
(OpamStateConfig.opamroot ?root_dir:options.opt_root ());
let root_is_ok =
OpamStd.Option.default false (OpamClientConfig.E.rootisok ())
in
if not (options.safe_mode || root_is_ok) &&
Unix.getuid () = 0 then
OpamConsole.warning "Running as root is not recommended";
{options with cli = fst cli}, self_upgrade_status
in
Term.(const self_upgrade $ no_self_upgrade $ global_options cli)
let apply_global_options cli (options,self_upgrade) =
apply_global_options cli options;
OpamConsole.log "CLI" "Parsing CLI version %s"
(OpamCLIVersion.to_string options.cli);
try
let argv0 = OpamFilename.of_string Sys.executable_name in
if self_upgrade <> `Running &&
OpamFilename.starts_with OpamStateConfig.(!r.root_dir) argv0 &&
not !OpamCoreConfig.r.OpamCoreConfig.safe_mode
then
OpamConsole.warning "You should not be running opam from within %s. \
Copying %s to your PATH first is advised."
(OpamFilename.Dir.to_string OpamStateConfig.(!r.root_dir))
(OpamFilename.to_string argv0)
with e -> OpamStd.Exn.fatal e
let self_upgrade_status global_options = snd global_options
let get_init_config ~no_sandboxing ~no_default_config_file ~add_config_file =
let builtin_config =
OpamInitDefaults.init_config ~sandboxing:(not no_sandboxing) ()
in
let config_files =
(if no_default_config_file then []
else List.filter OpamFile.exists (OpamPath.init_config_files ()))
@ List.map (fun url ->
match OpamUrl.local_file url with
| Some f -> OpamFile.make f
| None ->
let f = OpamFilename.of_string (OpamSystem.temp_file "conf") in
OpamProcess.Job.run (OpamDownload.download_as ~overwrite:false url f);
let hash = OpamHash.compute ~kind:`SHA256 (OpamFilename.to_string f) in
if OpamConsole.confirm
"Using configuration file from %s. \
Please verify the following SHA256:\n %s\n\
Is this correct?"
(OpamUrl.to_string url) (OpamHash.contents hash)
then OpamFile.make f
else OpamStd.Sys.exit_because `Aborted
) add_config_file
in
try
let others =
match config_files with
| [] -> ""
| [file] -> OpamFile.to_string file ^ " and then from "
| _ ->
(OpamStd.List.concat_map ~right:", and finally from " ", then "
OpamFile.to_string (List.rev config_files))
in
if config_files = [] then
OpamConsole.msg "No configuration file found, using built-in defaults.\n"
else
OpamConsole.msg "Configuring from %sbuilt-in defaults.\n" others;
List.fold_left (fun acc f ->
OpamFile.InitConfig.add acc (OpamFile.InitConfig.read f))
builtin_config config_files
with e ->
OpamConsole.error
"Error in configuration file, fix it, use '--no-opamrc', or check \
your '--config FILE' arguments:";
OpamConsole.errmsg "%s\n" (Printexc.to_string e);
OpamStd.Sys.exit_because `Configuration_error
(* INIT *)
let init_doc = "Initialize opam state, or set init options."
let init cli =
let doc = init_doc in
let man = [
`S Manpage.s_description;
`P "Initialise the opam state, or update opam init options";
`P (Printf.sprintf
"The $(b,init) command initialises a local \"opam root\" (by default, \
$(i,~%s.opam%s)) that holds opam's data and packages. This is a \
necessary step for normal operation of opam. The initial software \
repositories are fetched, and an initial 'switch' can also be \
installed, according to the configuration and options. These can be \
afterwards configured using $(b,opam switch) and $(b,opam \
repository)."
OpamArg.dir_sep OpamArg.dir_sep);
`P (Printf.sprintf
"The initial repository and defaults can be set through a \
configuration file found at $(i,~%s.opamrc) or $(i,/etc/opamrc)."
OpamArg.dir_sep);
`P "Additionally, this command allows one to customise some aspects of opam's \
shell integration, when run initially (avoiding the interactive \
dialog), but also at any later time.";
`S Manpage.s_arguments;
`S Manpage.s_options;
`S "CONFIGURATION FILE";
`P (Printf.sprintf
"Any field from the built-in initial configuration can be overridden \
through $(i,~%s.opamrc), $(i,/etc/opamrc), or a file supplied with \
$(i,--config). The default configuration for this version of opam \
can be obtained using $(b,--show-default-opamrc)."
OpamArg.dir_sep);
] @ OpamArg.man_build_option_section
in
let compiler =
mk_opt ~cli cli_original ["c";"compiler"] "PACKAGE"
"Set the compiler to install (when creating an initial switch)"
Arg.(some string) None
in
let no_compiler =
mk_flag ~cli cli_original ["bare"]
"Initialise the opam state, but don't setup any compiler switch yet."
in
let repo_name =
let doc =
Arg.info [] ~docv:"NAME" ~doc:
"Name of the initial repository, when creating a new opam root."
in
Arg.(value & pos ~rev:true 1 repository_name OpamRepositoryName.default
& doc)
in
let repo_url =
let doc =
Arg.info [] ~docv:"ADDRESS" ~doc:
"Address of the initial package repository, when creating a new opam \
root."
in
Arg.(value & pos ~rev:true 0 (some string) None & doc)
in
let interactive =
mk_vflag ~cli None [
cli_original, (Some false), ["a";"auto-setup"],
"Automatically do a full setup, including adding a line to your \
shell init files.";
cli_original, (Some true), ["i";"interactive"],
"Run the setup interactively (this is the default for an initial \
run, or when no more specific options are specified)";
]
in
let update_config =
mk_vflag ~cli None [
cli_original, (Some true), ["shell-setup"],
"Automatically setup the user shell configuration for opam, e.g. \
adding a line to the `~/.profile' file.";
cli_original, (Some false), ["n";"no-setup"],
"Do not update the user shell configuration to setup opam. Also \
implies $(b,--disable-shell-hook), unless $(b,--interactive) or \
specified otherwise";
]
in
let setup_completion =
mk_vflag ~cli None [
cli_original, (Some true), ["enable-completion"],
"Setup shell completion in opam init scripts, for supported \
shells.";
cli_original, (Some false), ["disable-completion"],
"Disable shell completion in opam init scripts.";
]
in
let env_hook =
mk_vflag ~cli None [
cli_original, (Some true), ["enable-shell-hook"],
"Setup opam init scripts to register a shell hook that will \
automatically keep the shell environment up-to-date at every \
prompt.";
cli_original, (Some false), ["disable-shell-hook"],
"Disable registration of a shell hook in opam init scripts.";
]
in
let config_file =
mk_opt_all ~cli cli_original ["config"] "FILE"
"Use the given init config file. If repeated, latest has the highest \
priority ($(b,i.e.) each field gets its value from where it was defined \
last). Specifying a URL pointing to a config file instead is \
allowed."
OpamArg.url
in
let no_config_file =
mk_flag ~cli cli_original ["no-opamrc"]
(Printf.sprintf
"Don't read `/etc/opamrc' or `~%s.opamrc': use the default settings and \
the files specified through $(b,--config) only" OpamArg.dir_sep)
in
let reinit =
mk_flag ~cli cli_original ["reinit"]
"Re-run the initial checks and setup, according to opamrc, even if this \
is not a new opam root"
in
let show_default_opamrc =
mk_flag ~cli cli_original ["show-default-opamrc"]
"Print the built-in default configuration to stdout and exit"
in
let bypass_checks =
mk_flag ~cli cli_original ["bypass-checks"]
"Skip checks on required or recommended tools, and assume everything is \
fine"
in
let no_sandboxing =
mk_flag ~cli cli_original ["disable-sandboxing"]
"Use a default configuration with sandboxing disabled (note that this \
may be overridden by `opamrc' if $(b,--no-opamrc) is not specified or \
$(b,--config) is used). Use this at your own risk, without sandboxing \
it is possible for a broken package script to delete all your files."
in
let cygwin_internal =
mk_vflag ~cli `none [
cli_from ~platform:`windows ~experimental:true cli2_2,
`internal, ["cygwin-internal-install"],
"Let opam setup and manage an internal Cygwin install (recommended)";
cli_from ~platform:`windows ~experimental:true cli2_2,
`default_location, ["cygwin-local-install"],
"Use preexistent Cygwin install";
cli_from ~experimental:true cli2_2,
`no, ["no-cygwin-setup"],
"Don't setup Cygwin";
]
in
let cygwin_extra_packages =
mk_opt ~cli (cli_from ~platform:`windows ~experimental:true cli2_2)
["cygwin-extra-packages"] "CYGWIN_PACKAGES"
"Specify additional packages to install \
with $(b,--cygwin-internal-install)"
Arg.(some (list string)) None
in
let cygwin_location =
mk_opt ~cli (cli_from ~platform:`windows ~experimental:true cli2_2)
["cygwin-location"] "DIR" "Specify Cygwin root location"
Arg.(some dirname) None
in
let git_location =
mk_opt ~cli (cli_from ~platform:`windows ~experimental:true cli2_2)
["git-location"] "DIR"
"Specify git binary directory. \
Ensure that it doesn't contains bash in the same directory"
Arg.(some dirname) None
in
let no_git_location =
mk_flag ~cli (cli_from ~experimental:true cli2_2)
["no-git-location"]
"Don't specify nor ask to specify git binary directory."
in
let init global_options
build_options repo_kind repo_name repo_url
interactive update_config completion env_hook no_sandboxing shell
dot_profile_o compiler no_compiler config_file no_config_file reinit
show_opamrc bypass_checks
cygwin_internal cygwin_location cygwin_extra_packages
git_location no_git_location
() =
apply_global_options cli global_options;
apply_build_options cli build_options;
(* If show option is set, dump opamrc and exit *)
if show_opamrc then
(OpamFile.InitConfig.write_to_channel stdout @@
OpamInitDefaults.init_config ~sandboxing:(not no_sandboxing) ();
OpamStd.Sys.exit_because `Success);
(* Else continue init *)
if compiler <> None && no_compiler then
OpamConsole.error_and_exit `Bad_arguments
"Options --bare and --compiler are incompatible";
let root = OpamStateConfig.(!r.root_dir) in
let config_f = OpamPath.config root in
let already_init = OpamFile.exists config_f in
(* handling of `-ni` option *)
let inplace =
interactive = Some true && update_config = Some false
&& env_hook = None && completion = None
in
let interactive, update_config, completion, env_hook =
match interactive with
| Some false ->
OpamStd.Option.Op.(
false,
update_config ++ Some true,
completion ++ Some true,
env_hook ++ Some true
)
| None ->
(not already_init ||
update_config = None && completion = None && env_hook = None),
update_config, completion, OpamStd.Option.Op.(env_hook ++ update_config)
| Some true ->
if update_config = None && completion = None && env_hook = None then
true, None, None, None
else
let reconfirm = function
| None | Some false -> None
| Some true -> Some true
in
true,
(if update_config = Some true then update_config else Some false),
reconfirm completion,
reconfirm env_hook
in
let shell = match shell with
| Some s -> s
| None -> OpamStd.Sys.guess_shell_compat ()
in
let dot_profile =
OpamStd.Option.Op.(dot_profile_o >>+ fun () ->
OpamStd.Sys.guess_dot_profile shell >>| OpamFilename.of_string)
in
let cygwin_setup =
let bad_arg arg1 arg2 =
OpamConsole.error_and_exit `Bad_arguments
"Options --%s and --%s are incompatible"
arg1 arg2
in
match cygwin_internal, cygwin_location, cygwin_extra_packages with
| `internal, Some _, _ ->
bad_arg "cygwin-internal-install" "cygwin-location"
| `default_location, _, Some _ ->
bad_arg "cygwin-local-install" "cygwin-extra-packages"
| `no, Some _, _ ->
bad_arg "no-cygwin-setup" "cygwin-location"
| `no, _, Some _ ->
bad_arg "no-cygwin-setup" "cygwin-extra-packages"
| `none, Some _, Some _ ->
bad_arg "cygwin-location" "cygwin-extra-packages"
| `none, None, None ->
None
| (`internal | `none), None, pkgs ->
Some (`internal
(OpamStd.Option.default [] pkgs
|> List.map OpamSysPkg.of_string))
| (`default_location | `none), Some dir, None -> Some (`location dir)
| (`default_location | `no) as setup, None, None -> Some setup
in
let git_location =
match git_location, no_git_location with
| Some _, true ->
OpamConsole.error_and_exit `Bad_arguments
"Options --no-git-location and --git-location are incompatible";
| None, false -> None
| Some d, false -> Some (Left d)
| None, true -> Some (Right ())
in
if already_init then
if reinit then
let init_config =
get_init_config ~no_sandboxing
~no_default_config_file:no_config_file ~add_config_file:config_file
in
let reinit conf =
OpamClient.reinit ~init_config ~interactive ?dot_profile
?update_config ?env_hook ?completion ~inplace ~bypass_checks
~check_sandbox:(not no_sandboxing) ?cygwin_setup ?git_location
conf shell
in
let config =
match OpamStateConfig.load ~lock_kind:`Lock_write root with
| Some c -> c
| exception (OpamPp.Bad_version _ as e) ->
OpamFormatUpgrade.hard_upgrade_from_2_1_intermediates ~reinit root;
raise e
| None -> OpamFile.Config.empty
in
reinit config
else
(if not interactive
&& update_config <> Some true
&& completion <> Some true
&& env_hook <> Some true then
OpamConsole.msg
"Opam was already initialised. If you want to set it up again, \
use `--interactive', `--reinit', or choose a different \
`--root'.\n";
OpamEnv.setup root ~interactive ?dot_profile ?update_config ?env_hook
?completion ~inplace shell)
else
let init_config =
get_init_config ~no_sandboxing
~no_default_config_file:no_config_file ~add_config_file:config_file
in
let repo =
OpamStd.Option.map (fun url ->
let repo_url = OpamUrl.parse ?backend:repo_kind ~from_file:false url in
{ repo_name; repo_url; repo_trust = None })
repo_url
in
let gt, rt, default_compiler =
OpamClient.init
~init_config ~interactive
?repo ~bypass_checks ?dot_profile
?update_config ?env_hook ?completion
~check_sandbox:(not no_sandboxing)
?cygwin_setup ?git_location
shell
in
OpamStd.Exn.finally (fun () -> OpamRepositoryState.drop rt)
@@ fun () ->
if no_compiler then () else
let invariant, default_compiler, name =
match compiler with
| Some comp when String.length comp > 0 ->
OpamSwitchCommand.guess_compiler_invariant rt [comp],
[],
comp
| _ ->
OpamFile.Config.default_invariant gt.config,
default_compiler, "default"
in
OpamConsole.header_msg "Creating initial switch '%s' (invariant %s%s)"
name
(match invariant with
| OpamFormula.Empty -> "empty"
| c -> OpamFileTools.dep_formula_to_string c)
(match default_compiler with
| [] -> ""
| comp -> " - initially with "^ (OpamFormula.string_of_atoms comp));
let (), st =
try
OpamSwitchCommand.create
gt ~rt ~invariant ~update_config:true (OpamSwitch.of_string name) @@
(fun st ->
(),
OpamSwitchCommand.install_compiler st
~ask:false
~additional_installs:default_compiler)
with e ->
OpamStd.Exn.finalise e @@ fun () ->
OpamConsole.note
"Opam has been initialised, but the initial switch creation \
failed.\n\
Use 'opam switch create <compiler>' to get started."
in
OpamSwitchState.drop st
in
mk_command ~cli cli_original "init" ~doc ~man
Term.(const init
$global_options cli $build_options cli $repo_kind_flag cli
cli_original $repo_name $repo_url $interactive $update_config
$setup_completion $env_hook $no_sandboxing $shell_opt cli
cli_original $dot_profile_flag cli cli_original $compiler
$no_compiler $config_file $no_config_file $reinit $show_default_opamrc
$bypass_checks $cygwin_internal $cygwin_location $cygwin_extra_packages
$git_location $no_git_location)
(* LIST *)
let list_doc = "Display the list of available packages."
let list ?(force_search=false) cli =
let doc = list_doc in
let selection_docs = OpamArg.package_selection_section in
let display_docs = OpamArg.package_listing_section in
let man = [
`S Manpage.s_description;
`P "List selections of opam packages.";
`P "Without argument, the command displays the list of currently installed \
packages. With pattern arguments, lists all available packages \
matching one of the patterns.";
`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, manually installed packages (as opposed to \
automatically installed ones because of dependencies) are underlined.";
`P ("See section $(b,"^selection_docs^") for all the ways to select the \
packages to be displayed, and section $(b,"^display_docs^") to \
customise the output format.");
`P "For a more detailed description of packages, see $(b,opam show). For \
extended search capabilities within the packages' metadata, see \
$(b,opam search).";
`S Manpage.s_arguments;
`S selection_docs;
`S display_docs;
] in
let pattern_list =
arg_list "PATTERNS"
"Package patterns with globs. Unless $(b,--search) is specified, they \
match againsta $(b,NAME) or $(b,NAME.VERSION)"
Arg.string
in
let state_selector =
mk_vflag_all ~cli ~section:selection_docs [
cli_original, OpamListCommand.Any, ["A";"all"],
"Include all, even uninstalled or unavailable packages";
cli_original, OpamListCommand.Installed, ["i";"installed"],
"List installed packages only. This is the default when no \
further arguments are supplied";
cli_original, OpamListCommand.Root, ["roots";"installed-roots"],
"List only packages that were explicitly installed, excluding \
the ones installed as dependencies";
cli_original, OpamListCommand.Available, ["a";"available"],
"List only packages that are available on the current system";
cli_original, OpamListCommand.Installable, ["installable"],
"List only packages that can be installed on the current switch \
(this calls the solver and may be more costly; a package \
depending on an unavailable package may be available, but is \
never installable)";
cli_between cli2_0 cli2_1 ~replaced:"--invariant",
OpamListCommand.Compiler, ["base"],
"List only the immutable base of the current switch (i.e. \
compiler packages)";
cli_from cli2_2, OpamListCommand.Compiler, ["invariant"],
"List only the immutable base of the current switch (i.e. \
invariant packages)";
cli_original, OpamListCommand.Pinned, ["pinned"],
"List only the pinned packages";
]
in
let section = selection_docs in
let search =
if force_search then Term.const true else
mk_flag ~cli cli_original ["search"] ~section
"Match $(i,PATTERNS) against the full descriptions of packages, and \
require all of them to match, instead of requiring at least one to \
match against package names (unless $(b,--or) is also specified)."
in
let repos =
mk_opt ~cli cli_original ["repos"] "REPOS" ~section
"Include only packages that took their origin from one of the given \
repositories (unless $(i,no-switch) is also specified, this excludes \
pinned packages)."
Arg.(some & list & repository_name) None
in
let owns_file =
mk_opt ~cli cli_original ["owns-file"] "FILE" ~section
"Finds installed packages responsible for installing the given file"
Arg.(some OpamArg.filename) None
in
let no_switch =
mk_flag ~cli cli_original ["no-switch"] ~section:selection_docs
"List what is available from the repositories, without consideration for \
the current (or any other) switch (installed or pinned packages, etc.)"
in
let disjunction =
mk_flag ~cli cli_original ["or"] ~section:selection_docs
"Instead of selecting packages that match $(i,all) the criteria, select \
packages that match $(i,any) of them"
in
let depexts =
mk_flag ~cli cli_original ["e";"external";"depexts"] ~section:display_docs
"Instead of displaying the packages, display their external dependencies \
that are associated with the current system. This excludes other \
display options. Rather than using this directly, you should probably \
head for the `depext' plugin, that will use your system package \
management system to handle the installation of the dependencies. Run \
`opam depext'."
in
let vars =
mk_opt ~cli cli_original ["vars"] "[VAR=STR,...]" ~section:display_docs
"Define the given variable bindings. Typically useful with \
$(b,--external) to override the values for $(i,arch), $(i,os), \
$(i,os-distribution), $(i,os-version), $(i,os-family)."
OpamArg.variable_bindings []
in
let silent =
mk_flag_replaced ~cli [
cli_between ~option:`default cli2_0 cli2_1 ~replaced:"--check", ["silent"];
cli_from cli2_1, ["check"]
] "Don't write anything in the output, exit with return code 0 if the list \
is not empty, 1 otherwise."
in
let no_depexts =
mk_flag ~cli cli_original ["no-depexts"]
"Disable external dependencies handling for the query. This can be used \
to include packages that are marked as unavailable because of an unavailable \
system dependency."
in
let list
global_options selection state_selector no_switch depexts vars repos
owns_file disjunction search silent no_depexts format packages () =
apply_global_options cli global_options;
let no_switch =
no_switch || OpamStateConfig.get_switch_opt () = None
in
let format =
let force_all_versions =
not search && state_selector = [] && match packages with
| [single] ->
let nameglob =
match OpamStd.String.cut_at single '.' with
| None -> single
| Some (n, _v) -> n
in
(try ignore (OpamPackage.Name.of_string nameglob); true
with Failure _ -> false)
| _ -> false
in
format ~force_all_versions
in
let join =
if disjunction then OpamFormula.ors else OpamFormula.ands
in
let state_selector =
if state_selector = [] then
if no_switch || search || owns_file <> None then Empty
else if packages = [] && selection = []
then Atom OpamListCommand.Installed
else Or (Atom OpamListCommand.Installed,
Atom OpamListCommand.Available)
else join (List.map (fun x -> Atom x) state_selector)
in
let pattern_selector =
if search then
join
(List.map (fun p ->
Atom (OpamListCommand.(Pattern (default_pattern_selector, p))))
packages)
else OpamListCommand.pattern_selector packages
in
let filter =
OpamFormula.ands [
join
(pattern_selector ::
(if no_switch then Empty else
match repos with None -> Empty | Some repos ->
Atom (OpamListCommand.From_repository repos)) ::
OpamStd.Option.Op.
((owns_file >>| fun f -> Atom (OpamListCommand.Owns_file f)) +!
Empty) ::
List.map (fun x -> Atom x) selection);
state_selector;
]
in
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamRepositoryState.with_ `Lock_none gt @@ fun rt ->
if no_depexts then OpamStateConfig.update ~no_depexts:true ();
let st =
if no_switch then OpamSwitchState.load_virtual ?repos_list:repos gt rt
else OpamSwitchState.load `Lock_none gt rt (OpamStateConfig.get_switch ())
in
let st =
let open OpamFile.Switch_config in
let conf = st.switch_config in
{ st with switch_config =
{ conf with variables =
conf.variables @ List.map (fun (var, v) -> var, S v) vars } }
in
if not depexts &&
not format.OpamListCommand.short &&
filter <> OpamFormula.Empty &&
not silent
then
OpamConsole.msg "# Packages matching: %s\n"
(OpamListCommand.string_of_formula filter);
let all = OpamPackage.Set.union st.packages st.installed in
let results =
OpamListCommand.filter ~base:all st filter
in
if not no_depexts && not silent then
(let drop_by_depexts =
List.fold_left (fun missing str ->
let is_missing pkgs =
if OpamStd.String.contains_char str '.' then
let nv = OpamPackage.of_string str in
if OpamPackage.Set.mem nv results then None else
OpamPackage.Set.find_opt (OpamPackage.equal nv) pkgs
else
let n = OpamPackage.Name.of_string str in
if OpamPackage.has_name results n then None else
let exist = OpamPackage.packages_of_name pkgs n in
if OpamPackage.Set.is_empty exist then None else
Some (OpamPackage.Set.max_elt exist)
in
match OpamStd.Option.Op.(
is_missing OpamPackage.Set.Op.(st.packages ++ st.pinned)
>>= OpamSwitchState.depexts_unavailable st) with
| Some nf -> OpamStd.String.Map.add str nf missing
| None -> missing
| exception Failure _ -> missing (* invalid package *)
) OpamStd.String.Map.empty packages
in
if not (OpamStd.String.Map.is_empty drop_by_depexts) then
OpamConsole.note
"Some packages are unavailable because of their external dependencies. \
Use `--no-depexts' to show them anyway.\n%s"
(OpamStd.Format.itemize (fun (n, spkgs) ->
Printf.sprintf "%s: %s" n
(OpamStd.Format.pretty_list
(List.map OpamSysPkg.to_string
(OpamSysPkg.Set.elements spkgs))))
(OpamStd.String.Map.bindings drop_by_depexts)));
if not depexts then
(if not silent then
OpamListCommand.display st format results
else if OpamPackage.Set.is_empty results then
OpamStd.Sys.exit_because `False)
else
let results_depexts = OpamListCommand.get_depexts st results in
if not silent then
OpamListCommand.print_depexts results_depexts
else if OpamSysPkg.Set.is_empty results_depexts then
OpamStd.Sys.exit_because `False
in
mk_command ~cli cli_original "list" ~doc ~man
Term.(const list $global_options cli $package_selection cli $state_selector
$no_switch $depexts $vars $repos $owns_file $disjunction $search
$silent $no_depexts $package_listing cli $pattern_list)
(* TREE *)
let tree_doc = "Draw the dependency forest of installed packages."
let tree ?(why=false) cli =
let doc = tree_doc in
let build_docs = "TREE BUILDING OPTIONS" in
let filter_docs = "TREE FILTERING OPTIONS" in
let selection_docs = OpamArg.package_selection_section in
let display_docs = OpamArg.package_listing_section in
let man = [
`S Manpage.s_description;
`P "This command displays the forest of currently installed \
packages as a Unicode/ASCII-art.";
`P "Without argument, it draws the dependency forest of packages with no \
dependants. With packages arguments, draws the forest of the specified \
packages. When non-installed packages are specified in the arguments, \
it will try to simulate installing them before drawing the forest.";
`P "When the $(b,--rev-deps) option is used, it draws the \
reverse-dependency forest instead. Without argument, draws the forest \
of packages with no dependencies. With packages arguments, draws the \
forest of the specified packages. Note that non-installed packages are \
ignored when this option is used.";
`P ("When a package appears twice or more in the forest, the second or \
later occurrences of the said package will be marked as a duplicate, \
and be annotated with the $(i,"^OpamTreeCommand.duplicate_symbol^") \
symbol. Any sub-trees rooted from such duplicates will be truncated \
to avoid redundancy.");
`P ("See section $(b,"^filter_docs^") and $(b,"^selection_docs^") for all \
the ways to select the packages to be displayed, and section \
$(b,"^display_docs^") to customise the output format.");
`P "For a flat list of packages which may not be installed, \
see $(b,opam list).";
`S Manpage.s_arguments;
`S build_docs;
`S filter_docs;
`P "These options only take effect when $(i,PACKAGES) are present.";
`S selection_docs;
`S display_docs;
] in
let mode =
let default = OpamTreeCommand.(if why then ReverseDeps else Deps) in
mk_vflag default ~cli ~section:build_docs [
cli_from cli2_2, OpamTreeCommand.Deps, ["deps"],
"Draw a dependency forest, starting from the packages not required by \
any other packages (this is the default).";
cli_from cli2_2, OpamTreeCommand.ReverseDeps, ["rev-deps"],
"Draw a reverse-dependency forest, starting from the packages which \
have no dependencies.";
]
in
let filter =
let default = OpamTreeCommand.Roots_from in
mk_vflag default ~cli ~section:filter_docs [
cli_from cli2_2, OpamTreeCommand.Roots_from, ["roots-from"],
"Display only the trees which roots from one of the $(i,PACKAGES) \
(this is the default).";
cli_from cli2_2, OpamTreeCommand.Leads_to, ["leads-to"],
"Display only the branches which leads to one of the $(i,PACKAGES).";
]
in
let no_cstr =
mk_flag ~cli (cli_from cli2_2) ["no-constraint"] ~section:display_docs
"Do not display the version constraints e.g. $(i,(>= 1.0.0))."
in
let no_switch =
mk_flag ~cli (cli_from cli2_2) ["no-switch"] ~section:selection_docs
"Ignore active switch and simulate installing packages from an empty \
switch to draw the forest"
in
let tree global_options mode filter post dev doc test dev_setup no_constraint
no_switch recurse subpath atoms_or_locals () =
if atoms_or_locals = [] && no_switch then
`Error
(true, "--no-switch can't be used without specifying a package or a path")
else
(apply_global_options cli global_options;
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamRepositoryState.with_ `Lock_none gt @@ fun rt ->
(if no_switch then
fun k ->
k @@ OpamSwitchState.load_virtual gt rt
else
OpamSwitchState.with_ `Lock_none ~rt gt) @@ fun st ->
let st, atoms =
OpamAuxCommands.simulate_autopin
st ~recurse ?subpath ~quiet:true
?locked:OpamStateConfig.(!r.locked) atoms_or_locals
in
let tog = OpamListCommand.{
post; test; doc; dev; dev_setup;
recursive = false;
depopts = false;
build = true;
} in
OpamTreeCommand.run st tog ~no_constraint mode filter atoms;
`Ok ())
in
mk_command_ret ~cli (cli_from cli2_2) "tree" ~doc ~man
Term.(const tree $global_options cli $mode $filter
$post cli $dev cli $doc_flag cli $test cli $dev_setup cli
$no_cstr $no_switch
$recurse cli $subpath cli
$atom_or_local_list)
(* SHOW *)
let show_doc = "Display information about specific packages."
let show cli =
let doc = show_doc in
let man = [
`S Manpage.s_description;
`P "This command displays the information block for the selected \
package(s).";
`P "The information block consists of 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.";
`P "Paths to package definition files or to directories containing package \
definitions can also be specified, in which case the corresponding \
metadata will be shown."
] in
let fields =
mk_opt ~cli cli_original ["f";"field"] "FIELDS"
(Printf.sprintf
"Only display the values of these fields. Fields can be selected \
among %s. Multiple fields can be separated with commas, in which case \
field titles will be printed; the raw value of any opam-file \
field can be queried by combinig with $(b,--raw)"
(OpamStd.List.concat_map ", " (Printf.sprintf "$(i,%s)" @* snd)
OpamListCommand.field_names))
Arg.(list string) []
in
let show_empty =
mk_flag ~cli cli_original ["empty-fields"]
"Show fields that are empty. This is implied when $(b,--field) is \
given."
in
let raw =
mk_flag ~cli cli_original ["raw"] "Print the raw opam file for this package" in
let where =
mk_flag ~cli cli_original ["where"]
"Print the location of the opam file used for this package" in
let list_files =
mk_flag ~cli cli_original ["list-files"]
"List the files installed by the package. Equivalent to \
$(b,--field=installed-files), and only available for installed \
packages"
in
let file =
mk_opt ~cli (cli_between cli2_0 cli2_1 ~replaced:"--just-file")
["file"] "FILE"
"DEPRECATED: use an explicit path argument as package instead. \
Get package information from the given FILE instead of from \
known packages. This implies $(b,--raw) unless $(b,--fields) is \
used. Only raw opam-file fields can be queried."
existing_filename_or_dash None
in
let normalise =
mk_flag ~cli cli_original ["normalise"]
"Print the values of opam fields normalised (no newlines, no implicit \
brackets)"
in
let no_lint =
mk_flag ~cli cli_original ["no-lint"]
"Don't output linting warnings or errors when reading from files"
in
let just_file =
mk_flag ~cli (cli_from cli2_1) ["just-file"]
"Load and display information from the given files (allowed \
$(i,PACKAGES) are file or directory paths), without consideration for \
the repositories or state of the package. This implies $(b,--raw) unless \
$(b,--fields) is used. Only raw opam-file fields can be queried. If no \
PACKAGES argument is given, read opam file from stdin."
in
let all_versions =
mk_flag ~cli (cli_from cli2_1) ["all-versions"]
"Display information of all packages matching $(i,PACKAGES), not \
restrained to a single package matching $(i,PACKAGES) constraints."
in
let sort = mk_flag ~cli (cli_from cli2_1) ["sort"] "Sort opam fields" in
let opam_files_in_dir d =
match OpamPinned.files_in_source d with
| [] -> []
| l -> List.map (fun nf -> nf.pin.pin_file) l
in
let show global_options fields show_empty raw where
list_files file normalise no_lint just_file all_versions sort atom_locs
() =
let print_just_file opamf opam =
if not no_lint then OpamFile.OPAM.print_errors opam;
let opam =
if not sort then opam else
OpamFileTools.sort_opam opam
in
if where then
OpamConsole.msg "%s\n"
(match opamf with
| Some opamf ->
OpamFilename.(Dir.to_string (dirname (OpamFile.filename opamf)))
| None -> ".")
else
let opam_content_list = OpamFile.OPAM.to_list opam in
let get_field f =
try OpamListCommand.mini_field_printer ~prettify:true ~normalise
(OpamStd.List.assoc String.equal f opam_content_list)
with Not_found -> ""
in
match fields with