-
Notifications
You must be signed in to change notification settings - Fork 371
/
Copy pathopamFile.ml
4280 lines (3805 loc) · 143 KB
/
opamFile.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. *)
(* *)
(**************************************************************************)
(** This module contains the handlers for reading and writing all of OPAM files,
and defines their internal types (records for most of them).
We handle three types of files:
- raw text files, without lexing
- "table" files, i.e. lexing is just cutting into lines and words, returning
a string list list. These are mostly used internally
- files using the "opam syntax" and lexer, parsed using OpamFormat.Pp.V
*)
open OpamParserTypes.FullPos
open OpamTypes
open OpamTypesBase
open OpamStd.Op
module OpamParser = OpamParser.FullPos
module OpamPrinter = OpamPrinter.FullPos
module Pp = struct
include OpamPp
module V = OpamFormat.V
module I = OpamFormat.I
let warn ?pos ?(strict=OpamFormatConfig.(!r.strict)) ?exn fmt =
if strict then
match exn with
| Some e -> raise e
| None -> bad_format ?pos fmt
else
Printf.ksprintf (fun s ->
if OpamConsole.verbose () then
match exn with
| None ->
OpamConsole.warning "%s"
(OpamPp.string_of_bad_format (Bad_format (pos, s)))
| Some e ->
OpamConsole.warning "%s" (OpamPp.string_of_bad_format e))
fmt
end
open Pp.Op
type 'a t = filename
type 'a typed_file = 'a t
let make f = (f: 'a t)
let filename f = (f: 'a t :> filename)
let to_string f = OpamFilename.to_string (filename f)
let exists f = OpamFilename.exists (filename f)
module type IO_FILE = sig
type t
val format_version: OpamVersion.t
val empty: t
val write: 'a typed_file -> t -> unit
val read : 'a typed_file -> t
val read_opt: 'a typed_file -> t option
val safe_read: 'a typed_file -> t
val read_from_channel: ?filename:'a typed_file -> in_channel -> t
val read_from_string: ?filename:'a typed_file -> string -> t
val write_to_channel: ?filename:'a typed_file -> out_channel -> t -> unit
val write_to_string: ?filename:'a typed_file -> t -> string
end
module type IO_Arg = sig
val internal : string
type t
val empty : t
val of_channel : 'a typed_file -> in_channel -> t
val to_channel : 'a typed_file -> out_channel -> t -> unit
val of_string : 'a typed_file -> string -> t
val to_string : 'a typed_file -> t -> string
end
module Stats = struct
let read_files = ref []
let write_files = ref []
let print () =
let aux kind = function
| [] -> ()
| l ->
OpamConsole.msg "%d files %s:\n %s\n"
(List.length !read_files) kind (String.concat "\n " l)
in
aux "read" !read_files;
aux "write" !write_files
end
let dummy_file = OpamFilename.raw "<none>"
module MakeIO (F : IO_Arg) = struct
let log ?level fmt =
OpamConsole.log (Printf.sprintf "FILE(%s)" F.internal) ?level fmt
let slog = OpamConsole.slog
let write f v =
let filename = OpamFilename.to_string f in
let chrono = OpamConsole.timer () in
let write = OpamFilename.with_open_out_bin_atomic in
write f (fun oc -> F.to_channel f oc v);
Stats.write_files := filename :: !Stats.write_files;
log "Wrote %s atomically in %.3fs" filename (chrono ())
let read_opt f =
let filename = OpamFilename.prettify f in
let chrono = OpamConsole.timer () in
try
let ic = OpamFilename.open_in f in
try
Unix.lockf (Unix.descr_of_in_channel ic) Unix.F_RLOCK 0;
Stats.read_files := filename :: !Stats.read_files;
let r = F.of_channel f ic in
close_in ic;
log ~level:3 "Read %s in %.3fs" filename (chrono ());
Some r
with e -> OpamStd.Exn.finalise e (fun () -> close_in ic)
with
| OpamSystem.File_not_found _ ->
None
| Pp.Bad_format _ as e ->
OpamStd.Exn.fatal e;
if OpamFormatConfig.(!r.strict) then
(OpamConsole.error "%s"
(Pp.string_of_bad_format ~file:(OpamFilename.to_string f) e);
OpamConsole.error_and_exit `File_error "Strict mode: aborting")
else raise e
let read f =
match read_opt f with
| Some f -> f
| None ->
OpamSystem.internal_error "File %s does not exist or can't be read"
(OpamFilename.to_string f)
let safe_read f =
try
match read_opt f with
| Some f -> f
| None ->
log ~level:2 "Cannot find %a" (slog OpamFilename.to_string) f;
F.empty
with
| (Pp.Bad_version _ | Pp.Bad_format _) as e->
OpamConsole.error "%s [skipped]\n"
(Pp.string_of_bad_format ~file:(OpamFilename.to_string f) e);
F.empty
let read_from_f f input =
try f input with
| Pp.Bad_format _ as e ->
if OpamFormatConfig.(!r.strict) then
(OpamConsole.error "%s" (Pp.string_of_bad_format e);
OpamConsole.error_and_exit `File_error "Strict mode: aborting")
else raise e
let read_from_channel ?(filename=dummy_file) ic =
read_from_f (F.of_channel filename) ic
let read_from_string ?(filename=dummy_file) str =
read_from_f (F.of_string filename) str
let write_to_channel ?(filename=dummy_file) oc t =
F.to_channel filename oc t
let write_to_string ?(filename=dummy_file) t =
F.to_string filename t
end
(** I - Raw text files (no parsing) *)
(** Compiler and package description opam file fields: one-line title and
content. Formerly, (<repo>/packages/.../descr,
<repo>/compilers/.../<v>.descr) *)
module DescrIO = struct
let internal = "descr"
let format_version = OpamVersion.of_string "0"
type t = string * string
let empty = "", ""
let synopsis = fst
let body = snd
let full (x,y) =
match y with
| "" -> x ^ "\n"
| y -> String.concat "" [x; "\n\n"; y; "\n"]
let of_channel _ ic =
let x =
try OpamStd.String.strip (input_line ic)
with End_of_file | Sys_error _ -> "" in
let y =
try OpamStd.String.strip (OpamSystem.string_of_channel ic)
with End_of_file | Sys_error _ -> ""
in
x, y
let to_channel _ oc (x,y) =
output_string oc x;
output_char oc '\n';
if y <> "" then
(output_char oc '\n';
output_string oc y;
output_char oc '\n')
let create str =
let head, tail =
match OpamStd.String.cut_at str '\n' with
| None -> str, ""
| Some (h,t) -> h, t in
OpamStd.String.strip head, OpamStd.String.strip tail
let of_string _ = create
let to_string _ = full
end
module Descr = struct
include DescrIO
include MakeIO(DescrIO)
end
(* module Comp_descr = Descr *)
(** Raw file interface used for variable expansions ( *.in ) *)
(*
module SubstIO = struct
let internal = "subst"
type t = string
let empty = ""
let of_channel _ ic =
OpamSystem.string_of_channel ic
let to_channel _ oc t =
output_string oc t
let of_string _ str = str
let to_string _ t = t
end
module Subst = struct
include SubstIO
include MakeIO(SubstIO)
end
*)
(** II - Base word list list parser and associated file types *)
module LinesBase = struct
(* Lines of space separated words *)
type t = string list list
let format_version = OpamVersion.of_string "0"
let empty = []
let internal = "lines"
let find_escapes s len =
let rec aux acc i =
if i < 0 then acc else
let acc =
match s.[i] with
| '\\' | ' ' | '\t' | '\n' ->
let esc,count = acc in
i::esc, count + 1
| _ -> acc in
aux acc (i-1) in
aux ([],0) (len - 1)
let escape_spaces = function
| "" ->
"@"
| "@" ->
"\\@"
| str ->
let len = String.length str in
match find_escapes str len with
| [], _ -> str
| escapes, n ->
let buf = Bytes.create (len + n) in
let rec aux i = function
| ofs1::(ofs2::_ as r) ->
Bytes.blit_string str ofs1 buf (ofs1+i) (ofs2-ofs1);
Bytes.set buf (ofs2+i) '\\';
aux (i+1) r
| [ofs] ->
Bytes.blit_string str ofs buf (ofs+i) (len-ofs);
buf
| [] -> assert false
in
Bytes.to_string (aux 0 (0::escapes))
let of_channel (_:filename) ic =
OpamLineLexer.main (Lexing.from_channel ic)
let to_channel (_:filename) oc t =
List.iter (function
| [] -> ()
| w::r ->
output_string oc (escape_spaces w);
List.iter (fun w ->
output_char oc '\t';
output_string oc (escape_spaces w))
r;
output_char oc '\n')
t
let of_string (_:filename) str =
OpamLineLexer.main (Lexing.from_string str)
let to_string (_:filename) (lines: t) =
let buf = Buffer.create 1024 in
List.iter (fun l ->
(match l with
| [] -> ()
| w::r ->
Buffer.add_string buf (escape_spaces w);
List.iter (fun w ->
Buffer.add_char buf '\t';
Buffer.add_string buf (escape_spaces w))
r);
Buffer.add_string buf "\n"
) lines;
Buffer.contents buf
let file_none = OpamFilename.raw "<none>"
let pp_string =
Pp.pp
(fun ~pos:_ s -> OpamLineLexer.main (Lexing.from_string s))
(fun lines -> to_string file_none lines)
let pp_channel ic oc =
Pp.pp
(fun ~pos:_ () -> of_channel file_none ic)
(to_channel file_none oc)
end
module Lines = struct
include LinesBase
include MakeIO(LinesBase)
end
module type LineFileArg = sig
val internal: string
type t
val empty: t
val pp: (string list list, t) Pp.t
end
module LineFile (X: LineFileArg) = struct
module IO = struct
include X
let format_version = OpamVersion.of_string "0"
let to_channel _ oc t = Pp.print (Lines.pp_channel stdin oc -| pp) t
let to_string _ t = Pp.print (Lines.pp_string -| pp) t
let of_channel filename ic =
Pp.parse (Lines.pp_channel ic stdout -| pp) ~pos:(pos_file filename) ()
let of_string filename str =
Pp.parse (Lines.pp_string -| pp)
~pos:{ pos_null with filename = OpamFilename.to_string filename }
str
end
include IO
include MakeIO(IO)
end
(** (1) Internal usage only *)
(** Compiler aliases definitions (aliases): table
<name> <compiler> *)
module Aliases = LineFile(struct
let internal = "aliases"
type t = string switch_map
let empty = OpamSwitch.Map.empty
let pp =
OpamSwitch.Map.(OpamFormat.lines_map ~empty ~add ~fold) @@
Pp.of_module "switch-name" (module OpamSwitch) ^+
Pp.last
end)
(** Indices of items and their associated source repository: table
<fullname> <repo-name> <dir-prefix> *)
module Repo_index (A : OpamStd.ABSTRACT) = LineFile(struct
let internal = "repo-index"
type t = (repository_name * string option) A.Map.t
let empty = A.Map.empty
let pp =
OpamFormat.lines_map ~empty ~add:A.Map.safe_add ~fold:A.Map.fold @@
Pp.of_module "name" (module A) ^+
Pp.of_module "repository" (module OpamRepositoryName) ^+
Pp.opt Pp.last
end)
module Package_index = Repo_index(OpamPackage)
(** List of packages (<switch>/installed, <switch>/installed-roots,
<switch>/reinstall): table
<package> <version> *)
module PkgList = LineFile (struct
let internal = "package-version-list"
type t = package_set
let empty = OpamPackage.Set.empty
let pp =
OpamPackage.Set.(OpamFormat.lines_set ~empty ~add ~fold) @@
(Pp.of_module "pkg-name" (module OpamPackage.Name) ^+
Pp.last -| Pp.of_module "pkg-version" (module OpamPackage.Version))
-| Pp.pp
(fun ~pos:_ (n,v) -> OpamPackage.create n v)
(fun nv -> nv.name, nv.version)
end)
(** Lists of pinned packages (<switch>/pinned): table
<name> <pin-kind> <target>
Backwards-compatibility code, do not use *)
module Pinned_legacy = struct
type pin_option =
| Version of version
| Source of url
let pp_pin =
let looks_like_version_re =
Re.(compile @@
seq [bos; digit; rep @@ diff any (set "/\\"); eos])
in
let pin_option_of_string ?kind s =
match kind with
| Some `version ->
Version (OpamPackage.Version.of_string s)
| None when Re.execp looks_like_version_re s ->
Version (OpamPackage.Version.of_string s)
| Some (#OpamUrl.backend as backend) ->
Source (OpamUrl.parse ~backend s)
| None ->
Source (OpamUrl.parse ~handle_suffix:false s)
in
let string_of_pin_kind = function
| `version -> "version"
| `rsync -> "path"
| #OpamUrl.backend as ub -> OpamUrl.string_of_backend ub
in
let pin_kind_of_string = function
| "version" -> `version
| "path" -> `rsync
| s -> OpamUrl.backend_of_string s
in
let string_of_pin_option = function
| Version v -> OpamPackage.Version.to_string v
| Source url -> OpamUrl.to_string url
in
let kind_of_pin_option = function
| Version _ -> `version
| Source url -> (url.OpamUrl.backend :> pin_kind)
in
Pp.pp
~name:"?pin-kind pin-target"
(fun ~pos -> function
| [x] -> pin_option_of_string x
| [k;x] -> pin_option_of_string ~kind:(pin_kind_of_string k) x
| _ -> Pp.bad_format ~pos "Invalid number of fields")
(fun x -> [string_of_pin_kind (kind_of_pin_option x);
string_of_pin_option x])
include LineFile(struct
let internal = "pinned"
type t = pin_option OpamPackage.Name.Map.t
let empty = OpamPackage.Name.Map.empty
let pp =
OpamPackage.Name.Map.(OpamFormat.lines_map ~empty ~add:safe_add ~fold) @@
Pp.of_module "pkg-name" (module OpamPackage.Name) ^+
pp_pin
end)
end
external open_env_updates:
('a, euok_writeable) env_update list
-> ('a, [> euok_writeable]) env_update list = "%identity"
(* cf. tests/lib/typeGymnastics.ml *)
(** Cached environment updates (<switch>/.opam-switch/environment
<opam-root>/.last-env/env-* last env files) *)
module Environment = struct include LineFile(struct
let internal = "environment"
type t = (spf_resolved, euok_writeable) env_update list
let empty = []
type optional_parts = [
| `comment of string
| `format of separator * path_format
| `norewrite
| `comment_format of string * separator * path_format
| `comment_norewrite of string
]
let pp =
let path_format : (string, path_format) Pp.t =
Pp.of_pair "path-format"
((function
| "host" -> Host
| "target" -> Target
| "target-quoted" -> Target_quoted
| "host-quoted" -> Host_quoted
| _ -> Pp.unexpected ()),
OpamTypesBase.string_of_path_format)
in
let separator : (string, separator) Pp.t =
Pp.of_pair "separator"
((function
| ":" -> SColon
| ";" -> SSemiColon
| _ -> Pp.unexpected ()),
(fun sep -> String.make 1 (char_of_separator sep)))
in
let env : (string, OpamParserTypes.FullPos.env_update_op_kind) Pp.t =
(Pp.of_pair "env_update_op"
(OpamLexer.FullPos.env_update_op, OpamPrinter.env_update_op_kind))
in
let failparse name = failwith (Printf.sprintf "parse <%s>" name) in
let failprint name = failwith (Printf.sprintf "print <%s>" name) in
let norewrite: (string, [ `norewrite ]) Pp.t =
let name = "norewrite" in
Pp.of_pair name
((function "norewrite" -> `norewrite | _ -> failparse name),
(function `norewrite -> "norewrite" ))
in
let comment_and_sepformat : (string list, optional_parts) Pp.t =
(separator ^+ path_format ^+ (Pp.last -| Pp.identity))
-| (let name = "separator-pathi-format-comment" in
Pp.of_pair name
((fun (sep, (fmt, comment)) ->
`comment_format (comment, sep, fmt)),
(function
| `comment_format (comment, sep, fmt) -> sep, (fmt, comment)
| _ -> failprint name)))
in
let comment_and_norewrite : (string list, optional_parts) Pp.t =
(norewrite ^+ (Pp.last -| Pp.identity))
-| (let name = "norewrite-comment" in
Pp.of_pair name
((fun (`norewrite, comment) ->
`comment_norewrite comment),
(function
| `comment_norewrite comment -> `norewrite, comment
| _ -> failprint name)))
in
let only_comment : (string list, optional_parts) Pp.t =
Pp.singleton
-| (let name = "only-comment" in
Pp.of_pair name
((fun x -> `comment x),
(function `comment x -> x | _ -> failprint name)))
in
let only_format : (string list, optional_parts) Pp.t =
(separator ^+ (Pp.last -| path_format))
-| (let name = "only-path-format" in
Pp.of_pair name
((fun sh -> `format sh),
(function `format sh -> sh | _ -> failprint name)))
in
let only_norewrite : (string list, optional_parts) Pp.t =
Pp.last -| norewrite
-| (let name = "only-norewrite" in
Pp.of_pair name
((function `norewrite -> `norewrite),
(function `norewrite -> `norewrite | _ -> failprint name)))
in
let optional_parts : (string list, optional_parts option) Pp.t =
Pp.opt
@@ Pp.fallback comment_and_sepformat
@@ Pp.fallback comment_and_norewrite
@@ Pp.fallback only_norewrite
@@ Pp.fallback only_format only_comment
in
(OpamFormat.lines_set ~empty:[] ~add:OpamStd.List.cons
~fold:List.fold_right
@@ (Pp.identity
^+ env
^+ Pp.identity
^+ optional_parts))
-| Pp.pp (fun ~pos:_ -> List.rev) List.rev
let pp =
pp -|
Pp.map_list
(Pp.pp
(fun ~pos:_ (envu_var, (envu_op, (envu_value, optional_parts))) ->
let envu = {
envu_var; envu_op = op_of_raw envu_op; envu_value; envu_comment = None;
envu_rewrite = Some (SPF_Resolved None);
} in
match optional_parts with
| None -> envu
| Some (`comment_format (comment, sep, fmt)) ->
{ envu with
envu_comment = Some comment;
envu_rewrite = Some (SPF_Resolved (Some (sep, fmt)));
}
| Some (`comment comment) ->
{ envu with
envu_comment = Some comment;
}
| Some (`format (sep, fmt)) ->
{ envu with
envu_rewrite = Some (SPF_Resolved (Some (sep, fmt)));
}
| Some `norewrite ->
{ envu with
envu_rewrite = None;
}
| Some (`comment_norewrite comment) ->
{ envu with
envu_comment = Some comment;
envu_rewrite = None;
}
)
(fun {envu_var; envu_op; envu_value; envu_comment; envu_rewrite} ->
let optional_parts =
match envu_comment, envu_rewrite with
| None, Some (SPF_Resolved None) ->
None
| None, Some (SPF_Resolved (Some (sep, fmt))) ->
Some (`format (sep, fmt))
| None, None ->
Some `norewrite
| Some comment, Some (SPF_Resolved (Some (sep, fmt))) ->
Some (`comment_format (comment, sep, fmt))
| Some comment, Some (SPF_Resolved None) ->
Some (`comment comment)
| Some comment, None ->
Some (`comment_norewrite comment)
in
(envu_var, (raw_of_op envu_op, (envu_value, optional_parts)))))
end)
let read file =
open_env_updates (read file)
let read_opt file =
Option.map open_env_updates (read_opt file)
let safe_read file =
open_env_updates (safe_read file)
let read_from_channel ?filename ch =
open_env_updates (read_from_channel ?filename ch)
let read_from_string ?filename s =
open_env_updates (read_from_string ?filename s)
end
(** (2) Part of the public repository format *)
(** repository index files ("urls.txt"): table
<filename> <md5> <perms> *)
module File_attributes = LineFile(struct
let internal = "file_attributes"
type t = file_attribute_set
let empty = OpamFilename.Attribute.Set.empty
let pp =
OpamFilename.Attribute.Set.(OpamFormat.lines_set ~empty ~add ~fold) @@
(Pp.of_module "file" (module OpamFilename.Base) ^+
Pp.of_pair "checksum" OpamHash.(of_string, contents) ^+
Pp.opt (Pp.last -| Pp.of_pair "perm" (int_of_string, string_of_int))
) -|
Pp.pp
(fun ~pos:_ (base,(hash,perm)) ->
OpamFilename.Attribute.create base hash perm)
(fun att -> OpamFilename.Attribute.(base att, (md5 att, perm att)))
end)
(** (3) Available in interface *)
(** Old Switch export/import format: table
<name> <version> <installed-state> [pinning-kind] [pinning-url] *)
module StateTable = struct
let internal = "export"
module M = OpamPackage.Name.Map
type t = switch_selections
let empty = {
sel_installed = OpamPackage.Set.empty;
sel_roots = OpamPackage.Set.empty;
sel_compiler = OpamPackage.Set.empty;
sel_pinned = OpamPackage.Set.empty;
}
let pp_state =
Pp.pp ~name:"pkg-state"
(fun ~pos:_ -> function
| "compiler" -> `Compiler
| "root" -> `Root
| "noroot" | "installed" -> `Installed
| "uninstalled" -> `Uninstalled
| "uninstalled-compiler" -> `Uninstalled_compiler
| _ -> Pp.unexpected ())
(function
| `Compiler -> "compiler"
| `Root -> "root"
| `Installed -> "installed"
| `Uninstalled -> "uninstalled"
| `Uninstalled_compiler -> "uninstalled-compiler")
let pp_lines =
M.(OpamFormat.lines_map ~empty ~add:safe_add ~fold) @@
Pp.of_module "pkg-name" (module OpamPackage.Name) ^+
Pp.of_module "pkg-version" (module OpamPackage.Version) ^+
(Pp.opt (pp_state ^+ Pp.opt Pinned_legacy.pp_pin) -|
Pp.default (`Root, None))
(* Convert from one name-map to type t *)
let pp =
pp_lines -| Pp.pp
(fun ~pos:_ map ->
M.fold
(fun name (version,(state,pin)) t ->
let nv = OpamPackage.create name version in
{
sel_installed = (match state with
| `Installed | `Root | `Compiler ->
OpamPackage.Set.add nv t.sel_installed
| `Uninstalled | `Uninstalled_compiler ->
t.sel_installed);
sel_roots = (match state with
| `Root | `Compiler ->
OpamPackage.Set.add nv t.sel_roots
| `Installed | `Uninstalled | `Uninstalled_compiler ->
t.sel_roots);
sel_compiler = (match state with
| `Compiler | `Uninstalled_compiler ->
OpamPackage.Set.add nv t.sel_compiler
| `Root | `Installed | `Uninstalled ->
t.sel_compiler);
sel_pinned = (match pin with
| Some (Pinned_legacy.Version v) ->
OpamPackage.Set.add (OpamPackage.create name v)
t.sel_pinned
| Some _ ->
OpamPackage.Set.add (OpamPackage.create name version)
t.sel_pinned
| None -> t.sel_pinned);
})
map
empty)
(fun t ->
M.empty |>
OpamPackage.Set.fold (fun nv ->
M.add nv.name
(nv.version, (`Installed, None)))
t.sel_installed |>
OpamPackage.Set.fold (fun nv ->
M.add nv.name
(nv.version, (`Root, None)))
t.sel_roots |>
OpamPackage.Set.fold (fun nv acc ->
let name = nv.name in
try
let (v, _) = M.find name acc in
M.add name (v, (`Compiler, None)) acc
with Not_found ->
M.add name
(nv.version, (`Uninstalled_compiler, None))
acc)
t.sel_compiler |>
OpamPackage.Set.fold (fun nv map ->
let state =
try let _, (state, _) = M.find nv.name map in state
with Not_found -> `Uninstalled
in
(* Incorrect: marks all pins as version. But this is deprecated. *)
M.add nv.name
(nv.version, (state, Some (Pinned_legacy.Version nv.version))) map)
t.sel_pinned)
end
module LegacyState = struct
type t = switch_selections
include (LineFile (StateTable) : IO_FILE with type t := t)
end
(** III - Opam Syntax parser and associated file types *)
module Syntax = struct
(* Idea: have a [(ic, oc_with_lock * t) pp] that can be used to reading and
re-writing files with a guarantee that it hasn't been rewritten in the
meantime *)
let parser_main lexbuf filename =
let error msg =
let curr = lexbuf.Lexing.lex_curr_p in
let start = lexbuf.Lexing.lex_start_p in
let pos =
{ filename = curr.Lexing.pos_fname;
start =
start.Lexing.pos_lnum,
start.Lexing.pos_cnum - start.Lexing.pos_bol;
stop = (* XXX here we take current position, where error occurs as end position *)
curr.Lexing.pos_lnum,
curr.Lexing.pos_cnum - curr.Lexing.pos_bol;
}
in
raise (OpamPp.Bad_format (Some pos, msg))
in
let filename = OpamFilename.to_string filename in
lexbuf.Lexing.lex_curr_p <- { lexbuf.Lexing.lex_curr_p with
Lexing.pos_fname = filename };
match OpamParser.main OpamLexer.token lexbuf filename with
| {file_contents =
[{pelem = Variable({pelem = "opam-version"; _},
{pelem = String ver; _}); _ };
{pelem = Section {section_kind = {pelem = "#"; _}; _}; _}]; _}
when OpamVersion.(compare (nopatch (of_string ver))
(nopatch OpamVersion.current)) <= 0 ->
error "Parse error"
| opamfile -> opamfile
| exception OpamLexer.Error msg -> error msg
| exception Parsing.Parse_error -> error "Parse error"
let pp_channel filename ic oc =
Pp.pp
(fun ~pos:_ () ->
let lexbuf = Lexing.from_channel ic in
parser_main lexbuf filename)
(fun file ->
let fmt = Format.formatter_of_out_channel oc in
OpamPrinter.format_opamfile fmt file)
let of_channel (filename:filename) (ic:in_channel) =
Pp.parse ~pos:(pos_file filename) (pp_channel filename ic stdout) ()
let to_channel filename oc t =
Pp.print (pp_channel filename stdin oc) t
let of_string (filename:filename) str =
let lexbuf = Lexing.from_string str in
parser_main lexbuf filename
let to_string _file_name t =
OpamPrinter.opamfile t
let to_string_with_preserved_format
filename ?(format_from=filename) ?format_from_string
~empty ?(sections=[]) ~fields pp t =
let current_str_opt =
match format_from_string with
| Some s -> Some s
| None ->
try Some (OpamFilename.read format_from)
with OpamSystem.File_not_found _ -> None
in
match current_str_opt with
| None -> to_string filename (Pp.print pp (filename, t))
| Some str ->
let syn_file = of_string filename str in
let syn_t = Pp.print pp (filename, t) in
let it_ident it = match it.pelem with
| Variable (f, _) -> `Var f.pelem
| Section ({section_kind = k; section_name = n; _}) ->
`Sec (k.pelem, OpamStd.Option.map (fun x -> x.pelem) n)
in
let lines_index =
let rec aux acc s =
let until =
try Some (String.index_from s (List.hd acc) '\n')
with Not_found -> None
in
match until with
| Some until -> aux (until+1 :: acc) s
| None -> Array.of_list (List.rev acc)
in
aux [0] str
in
let pos_index (li,col) = lines_index.(li - 1) + col in
let extract start stop =
if stop < start then raise Not_found;
String.sub str start (stop - start)
in
let value_list_str lastpos vlst vlst_raw =
let extract_pos start stop = extract (pos_index start) (pos_index stop) in
let def_blank blank = OpamStd.Option.default "\n " blank in
let find_split f =
let rec aux p = function
| x::r when f x -> Some (p, x, r)
| p::r -> aux (Some p) r
| [] -> None
in
aux None
in
let full_vlst_raw = vlst_raw in
let rec aux lastpos blank acc vlst vlst_raw =
match vlst, vlst_raw with
| v::r, vraw :: rraw when OpamPrinter.value_equals v vraw ->
let blank = extract lastpos (pos_index vraw.pos.start) in
let str = extract_pos vraw.pos.start vraw.pos.stop in
let new_v = blank ^ str in
let blank = Some blank in
let lastpos = pos_index vraw.pos.stop in
aux lastpos blank (new_v :: acc) r rraw
| v::r , _ ->
(match find_split (OpamPrinter.value_equals v) full_vlst_raw with
| Some (pvraw, vraw, rraw) ->
let str = extract_pos vraw.pos.start vraw.pos.stop in
let blank, lastpos =
if pos_index vraw.pos.start - lastpos <= 0 then
def_blank blank, lastpos
else
(let start = match pvraw with
| Some pvraw -> pos_index pvraw.pos.stop
| None -> lastpos
in
let stop = pos_index vraw.pos.start in
extract start stop),
pos_index vraw.pos.stop
in
let new_v = blank ^ str in
let blank = Some blank in
aux lastpos blank (new_v :: acc) r rraw
| None ->
let blank, rraw, lastpos =
match vlst_raw with
| vraw :: rraw ->
let blank = extract lastpos (pos_index vraw.pos.start) in
let rraw, lastpos =
if OpamStd.List.find_opt
(OpamPrinter.value_equals vraw) vlst <> None then
vlst_raw, lastpos
else
rraw, pos_index vraw.pos.stop
in