forked from ocaml/opam
/
opamMain.ml
2523 lines (2483 loc) · 103 KB
/
opamMain.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-2015 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 OpamTypesBase
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.git () <> None 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
Printf.eprintf "!! %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 =
let no_self_upgrade =
mk_flag ~section:global_option_section ["no-self-upgrade"]
"OPAM will replace itself with a newer binary found \
at $(b,OPAMROOT/opam) if present. This disables this behaviour." in
let self_upgrade no_self_upgrade options =
let self_upgrade_status =
if OpamStd.Config.env_string "NOSELFUPGRADE" =
Some self_upgrade_bootstrapping_value
then `Running
else if no_self_upgrade then `Disable
else if OpamStd.Config.env_bool "NOSELFUPGRADE" = Some true then `Disable
else `None
in
if self_upgrade_status = `None then
switch_to_updated_self
OpamStd.Option.Op.(options.debug_level ++
OpamStd.Config.env_level "DEBUG" +! 0 > 0)
(OpamStateConfig.opamroot ?root_dir:options.opt_root ());
if not options.safe_mode && Unix.getuid () = 0 then
OpamConsole.warning "Running as root is not recommended";
options, self_upgrade_status
in
Term.(pure self_upgrade $ no_self_upgrade $ global_options)
let apply_global_options (options,self_upgrade) =
apply_global_options options;
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 init_dot_profile shell dot_profile =
match dot_profile with
| Some n -> n
| None -> OpamFilename.of_string (OpamStd.Sys.guess_dot_profile shell)
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 initialises a local \"opam root\" (by default, \
$(i,~/.opam/)) that holds opam's data and packages. This is a \
necessary step for normal operation of opam.";
`P "Additionally, it prompts the user with the option to add a \
configuration hook in their shell init files. The initial software \
repositories are fetched, and an initial 'switch' can also be \
installed, according to the configuration and options.";
`P "The initial repository and defaults can be set through a \
configuration file found at $(i,~/.opamrc) or $(i,/etc/opamrc).";
`P "For further customisation once opam has been initialised, see \
$(b,opam switch) and $(b,opam repository).";
`S "CONFIGURATION FILE";
`P "Any field from the built-in initial configuration can be overriden \
through $(i,~/.opamrc), $(i,/etc/opamrc), or a file supplied with \
$(i,--config). The default configuration for this version of opam is:";
`Pre (OpamFile.InitConfig.write_to_string (OpamInitDefaults.init_config));
`P "Additional fields in the same format as for the $(i,~/.opam/config) \
file are also supported: $(b,jobs:), $(b,download-command:), \
$(b,download-jobs:), $(b,solver-criteria:), \
$(b,solver-upgrade-criteria:), \
$(b,solver-fixup-criteria:), $(b,solver:), $(b,wrap-build-commands:), \
$(b,wrap-install-commands:), $(b,wrap-remove-commands:), \
$(b,global-variables:)."
] in
let compiler =
mk_opt ["c";"compiler"] "VERSION" "Set the compiler to install"
Arg.(some string) None
in
let no_compiler =
mk_flag ["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 repository." [] 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 repository." [] in
Arg.(value & pos ~rev:true 0 (some string) None & 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 config_file =
mk_opt ["config"] "FILE"
"Use the given init config file (default is ~/.opamrc or /etc/opam, \
if present)"
Arg.(some & OpamArg.filename) None
in
let no_config_file =
mk_flag ["default-config"]
"Use the built-in default configuration, bypassing any opamrc file found \
on the system"
in
let bypass_checks =
mk_flag ["bypass-checks"]
"Skip checks on required or recommended tools, \
and assume everything is fine"
in
let init global_options
build_options repo_kind repo_name repo_url
no_setup auto_setup shell dot_profile_o
compiler no_compiler config_file no_config_file bypass_checks =
apply_global_options global_options;
apply_build_options build_options;
let config_file =
if no_config_file then None else
match config_file with
| Some f -> Some (OpamFile.make f)
| None -> OpamPath.init_config_file ()
in
let init_config = match config_file with
| None -> None
| Some cf ->
try
let r = OpamFile.InitConfig.read cf in
OpamConsole.note "Will configure defaults from %s"
(OpamFile.to_string cf);
Some r
with e ->
OpamConsole.error
"Error in configuration file, fix it or use '--default-config' or \
'--config FILE':";
OpamConsole.errmsg "%s" (Printexc.to_string e);
OpamStd.Sys.exit 10
in
let repo =
OpamStd.Option.map (fun url ->
let repo_url = OpamUrl.parse ?backend:repo_kind url in
let repo_root =
OpamRepositoryPath.create (OpamStateConfig.(!r.root_dir))
repo_name
in
{ repo_root; repo_name; repo_url; repo_priority = 0 })
repo_url
in
let update_config =
if no_setup then `no
else if auto_setup then `yes
else `ask in
let dot_profile = init_dot_profile shell dot_profile_o in
let gt, rt, default_compiler =
OpamClient.init
?init_config ?repo ~bypass_checks
shell dot_profile update_config
in
if not no_compiler &&
OpamFile.Config.installed_switches gt.config = [] then
match compiler with
| Some comp ->
let packages =
OpamSwitchCommand.guess_compiler_package rt comp
in
OpamSwitchCommand.switch_with_autoinstall
gt ~packages (OpamSwitch.of_string comp)
|> ignore
| None ->
let candidates = OpamFormula.to_dnf default_compiler in
let all_packages = OpamSwitchCommand.get_compiler_packages rt in
let compiler_packages =
try
Some (List.find (fun atoms ->
let names = List.map fst atoms in
let pkgs = OpamFormula.packages_of_atoms all_packages atoms in
List.for_all (OpamPackage.has_name pkgs) names)
candidates)
with Not_found -> None
in
match compiler_packages with
| Some packages ->
OpamSwitchCommand.switch_with_autoinstall
gt ~packages (OpamSwitch.of_string "default")
|> ignore
| None ->
OpamConsole.note
"No compiler selected, and no available default switch found: \
no switch has been created.\n\
Use 'opam switch create <compiler>' to get started."
in
Term.(pure init
$global_options $build_options $repo_kind_flag $repo_name $repo_url
$no_setup $auto_setup $shell_opt $dot_profile_flag $compiler $no_compiler
$config_file $no_config_file $bypass_checks),
term_info "init" ~doc ~man
(* LIST *)
let list_doc = "Display the list of available packages."
let list =
let doc = list_doc in
let selection_docs = "PACKAGE SELECTION" in
let display_docs = "OUTPUT FORMAT" in
let man = [
`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 ("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)."
] in
let state_selector =
let docs = selection_docs in
Arg.(value & vflag_all [] [
OpamListCommand.Any, info ~docs ["A";"all"]
~doc:"Include all, even uninstalled or unavailable packages";
OpamListCommand.Installed, info ~docs ["i";"installed"]
~doc:"List installed packages only. This is the default when no \
further arguments are supplied";
OpamListCommand.Root, info ~docs ["roots";"installed-roots"]
~doc:"List only packages that were explicitely installed, excluding \
the ones installed as dependencies";
OpamListCommand.Available, info ~docs ["a";"available"]
~doc:"List only packages that are available on the current system";
OpamListCommand.Installable, info ~docs ["installable"]
~doc:"List only packages that can be installed on the current switch \
(this calls the solver and may be more costly)";
OpamListCommand.Compiler, info ~docs ["base"]
~doc:"List only the immutable base of the current switch (i.e. \
compiler packages)";
OpamListCommand.Pinned, info ~docs ["pinned"]
~doc:"List only the pinned packages";
])
in
let depends_on =
let doc =
"List only packages that depend on one of (comma-separated) $(docv)."
in
Arg.(value & opt (list atom) [] &
info ~doc ~docs:selection_docs ~docv:"PACKAGES" ["depends-on"])
in
let required_by =
let doc = "List only the dependencies of (comma-separated) $(docv)." in
Arg.(value & opt (list atom) [] &
info ~doc ~docs:selection_docs ~docv:"PACKAGES" ["required-by"])
in
let resolve =
let doc =
"Restrict to a solution to install (comma-separated) $(docv), $(i,i.e.) \
a consistent set of packages including those. This is subtly different \
from `--required-by --recursive`, which is more predictable and can't \
fail, but lists all dependencies independently without ensuring \
consistency. \
Without `--installed`, the answer is self-contained and independent of \
the current installation. With `--installed', it's computed from the \
set of currently installed packages. \
`--no-switch` further makes the solution independent from the \
currently pinned packages, architecture, and compiler version. \
The combination with `--depopts' is not supported."
in
Arg.(value & opt (list atom) [] &
info ~doc ~docs:selection_docs ~docv:"PACKAGES" ["resolve"])
in
let recursive =
mk_flag ["recursive"] ~section:selection_docs
"With `--depends-on' and `--required-by', display all transitive \
dependencies rather than just direct dependencies." in
let depopts =
mk_flag ["depopts"] ~section:selection_docs
"Include optional dependencies in dependency requests."
in
let nobuild =
mk_flag ["nobuild"] ~section:selection_docs
"Exclude build dependencies (they are included by default)."
in
let dev =
mk_flag ["dev"] ~section:selection_docs
"Include development packages in dependencies."
in
let doc_flag =
mk_flag ["doc"] ~section:selection_docs
"Include doc-only dependencies."
in
let test =
mk_flag ["t";"test"] ~section:selection_docs
"Include test-only dependencies."
in
let repos =
mk_opt ["repos"] "REPOS" ~section:selection_docs
"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 field_match =
mk_opt_all ["field-match"] "FIELD:PATTERN" ~section:selection_docs
"Filter packages with a match for $(i,PATTERN) on the given $(i,FIELD)"
Arg.(pair ~sep:':' string string)
in
let has_flag =
mk_opt_all ["has-flag"] "FLAG" ~section:selection_docs
("Only include packages which have the given flag set. Package flags are \
one of: "^
(OpamStd.List.concat_map " "
(Printf.sprintf "$(b,%s)" @* string_of_pkg_flag)
all_package_flags))
((fun s -> match pkg_flag_of_string s with
| Pkgflag_Unknown s ->
`Error ("Invalid package flag "^s^", must be one of "^
OpamStd.List.concat_map " " string_of_pkg_flag
all_package_flags)
| f -> `Ok f),
fun fmt flag ->
Format.pp_print_string fmt (string_of_pkg_flag flag))
in
let has_tag =
mk_opt_all ["has-tag"] "TAG" ~section:selection_docs
"Only includes packages which have the given tag set"
Arg.string
in
let no_switch =
mk_flag ["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 depexts =
mk_opt ["e";"external"] "TAGS" ~section:display_docs
"Instead of displaying the packages, display their external dependencies \
that are associated with any subset of the given $(i,TAGS) (OS, \
distribution, etc.). This excludes other display options. \
Common tags include `debian', `x86', `osx', `homebrew', `source'... \
Without $(i,TAGS), display the tags and all associated external \
dependencies. \
Rather than using this directly, you should probably head for the \
`depext' plugin, that can infer your system's tags and handle \
the system installations. Run `opam depext'."
Arg.(some & list string) None in
let print_short =
mk_flag ["short";"s"] ~section:display_docs
"Don't print a header, and sets the default columns to $(b,name) only. \
If you need package versions included, use $(b,--columns=package) \
instead"
in
let sort =
mk_flag ["sort";"S"] ~section:display_docs
"Sort the packages in dependency order (i.e. an order in which they \
could be individually installed.)"
in
let columns =
mk_opt ["columns"] "COLUMNS" ~section:display_docs
(Printf.sprintf "Select the columns to display among: %s.\n\
The default is $(b,name) when $(i,--short) is present \
and %s otherwise."
(OpamStd.List.concat_map ", " (fun (_,f) -> Printf.sprintf "$(b,%s)" f)
OpamListCommand.field_names)
(OpamStd.List.concat_map ", "
(fun f -> Printf.sprintf "$(b,%s)" (OpamListCommand.string_of_field f))
OpamListCommand.default_list_format))
Arg.(some & list opamlist_column) None
in
let all_versions = mk_flag ["all-versions"] ~section:selection_docs
"Normally, when multiple versions of a package match, only one is shown \
in the output (the installed one, the pinned-to one, or, failing that, \
the highest one available or the highest one). This flag disables this \
behaviour and shows all matching versions. This also changes the \
default display format to include package versions instead of just \
package names (including when --short is set)."
in
let normalise = mk_flag ["normalise"] ~section:display_docs
"Print the values of opam fields normalised"
in
let wrap = mk_flag ["wrap"] ~section:display_docs
"Wrap long lines, the default being to truncate when displaying on a \
terminal, or to keep as is otherwise"
in
let separator =
Arg.(value & opt string " " & info ["separator"]
~docv:"STRING" ~docs:display_docs
~doc:"Set the column-separator string")
in
let list global_options state_selector field_match
depends_on required_by resolve recursive depopts no_switch
depexts nobuild dev doc test repos has_flag has_tag
print_short sort columns all_versions normalise wrap separator
packages =
apply_global_options global_options;
let no_switch =
no_switch || OpamStateConfig.(!r.current_switch) = None
in
let state_selector =
if state_selector = [] then
if no_switch then Empty
else if
depends_on = [] && required_by = [] && resolve = [] &&
packages = [] && field_match = [] && has_flag = [] && has_tag = []
then Atom OpamListCommand.Installed
else Or (Atom OpamListCommand.Installed,
Atom OpamListCommand.Available)
else OpamFormula.ands (List.map (fun x -> Atom x) state_selector)
in
let dependency_toggles = {
OpamListCommand.
recursive; depopts; build = not nobuild; test; doc; dev
} in
let pattern_toggles ?(exact=true) field = {
OpamListCommand.
exact;
case_sensitive = false;
fields = [field];
glob = true;
ext_fields = false;
} in
let filter =
OpamFormula.ands
(state_selector ::
List.map (fun x -> Atom x)
((match depends_on with [] -> [] | deps ->
[OpamListCommand.Depends_on (dependency_toggles, deps)]) @
(match required_by with [] -> [] | rdeps ->
[OpamListCommand.Required_by (dependency_toggles, rdeps)]) @
(match resolve with [] -> [] | deps ->
[OpamListCommand.Solution (dependency_toggles, deps)]) @
(if no_switch then [] else
match repos with None -> [] | Some repos ->
[OpamListCommand.From_repository repos]) @
(List.map (fun (field,patt) ->
OpamListCommand.Pattern
(pattern_toggles ~exact:false field, patt))
field_match) @
(List.map (fun flag -> OpamListCommand.Flag flag) has_flag) @
(List.map (fun tag -> OpamListCommand.Tag tag) has_tag)) @
[OpamFormula.ors
(List.map (fun patt ->
match OpamStd.String.cut_at patt '.' with
| None ->
Atom (OpamListCommand.Pattern (pattern_toggles "name", patt))
| Some (name, version) ->
OpamFormula.ands
[Atom (OpamListCommand.Pattern
(pattern_toggles "name", name));
Atom (OpamListCommand.Pattern
(pattern_toggles "version", version))])
packages)])
in
let format =
match columns with
| Some c -> c
| None ->
let cols =
if print_short then [OpamListCommand.Name]
else OpamListCommand.default_list_format
in
if all_versions then
List.map (function
| OpamListCommand.Name -> OpamListCommand.Package
| c -> c)
cols
else cols
in
OpamGlobalState.with_ `Lock_none @@ fun gt ->
let st =
let rt = OpamRepositoryState.load `Lock_none gt in
if no_switch then OpamSwitchState.load_virtual ?repos_list:repos gt rt
else OpamSwitchState.load `Lock_none gt rt (OpamStateConfig.get_switch ())
in
if not print_short && filter <> OpamFormula.Empty 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
match depexts with
| None ->
OpamListCommand.display st
~format
~dependency_order:sort
~header:(not print_short)
~all_versions
~wrap:(if wrap then `Wrap "\\ " else `Truncate)
~separator
~normalise
results
| Some tags_list ->
OpamListCommand.print_depexts st results tags_list
in
Term.(pure list $global_options $state_selector $field_match
$depends_on $required_by $resolve $recursive $depopts
$no_switch $depexts $nobuild $dev $doc_flag $test $repos
$has_flag $has_tag
$print_short $sort $columns $all_versions
$normalise $wrap $separator
$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 installed =
mk_flag ["i";"installed"] "Search among installed packages only." in
let case_sensitive =
mk_flag ["c";"case-sensitive"] "Force the search in case sensitive mode." in
let owns_file =
let doc =
"Finds installed packages responsible for installing the given file"
in
Arg.(value & opt (some OpamArg.filename) None & info ~doc ["owns-file"])
in
let search global_options print_short installed installed_roots
case_sensitive owns_file pkgs =
apply_global_options global_options;
match owns_file with
| None ->
let filter = match installed, installed_roots with
| _, true -> `roots
| true, _ -> `installed
| _ -> `all in
let order = `normal in
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamListCommand.list gt ~print_short ~filter ~order
~exact_name:false ~case_sensitive pkgs;
`Ok ();
| Some file ->
if installed || installed_roots || case_sensitive then
`Error (true, "options conflicting with --owns-file")
else
OpamGlobalState.with_ `Lock_none @@ fun gt ->
let root = OpamStateConfig.(!r.root_dir) in
let switch =
try
List.find (fun sw ->
OpamFilename.remove_prefix (OpamPath.Switch.root root sw) file
<> OpamFilename.to_string file)
(OpamFile.Config.installed_switches gt.config)
with Not_found ->
OpamConsole.error_and_exit
"The specified file does not seem to belong to an opam switch of \
the current opam root (%s)"
(OpamFilename.Dir.to_string root)
in
let rel_name =
OpamFilename.remove_prefix (OpamPath.Switch.root root switch) file
in
let matching_change_files =
List.filter (fun change_f ->
OpamFilename.check_suffix change_f ".changes" &&
let changes =
OpamFile.Changes.safe_read (OpamFile.make change_f)
in
OpamStd.String.Map.exists
(fun f -> function
| OpamDirTrack.Removed -> false
| _ -> rel_name = f)
changes)
(OpamFilename.files (OpamPath.Switch.install_dir root switch))
in
List.iter (fun f ->
OpamConsole.msg "%s\n"
OpamFilename.(Base.to_string (basename (chop_extension f))))
matching_change_files;
`Ok ()
in
Term.ret @@
Term.(pure search $global_options
$print_short_flag $installed $installed_roots_flag $case_sensitive
$owns_file
$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 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.";
] in
let fields =
let doc =
Arg.info
~docv:"FIELDS"
~doc:("Only display the values of these fields. Fields can be selected \
among "^
OpamStd.List.concat_map ", " (Printf.sprintf "$(i,%s)" @* snd)
OpamListCommand.field_names
^". 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 suffixing a colon character (:), e.g. \
$(b,--field=depopts:).")
["f";"field"] in
Arg.(value & opt (list string) [] & doc) in
let show_empty =
mk_flag ["empty-fields"]
"Show fields that are empty. This is implied when $(b,--field) is \
given."
in
let raw =
mk_flag ["raw"] "Print the raw opam file for this package" in
let where =
mk_flag ["where"]
"Print the location of the opam file used for this package" in
let list_files =
mk_flag ["list-files"]
"List the files installed by the package. Equivalent to \
$(b,--field=installed-files), and only available for installed \
packages"
in
let file =
let doc =
Arg.info
~docv:"FILE"
~doc:"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."
["file"] in
Arg.(value & opt (some existing_filename_or_dash) None & doc) in
let normalise = mk_flag ["normalise"]
"Print the values of opam fields normalised (no newlines, no implicit \
brackets)"
in
let pkg_info global_options fields show_empty raw where
list_files file normalise packages =
apply_global_options global_options;
match file, packages with
| None, [] ->
`Error (true, "required argument PACKAGES is missing")
| Some _, _::_ ->
`Error (true,
"arguments PACKAGES and `--files' can't be specified together")
| None, pkgs ->
let fields, show_empty =
if list_files then
fields @ [OpamListCommand.(string_of_field Installed_files)],
show_empty
else fields, show_empty || fields <> []
in
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamListCommand.info gt
~fields ~raw_opam:raw ~where ~normalise ~show_empty pkgs;
`Ok ()
| Some f, [] ->
let opam = match f with
| Some f -> OpamFile.OPAM.read (OpamFile.make f)
| None -> OpamFile.OPAM.read_from_channel stdin
in
if where then
(OpamConsole.msg "%s\n"
(match f with Some f -> OpamFilename.(Dir.to_string (dirname f))
| None -> ".");
`Ok ())
else
let opam_content_list = OpamFile.OPAM.to_list opam in
let get_field f =
let f = OpamStd.String.remove_suffix ~suffix:":" f in
try OpamListCommand.mini_field_printer ~prettify:true ~normalise
(List.assoc f opam_content_list)
with Not_found -> ""
in
match fields with
| [] ->
OpamFile.OPAM.write_to_channel stdout opam; `Ok ()
| [f] ->
OpamConsole.msg "%s\n" (get_field f); `Ok ()
| flds ->
let tbl =
List.map (fun fld ->
[ OpamConsole.colorise `blue
(OpamStd.String.remove_suffix ~suffix:":" fld ^ ":");
get_field fld ])
flds
in
OpamStd.Format.align_table tbl |>
OpamStd.Format.print_table stdout ~sep:" ";
`Ok ()
in
Term.(ret
(pure pkg_info $global_options $fields $show_empty $raw $where $list_files
$file $normalise $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, [],
"Returns the bindings for the environment variables set in the current \
switch, e.g. PATH, in a format intended to be evaluated by a shell. With \
$(i,-v), add comments documenting the reason or package of origin for \
eachbinding. This is most usefully used as $(b,eval `opam config env`) to \
have further shell commands be evaluated in the proper opam context.";
"revert-env", `revert_env, [],
"Reverts environment changes made by opam, e.g. $(b,eval `opam config \
revert-env`) undoes what $(b,eval `opam config env`) did.";
"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 (ii) \
global-configuration 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,COMMAND) 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). Opam expansion takes place in \
command and args. If no switch is present on the command line or in the \
$(i,OPAMSWITCH) environment variable, $(i,OPAMSWITCH) is not set in \
$(i,COMMAND)'s environment.";
"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. Use \
$(i,-) to include global configuration variables for this switch.";
"set", `set, ["VAR";"VALUE"],
"Set the given opam variable for the current switch. Warning: changing a \
configured path will not move any files! This command does not perform \
anyvariable expansion.";
"unset", `unset, ["VAR"],
"Unset the given opam variable for the current switch. Warning: \
unsetting built-in configuration variables can cause problems!";
"set-global", `set_global, ["VAR";"VALUE"],
"Set the given variable globally in the opam root, to be visible in all \
switches";
"unset-global", `unset_global, ["VAR"],
"Unset the given global variable";
"expand", `expand, ["STRING"],
"Expand variable interpolations in the given string";
"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.";
"pef-universe", `pef, ["[FILE]"],
"Outputs the current available package universe in PEF 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 profile_doc = "Modify ~/.profile (or ~/.zshrc, etc., depending on your shell) 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 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 inplace_path_doc= "When updating the PATH variable, replace any pre-existing OPAM path \
in-place rather than putting the new path in front. This means programs \
installed in OPAM that were shadowed will remain so after \
$(b,opam config env)" in
let profile = mk_flag ["profile"] profile_doc in
let no_complete = mk_flag ["no-complete"] no_complete_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 inplace_path = mk_flag ["inplace-path"] inplace_path_doc in
let config global_options
command shell sexp inplace_path
dot_profile_o list all global user
profile no_complete params =
apply_global_options global_options;
match command, params with
| Some `env, [] ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
if OpamStateConfig.(!r.current_switch) = None then `Ok () else
OpamSwitchState.with_ `Lock_none gt @@ fun st ->
`Ok (OpamConfigCommand.env st
~csh:(shell=`csh) ~sexp ~fish:(shell=`fish) ~inplace_path)
| Some `revert_env, [] ->
`Ok (OpamConfigCommand.print_eval_env
~csh:(shell=`csh) ~sexp ~fish:(shell=`fish)
(OpamEnv.add [] []))
| Some `setup, [] ->
let user = all || user in
let global = all || global in
let profile = user || profile in
let completion = global && not no_complete in
let dot_profile = init_dot_profile shell dot_profile_o in
if list then
`Ok (OpamConfigCommand.setup_list shell dot_profile)
else if profile || completion then
let dot_profile = if profile then Some dot_profile else None in
OpamGlobalState.with_ `Lock_write @@ fun gt ->
`Ok (OpamConfigCommand.setup gt
?dot_profile ~completion ~shell
~user ~global)
else
`Ok (OpamConsole.msg
"usage: opam config setup [options]\n\
\n\
Main options\n\
\ -l, --list %s\n\
\ -a, --all %s\n\
\ --shell=<bash|sh|csh|zsh|fish>\n\
\ Configure assuming the given shell.\n\
\n\
User configuration\n\
\ -u, --user %s\n\
\ --profile %s\n\
\ --dot-profile FILE %s\n\
\n\
Global configuration\n\
\ -g,--global %s\n\
\ --no-complete %s\n\n"
list_doc all_doc
user_doc profile_doc dot_profile_doc
global_doc no_complete_doc)
| Some `exec, (_::_ as c) ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
`Ok (OpamConfigCommand.exec gt ~inplace_path c)
| Some `list, params ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
(try `Ok (OpamConfigCommand.list gt (List.map OpamPackage.Name.of_string params))
with Failure msg -> `Error (false, msg))
| Some `set, [var; value] ->
`Ok (OpamConfigCommand.set (OpamVariable.Full.of_string var) (Some value))
| Some `unset, [var] ->
`Ok (OpamConfigCommand.set (OpamVariable.Full.of_string var) None)
| Some `set_global, [var; value] ->
`Ok (OpamConfigCommand.set_global
(OpamVariable.Full.of_string var) (Some value))
| Some `unset_global, [var] ->
`Ok (OpamConfigCommand.set_global
(OpamVariable.Full.of_string var) None)
| Some `expand, [str] ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
`Ok (OpamConfigCommand.expand gt str)
| Some `var, [var] ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
(try `Ok (OpamConfigCommand.variable gt (OpamVariable.Full.of_string var))
with Failure msg -> `Error (false, msg))
| Some `subst, (_::_ as files) ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
`Ok (OpamConfigCommand.subst gt (List.map OpamFilename.Base.of_string files))
| Some `pef, _params ->
failwith "!X todo"
(*
let opam_state = OpamSwitchState.load_full_compat "config-universe"
(OpamStateConfig.get_switch ()) in
let dump oc = OpamState.dump_state opam_state oc in
(match params with
| [] -> `Ok (dump stdout)
| [file] -> let oc = open_out file in dump oc; close_out oc; `Ok ()
| _ -> bad_subcommand commands ("config", command, params))
*)
| Some `cudf, params ->
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamSwitchState.with_ `Lock_none gt @@ fun opam_state ->
let opam_univ =
OpamSwitchState.universe opam_state
~requested:(OpamPackage.names_of_packages opam_state.packages)
Depends
in
let dump oc = OpamSolver.dump_universe opam_univ oc in
(match params with
| [] -> `Ok (dump stdout)
| [file] -> let oc = open_out file in dump oc; close_out oc; `Ok ()
| _ -> bad_subcommand commands ("config", command, params))
| Some `report, [] -> (
let print label fmt = Printf.printf ("# %-15s "^^fmt^^"\n") label in
Printf.printf "# OPAM config report\n";
print "opam-version" "%s " (OpamVersion.to_string (OpamVersion.full ()));
print "self-upgrade" "%s"
(if self_upgrade_status global_options = `Running then
OpamFilename.prettify (fst (self_upgrade_exe (OpamStateConfig.(!r.root_dir))))
else "no");
print "os" "%s" (OpamStd.Sys.os_string ());
try
OpamGlobalState.with_ `Lock_none @@ fun gt ->
OpamSwitchState.with_ `Lock_none gt @@ fun state ->
let external_solver =
OpamSolverConfig.external_solver_command
~input:"$in" ~output:"$out" ~criteria:"$criteria" in
print "external-solver" "%s"
(OpamStd.Option.to_string ~none:"no" (String.concat " ")
external_solver);
if external_solver <> None then
print "criteria" "%s" (OpamSolverConfig.criteria `Default);
let nprint label n =
if n <> 0 then [Printf.sprintf "%d (%s)" n label]
else [] in
print "jobs" "%d" (Lazy.force OpamStateConfig.(!r.jobs));
print "repositories" "%s"
(let repos = state.switch_repos.repositories in