-
Notifications
You must be signed in to change notification settings - Fork 368
/
opamSystem.ml
1626 lines (1490 loc) · 51.9 KB
/
opamSystem.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. *)
(* *)
(**************************************************************************)
type install_warning =
[ `Add_exe | `Install_dll | `Install_script | `Install_unknown
| `Cygwin | `Msys2 | `Tainted of [`Msys2 | `Cygwin] | `Cygwin_libraries ]
type install_warning_fn = string -> install_warning -> unit
exception Process_error of OpamProcess.result
exception Internal_error of string
exception Command_not_found of string
exception File_not_found of string
exception Permission_denied of string
let log ?level fmt = OpamConsole.log "SYSTEM" ?level fmt
let slog = OpamConsole.slog
let internal_error fmt =
Printf.ksprintf (fun str ->
log "error: %s" str;
raise (Internal_error str)
) fmt
let process_error r =
if r.OpamProcess.r_signal = Some Sys.sigint then raise Sys.Break
else raise (Process_error r)
let raise_on_process_error r =
if OpamProcess.is_failure r then raise (Process_error r)
let command_not_found cmd =
raise (Command_not_found cmd)
let permission_denied cmd =
raise (Permission_denied cmd)
module Sys2 = struct
(* same as [Sys.is_directory] except for symlinks, which returns always [false]. *)
let is_directory file =
try Unix.( (lstat file).st_kind = S_DIR )
with Unix.Unix_error _ as e -> raise (Sys_error (Printexc.to_string e))
end
let file_or_symlink_exists f =
try ignore (Unix.lstat f); true
with Unix.Unix_error (Unix.ENOENT, _, _) -> false
let (/) = Filename.concat
let temp_basename prefix =
Printf.sprintf "%s-%d-%06x" prefix (OpamStubs.getpid ()) (Random.int 0xFFFFFF)
let rec mk_temp_dir ?(prefix="opam") () =
let s = Filename.get_temp_dir_name () / temp_basename prefix in
if Sys.file_exists s then
mk_temp_dir ()
else
s
let safe_mkdir dir =
try
log "mkdir %s" dir;
Unix.mkdir dir 0o755
with
Unix.Unix_error(Unix.EEXIST,_,_) -> ()
let mkdir dir =
let rec aux dir =
if not (Sys.file_exists dir) then begin
aux (Filename.dirname dir);
safe_mkdir dir;
end in
aux dir
let rm_command =
if Sys.win32 then
"cmd /d /v:off /c rd /s /q"
else
"rm -rf"
let remove_dir dir =
log "rmdir %s" dir;
if Sys.file_exists dir then (
let err = Sys.command (Printf.sprintf "%s %s" rm_command (Filename.quote dir)) in
if err <> 0 then
internal_error "Cannot remove %s (error %d)." dir err
)
let temp_files = Hashtbl.create 1024
let logs_cleaner =
let to_clean = ref OpamStd.String.Set.empty in
OpamStd.Sys.at_exit
(fun () ->
OpamStd.String.Set.iter (fun f ->
try
Unix.unlink f;
(* Only log the item if unlink succeeded *)
log "logs_cleaner: rm: %s" f
with Unix.Unix_error _ -> ())
!to_clean;
if OpamCoreConfig.(!r.log_dir = default.log_dir) then
try Unix.rmdir OpamCoreConfig.(default.log_dir)
with Unix.Unix_error _ -> ());
fun tmp_dir ->
if OpamCoreConfig.(!r.keep_log_dir) then
to_clean := OpamStd.String.Set.remove tmp_dir !to_clean
else
to_clean := OpamStd.String.Set.add tmp_dir !to_clean
let rec temp_file ?(auto_clean=true) ?dir prefix =
let temp_dir = match dir with
| None -> OpamCoreConfig.(!r.log_dir)
| Some d -> d in
mkdir temp_dir;
let file = temp_dir / temp_basename prefix in
if Hashtbl.mem temp_files file then
temp_file ~auto_clean ?dir prefix
else (
Hashtbl.add temp_files file true;
if auto_clean then logs_cleaner file;
file
)
let remove_file file =
if
try ignore (Unix.lstat file); true with Unix.Unix_error _ -> false
then (
log "rm %s" file;
try
try Unix.unlink file
with Unix.Unix_error(EACCES, _, _) when Sys.win32 ->
(* Attempt to remove the read-only bit on Windows *)
Unix.chmod file 0o666;
Unix.unlink file
with Unix.Unix_error _ as e ->
internal_error "Cannot remove %s (%s)." file (Printexc.to_string e)
)
let string_of_channel ic =
let n = 32768 in
let s = Bytes.create n in
let b = Buffer.create 1024 in
let rec iter ic b s =
let nread =
try input ic s 0 n
with End_of_file -> 0 in
if nread > 0 then (
Buffer.add_subbytes b s 0 nread;
iter ic b s
) in
iter ic b s;
Buffer.contents b
let read file =
let ic =
try open_in_bin file
with Sys_error _ -> raise (File_not_found file) in
Unix.lockf (Unix.descr_of_in_channel ic) Unix.F_RLOCK 0;
let s = string_of_channel ic in
close_in ic;
s
let write file contents =
mkdir (Filename.dirname file);
let oc =
try open_out_bin file
with Sys_error _ -> raise (File_not_found file)
in
Unix.lockf (Unix.descr_of_out_channel oc) Unix.F_LOCK 0;
output_string oc contents;
close_out oc
let setup_copy ?(chmod = fun x -> x) ~src ~dst () =
let ic = open_in_bin src in
try
let perm =
(Unix.fstat (Unix.descr_of_in_channel ic)).st_perm |> chmod
in
let () =
try if Unix.((lstat dst).st_kind <> S_REG) then
remove_file dst
with Unix.Unix_error(ENOENT, _, _) -> ()
in
let fd =
let flags = Unix.[ O_WRONLY; O_CREAT; O_TRUNC ] in
try Unix.openfile dst flags perm
with Unix.Unix_error(EACCES, _, _) when Sys.win32 ->
(* Attempt to remove the read-only bit on Windows *)
begin
try Unix.chmod dst 0o666
with Unix.Unix_error(_, _, _) -> ()
end;
Unix.openfile dst flags perm
in
try
if Unix.((fstat fd).st_perm) <> perm then
Unix.fchmod fd perm;
(ic, Unix.out_channel_of_descr fd)
with exn ->
OpamStd.Exn.finalise exn (fun () -> Unix.close fd)
with exn ->
OpamStd.Exn.finalise exn (fun () -> close_in ic)
let copy_channels =
let buf_len = 4096 in
let buf = Bytes.create buf_len in
let rec loop ic oc =
match input ic buf 0 buf_len with
| 0 -> ()
| n ->
output oc buf 0 n;
loop ic oc
in
loop
let copy_file_aux ?chmod ~src ~dst () =
let close_channels ic oc =
OpamStd.Exn.finally (fun () -> close_in ic) (fun () -> close_out oc) in
try
let ic, oc = setup_copy ?chmod ~src ~dst () in
OpamStd.Exn.finally (fun () -> close_channels ic oc)
(fun () -> copy_channels ic oc);
with Unix.Unix_error _ as e ->
(* Remove the partial destination file, if any. *)
(try Unix.unlink dst with Unix.Unix_error _ -> ());
internal_error "Cannot copy %s to %s (%s)." src dst (Printexc.to_string e)
let chdir dir =
try Unix.chdir dir
with Unix.Unix_error _ -> raise (File_not_found dir)
let in_dir dir fn =
let reset_cwd =
let cwd =
try Some (Sys.getcwd ())
with Sys_error _ -> None in
fun () ->
match cwd with
| None -> ()
| Some cwd -> try chdir cwd with File_not_found _ -> () in
chdir dir;
try
let r = fn () in
reset_cwd ();
r
with e ->
OpamStd.Exn.finalise e reset_cwd
let list kind dir =
try
in_dir dir (fun () ->
let d = Sys.readdir (Sys.getcwd ()) in
let d = Array.to_list d in
let l = List.filter kind d in
List.map (Filename.concat dir) (List.sort compare l)
)
with File_not_found _ -> []
let ls dir = list (fun _ -> true) dir
let files_with_links =
list (fun f -> try not (Sys.is_directory f) with Sys_error _ -> false)
let files_all_not_dir =
list (fun f -> try not (Sys2.is_directory f) with Sys_error _ -> false)
let directories_strict =
list (fun f -> try Sys2.is_directory f with Sys_error _ -> false)
let directories_with_links =
list (fun f -> try Sys.is_directory f with Sys_error _ -> false)
let rec_files dir =
let rec aux accu dir =
let d = directories_with_links dir in
let f = files_with_links dir in
List.fold_left aux (f @ accu) d in
aux [] dir
let files dir =
files_with_links dir
let rec_dirs dir =
let rec aux accu dir =
let d = directories_with_links dir in
List.fold_left aux (d @ accu) d in
aux [] dir
let dirs dir =
directories_with_links dir
let dir_is_empty dir =
try in_dir dir (fun () -> Sys.readdir (Sys.getcwd ()) = [||])
with File_not_found _ -> false
let with_tmp_dir fn =
let dir = mk_temp_dir () in
try
mkdir dir;
let e = fn dir in
remove_dir dir;
e
with e ->
OpamStd.Exn.finalise e @@ fun () ->
remove_dir dir
let in_tmp_dir fn =
with_tmp_dir @@ fun dir ->
in_dir dir fn
let with_tmp_dir_job fjob =
let dir = mk_temp_dir () in
mkdir dir;
OpamProcess.Job.finally (fun () -> remove_dir dir) (fun () -> fjob dir)
let remove file =
if (try Sys2.is_directory file with Sys_error _ -> false) then
remove_dir file
else
remove_file file
let real_path p =
(* if Filename.is_relative p then *)
match (try Some (Sys.is_directory p) with Sys_error _ -> None) with
| None ->
let rec resolve dir =
if Sys.file_exists dir then OpamCompat.Unix.normalise dir else
let parent = Filename.dirname dir in
if dir = parent then dir
else Filename.concat (resolve parent) (Filename.basename dir)
in
let p =
if Filename.is_relative p then Filename.concat (Sys.getcwd ()) p
else p
in
resolve p
| Some true -> OpamCompat.Unix.normalise p
| Some false ->
let dir = OpamCompat.Unix.normalise (Filename.dirname p) in
match Filename.basename p with
| "." -> dir
| base -> dir / base
(* else p *)
type command = string list
let default_env () =
OpamStd.Env.list () |> List.map (fun (var, v) -> var^"="^v) |> Array.of_list
let env_var env var =
let len = Array.length env in
let f = if Sys.win32 then String.uppercase_ascii else fun x -> x in
let prefix = f var^"=" in
let pfxlen = String.length prefix in
let rec aux i =
if i >= len then "" else
let s = env.(i) in
if OpamStd.String.starts_with ~prefix (f s) then
String.sub s pfxlen (String.length s - pfxlen)
else aux (i+1)
in
aux 0
let forward_to_back =
if Sys.win32 then
String.map (function '/' -> '\\' | c -> c)
else
fun x -> x
let back_to_forward =
if Sys.win32 then
String.map (function '\\' -> '/' | c -> c)
else
fun x -> x
(* OCaml 4.05.0 no longer follows the updated PATH to resolve commands. This
makes unqualified commands absolute as a workaround. *)
let t_resolve_command =
let is_external_cmd name =
let name = forward_to_back name in
OpamStd.String.contains_char name Filename.dir_sep.[0]
in
let check_perms =
if Sys.win32 then fun f ->
try (Unix.stat f).Unix.st_kind = Unix.S_REG
with e -> OpamStd.Exn.fatal e; false
else fun f ->
try
let open Unix in
let uid = geteuid () in
let groups = OpamStd.IntSet.of_list (getegid () :: Array.to_list (getgroups ())) in
let {st_uid; st_gid; st_perm; _} = stat f in
let mask =
if uid = st_uid then
0o100
else if OpamStd.IntSet.mem st_gid groups then
0o010
else
0o001
in
if (st_perm land mask) <> 0 then
true
else
match OpamACL.get_acl_executable_info f st_uid with
| None -> false
| Some [] -> true
| Some gids -> OpamStd.IntSet.(not (is_empty (inter (of_list gids) groups)))
with e -> OpamStd.Exn.fatal e; false
in
let resolve ?dir env name =
if not (Filename.is_relative name) then begin
(* absolute path *)
if not (Sys.file_exists name) then `Not_found
else if not (check_perms name) then `Denied
else `Cmd name
end else if is_external_cmd name then begin
(* relative path *)
let cmd = match dir with
| None -> name
| Some d -> Filename.concat d name
in
if not (Sys.file_exists cmd) then `Not_found
else if not (check_perms cmd) then `Denied
else `Cmd cmd
end else
(* bare command, lookup in PATH *)
(* Following the shell sematics for looking up PATH, programs with the
expected name but not the right permissions are skipped silently.
Therefore, only two outcomes are possible in that case, [`Cmd ..] or
[`Not_found]. *)
let path = OpamStd.Sys.split_path_variable (env_var env "PATH") in
let name =
if Sys.win32 && not (Filename.check_suffix name ".exe") then
name ^ ".exe"
else name
in
let possibles = OpamStd.List.filter_map (fun path ->
let candidate = Filename.concat path name in
if Sys.file_exists candidate then Some candidate else None) path
in
match List.find check_perms possibles with
| cmdname -> `Cmd cmdname
| exception Not_found ->
if possibles = [] then
`Not_found
else
`Denied
in
fun ?env ?dir name ->
let env = match env with None -> default_env () | Some e -> e in
resolve env ?dir name
let resolve_command ?env ?dir name =
match t_resolve_command ?env ?dir name with
| `Cmd cmd -> Some cmd
| `Denied | `Not_found -> None
let apply_cygpath name =
let r =
OpamProcess.run
(OpamProcess.command ~name:(temp_file "command") ~allow_stdin:false ~verbose:false "cygpath" ["--"; name])
in
OpamProcess.cleanup ~force:true r;
if OpamProcess.is_success r then
List.hd r.OpamProcess.r_stdout
else
OpamConsole.error_and_exit `Internal_error "Could not apply cygpath to %s" name
let get_cygpath_function =
if Sys.win32 then
fun ~command ->
lazy (if OpamStd.(Option.map_default Sys.is_cygwin_variant `Native (resolve_command command)) = `Cygwin then
apply_cygpath
else
fun x -> x)
else
let f = Lazy.from_val (fun x -> x) in
fun ~command:_ -> f
let apply_cygpath_path_transform path =
let r =
OpamProcess.run
(OpamProcess.command ~name:(temp_file "command") ~verbose:false "cygpath" ["--path"; "--"; path])
in
OpamProcess.cleanup ~force:true r;
if OpamProcess.is_success r then
List.hd r.OpamProcess.r_stdout
else
OpamConsole.error_and_exit `Internal_error "Could not apply cygpath --path to %s" path
let get_cygpath_path_transform =
(* We are running in a functioning Cygwin or MSYS2 environment if and only
if `cygpath` is in the PATH. *)
if Sys.win32 then
lazy (
match resolve_command "cygpath" with
| Some _ -> apply_cygpath_path_transform
| None -> fun x -> x)
else
Lazy.from_val (fun x -> x)
let runs = ref []
let print_stats () =
match !runs with
| [] -> ()
| l ->
OpamConsole.msg "%d external processes called:\n%s"
(List.length l) (OpamStd.Format.itemize ~bullet:" " (String.concat " ") l)
let log_file ?dir name = temp_file ?dir (OpamStd.Option.default "log" name)
let make_command
?verbose ?env ?name ?text ?metadata ?allow_stdin ?stdout
?dir ?(resolve_path=true)
cmd args =
let env = match env with None -> default_env () | Some e -> e in
let name = log_file name in
let verbose =
OpamStd.Option.default OpamCoreConfig.(!r.verbose_level >= 2) verbose
in
(* Check that the command doesn't contain whitespaces *)
if None <> try Some (String.index cmd ' ') with Not_found -> None then
OpamConsole.warning "Command %S contains space characters" cmd;
let full_cmd =
if resolve_path then t_resolve_command ~env ?dir cmd
else `Cmd cmd
in
match full_cmd with
| `Cmd cmd ->
OpamProcess.command
~env ~name ?text ~verbose ?metadata ?allow_stdin ?stdout ?dir
cmd args
| `Not_found -> command_not_found cmd
| `Denied -> permission_denied cmd
let run_process
?verbose ?env ~name ?metadata ?stdout ?allow_stdin command =
let env = match env with None -> default_env () | Some e -> e in
let chrono = OpamConsole.timer () in
runs := command :: !runs;
match command with
| [] -> invalid_arg "run_process"
| cmd :: args ->
if OpamStd.String.contains_char cmd ' ' then
OpamConsole.warning "Command %S contains space characters" cmd;
match t_resolve_command ~env cmd with
| `Cmd full_cmd ->
let verbose = match verbose with
| None -> OpamCoreConfig.(!r.verbose_level) >= 2
| Some b -> b in
let r =
OpamProcess.run
(OpamProcess.command
~env ~name ~verbose ?metadata ?allow_stdin ?stdout
full_cmd args)
in
let str = String.concat " " (cmd :: args) in
log ~level:2 "[%a] (in %.3fs) %s"
(OpamConsole.slog Filename.basename) name
(chrono ()) str;
r
| `Not_found -> command_not_found cmd
| `Denied -> permission_denied cmd
let command ?verbose ?env ?name ?metadata ?allow_stdin cmd =
let name = log_file name in
let r = run_process ?verbose ?env ~name ?metadata ?allow_stdin cmd in
OpamProcess.cleanup r;
raise_on_process_error r
let commands ?verbose ?env ?name ?metadata ?(keep_going=false) commands =
let name = log_file name in
let run = run_process ?verbose ?env ~name ?metadata in
let command r0 c =
match r0, keep_going with
| (`Error _ | `Exception _), false -> r0
| _ ->
let r1 = try
let r = run c in
if OpamProcess.is_success r then `Successful r else `Error r
with Command_not_found _ as e -> `Exception e
in
match r0 with `Start | `Successful _ -> r1 | _ -> r0
in
match List.fold_left command `Start commands with
| `Start -> ()
| `Successful r -> OpamProcess.cleanup r
| `Error e -> process_error e
| `Exception e -> raise e
let read_command_output ?verbose ?env ?metadata ?allow_stdin cmd =
let name = log_file None in
let r =
run_process ?verbose ?env ~name ?metadata ?allow_stdin
~stdout:(name^".out")
cmd
in
OpamProcess.cleanup r;
raise_on_process_error r;
r.OpamProcess.r_stdout
let verbose_for_base_commands () =
OpamCoreConfig.(!r.verbose_level) >= 3
let cygify f =
if Sys.win32 then
List.map (Lazy.force f)
else
fun x -> x
let copy_file src dst =
if (try Sys.is_directory src
with Sys_error _ -> raise (File_not_found src))
then internal_error "Cannot copy %s: it is a directory." src;
if (try Sys.is_directory dst with Sys_error _ -> false)
then internal_error "Cannot copy to %s: it is a directory." dst;
if file_or_symlink_exists dst
then remove_file dst;
mkdir (Filename.dirname dst);
log "copy %s -> %s" src dst;
copy_file_aux ~src ~dst ()
let copy_dir src dst =
(* MSYS2 requires special handling because its uses copying rather than
symlinks for maximum portability on Windows. However copying a source
directory containing symlinks presents a problem.
As a real example look at https://github.com/OCamlPro/ocp-indent/tree/1.8.2/tests/inplace:
$ ls -l tests/inplace/
total 0
-rw-r--r-- 1 user group 0 Aug 12 20:53 executable.ml
lrwxrwxrwx 1 user group 12 Aug 12 20:53 link.ml -> otherfile.ml
lrwxrwxrwx 1 user group 7 Aug 12 20:53 link2.ml -> link.ml
-rw-r--r-- 1 user group 0 Aug 12 20:53 otherfile.ml
With a regular copy:
cp -PRp ...\ocp-indent-1.8.1\tests ... \tmp\ocp-indent.1.8.1
it _can_ fail with:
# /usr/bin/cp: cannot create symbolic link 'C:\somewhere/tests/inplace/link.ml': No such file or directory
# /usr/bin/cp: cannot create symbolic link 'C:\somewhere/tests/inplace/link2.ml': No such file or directory
What is happening is that _if_ link2.ml is copied before link.ml, then the
copy of link2.ml will fail with "No such file or directory". What is worse,
it depends on the opaque order in which the files are copied; sometimes it
can work and sometimes it won't.
So we do a two-pass copy. The first pass copies everything except the
symlinks, and the second pass copies everything that remained. Rsync is the
perfect tool for that.
*)
if OpamStd.Sys.get_windows_executable_variant "rsync" = `Msys2 then
let convert_path = Lazy.force (get_cygpath_function ~command:"rsync") in
(* ensure that rsync doesn't recreate a subdir: add trailing '/' even if
cygpath may add one *)
let trailingslash_cygsrc =
(OpamStd.String.remove_suffix ~suffix:"/" (convert_path src)) ^ "/"
in
let cygdest = convert_path dst in
(if Sys.file_exists dst then () else mkdir (Filename.dirname dst);
command ~verbose:(verbose_for_base_commands ())
([ "rsync"; "-a"; "--no-links"; trailingslash_cygsrc; cygdest ]);
command ~verbose:(verbose_for_base_commands ())
([ "rsync"; "-a"; "--ignore-existing"; trailingslash_cygsrc; cygdest ]))
else if Sys.file_exists dst then
if Sys.is_directory dst then
match ls src with
| [] -> ()
| srcfiles ->
command ~verbose:(verbose_for_base_commands ())
([ "cp"; "-PRp" ] @ srcfiles @ [ dst ])
else
internal_error
"Can not copy dir %s to %s, which is not a directory" src dst
else
(mkdir (Filename.dirname dst);
command ~verbose:(verbose_for_base_commands ())
[ "cp"; "-PRp"; src; dst ])
let mv_aux f src dst =
if file_or_symlink_exists dst then remove_file dst;
mkdir (Filename.dirname dst);
command ~verbose:(verbose_for_base_commands ()) ("mv"::(cygify f [src; dst]))
let mv = mv_aux (get_cygpath_function ~command:"mv")
let is_exec file =
let stat = Unix.stat file in
stat.Unix.st_kind = Unix.S_REG &&
stat.Unix.st_perm land 0o111 <> 0
let file_is_empty f = Unix.((stat f).st_size = 0)
let classify_executable file =
let c = open_in file in
(* On a 32-bit system, this could fail for a PE image with a 2GB+ DOS header =-o *)
let input_int_little c =
let b1 = input_byte c in
let b2 = input_byte c in
let b3 = input_byte c in
let b4 = input_byte c in
b1 lor (b2 lsl 8) lor (b3 lsl 16) lor (b4 lsl 24) in
let input_short_little c =
let b1 = input_byte c in
let b2 = input_byte c in
b1 lor (b2 lsl 8) in
set_binary_mode_in c true;
try
match really_input_string c 2 with
"#!" ->
close_in c;
`Script
| "MZ" ->
let is_pe =
try
(* Offset to PE header at 0x3c (but we've already read two bytes) *)
ignore (really_input_string c 0x3a);
ignore (really_input_string c (input_int_little c - 0x40));
let magic = really_input_string c 4 in
magic = "PE\000\000"
with End_of_file ->
close_in c;
false in
if is_pe then
try
let arch =
(* NB It's not necessary to determine PE/PE+ headers for x64/x86 determination *)
match input_short_little c with
0x8664 ->
`x86_64
| 0x14c ->
`x86
| _ ->
raise End_of_file
in
ignore (really_input_string c 14);
let size_of_opt_header = input_short_little c in
let characteristics = input_short_little c in
(* Executable images must have a PE "optional" header and be marked executable *)
(* Could also validate IMAGE_FILE_32BIT_MACHINE (0x100) for x86 and IMAGE_FILE_LARGE_ADDRESS_AWARE (0x20) for x64 *)
if size_of_opt_header <= 0 || characteristics land 0x2 = 0 then
raise End_of_file;
close_in c;
if characteristics land 0x2000 <> 0 then
`Dll arch
else
`Exe arch
with End_of_file ->
close_in c;
`Unknown
else
`Exe `i386
| _ ->
close_in c;
`Unknown
with End_of_file ->
close_in c;
`Unknown
let default_install_warning dst = function
| `Add_exe ->
OpamConsole.warning "Automatically adding .exe to %s" dst
| `Install_dll ->
(* TODO Installation of .dll to bin is unfortunate, but not sure if it
should be a warning *)
()
| `Install_script ->
(* TODO Generate a .cmd wrapper (and warn about it - they're not perfect) *)
OpamConsole.warning "%s is a script; the command won't be available" dst;
| `Install_unknown ->
(* TODO Installation of a non-executable file is unexpected, but not sure
if it should be a warning/error *)
()
| `Cygwin ->
OpamConsole.warning "%s is a Cygwin-linked executable" dst
| `Msys2 ->
OpamConsole.warning "%s is a MSYS2-linked executable" dst
| `Tainted `Cygwin ->
OpamConsole.warning
"%s is an executable which links to a Cygwin-linked library" dst
| `Tainted `Msys2 ->
OpamConsole.warning
"%s is an executable which links to a MSYS2-linked library" dst
| `Cygwin_libraries ->
OpamConsole.warning
"%s links with a Cygwin-compiled DLL (almost certainly a packaging \
or environment error)" dst
let install ?(warning=default_install_warning) ?exec src dst =
if Sys.is_directory src then
internal_error "Cannot install %s: it is a directory." src;
if (try Sys.is_directory dst with Sys_error _ -> false) then
internal_error "Cannot install to %s: it is a directory." dst;
mkdir (Filename.dirname dst);
let exec = match exec with
| Some e -> e
| None -> is_exec src in
let perm = if exec then 0o755 else 0o644 in
log "install %s -> %s (%o)" src dst perm;
if Sys.win32 then
if exec then begin
let (dst, cygcheck) =
match classify_executable src with
`Exe _ ->
if not (Filename.check_suffix dst ".exe") && not (Filename.check_suffix dst ".dll") then begin
warning dst `Add_exe;
(dst ^ ".exe", true)
end else
(dst, true)
| `Dll _ ->
warning dst `Install_dll;
(dst, true)
| `Script ->
warning dst `Install_script;
(dst, false)
| `Unknown ->
warning dst `Install_unknown;
(dst, false)
in
copy_file_aux ~src ~dst ();
if cygcheck then
match OpamStd.Sys.get_windows_executable_variant dst with
| `Native ->
()
| (`Cygwin | `Msys2 | `Tainted _) as code ->
warning dst code
end else
copy_file_aux ~src ~dst ()
else
copy_file_aux ~chmod:(fun _ -> perm) ~src ~dst ()
let cpu_count () =
try
let ans =
let open OpamStd in
match Sys.os () with
| Sys.Win32 -> [Env.get "NUMBER_OF_PROCESSORS"]
| Sys.FreeBSD -> read_command_output ~verbose:(verbose_for_base_commands ())
["sysctl"; "-n"; "hw.ncpu"]
| _ -> read_command_output ~verbose:(verbose_for_base_commands ())
["getconf"; "_NPROCESSORS_ONLN"]
in
int_of_string (List.hd ans)
with Not_found | Process_error _ | Failure _ -> 1
open OpamProcess.Job.Op
module Tar = struct
type extract =
| Bzip2
| Gzip
| Lzma
| Xz
let extract_command = function
| Bzip2 -> "bzip2"
| Gzip -> "gzip"
| Lzma -> "lzma"
| Xz -> "xz"
let extract_option = function
| Bzip2 -> 'j'
| Gzip -> 'z'
| Lzma -> 'Y'
| Xz -> 'J'
let extensions =
[ [ "tar.gz" ; "tgz" ], Gzip
; [ "tar.bz2" ; "tbz" ], Bzip2
; [ "tar.xz" ; "txz" ], Xz
; [ "tar.lzma" ; "tlz" ], Lzma
]
let guess_type f =
try
let ic = open_in f in
let c1 = input_char ic in
let c2 = input_char ic in
close_in ic;
match c1, c2 with
| '\031', '\139' -> Some Gzip
| 'B' , 'Z' -> Some Bzip2
| '\xfd', '\x37' -> Some Xz
| '\x5d', '\x00' -> Some Lzma
| _ -> None
with Sys_error _ -> None
let match_ext file ext =
List.exists (Filename.check_suffix file) ext
let get_type file =
let ext =
List.fold_left
(fun acc (ext, t) -> match acc with
| Some t -> Some t
| None ->
if match_ext file ext
then Some t
else None)
None
extensions in
if Sys.file_exists file then guess_type file
else ext
let is_archive file =
get_type file <> None
let check_extract file =
OpamStd.Option.Op.(
get_type file >>= fun typ ->
let cmd = extract_command typ in
let res = resolve_command cmd <> None in
if not res then
Some (Printf.sprintf "Tar needs %s to extract the archive" cmd)
else None)
let tar_cmd = lazy (
match OpamStd.Sys.os () with
| OpamStd.Sys.OpenBSD -> "gtar"
| _ -> "tar"
)
let cygpath_tar = lazy (
Lazy.force (get_cygpath_function ~command:(Lazy.force tar_cmd))
)
let extract_command =
fun file ->
OpamStd.Option.Op.(
get_type file >>| fun typ ->
let f = Lazy.force cygpath_tar in
let tar_cmd = Lazy.force tar_cmd in
let command c dir =
make_command tar_cmd [ Printf.sprintf "xf%c" c ; f file; "-C" ; f dir ]
in
command (extract_option typ))
let compress_command =
fun file dir ->
let f = Lazy.force cygpath_tar in
let tar_cmd = Lazy.force tar_cmd in
make_command tar_cmd [
"cfz"; f file;
"-C" ; f (Filename.dirname dir);
f (Filename.basename dir)
]
end
module Zip = struct
let is_archive f =
if Sys.file_exists f then
try
let ic = open_in f in
let c1 = input_char ic in
let c2 = input_char ic in
let c3 = input_char ic in
let c4 = input_char ic in
close_in ic;
match c1, c2, c3, c4 with
| '\x50', '\x4b', '\x03', '\x04' -> true
| _ -> false
with Sys_error _ | End_of_file -> false
else
Filename.check_suffix f "zip"
let extract_command file =
Some (fun dir -> make_command "unzip" [ file; "-d"; dir ])
end
let is_archive file =
Tar.is_archive file || Zip.is_archive file
let extract_command file =
if Zip.is_archive file then Zip.extract_command file
else Tar.extract_command file
let make_tar_gz_job ~dir file =
let tmpfile = file ^ ".tmp" in
remove_file tmpfile;
Tar.compress_command tmpfile dir @@> fun r ->
OpamProcess.cleanup r;
if OpamProcess.is_success r then
(mv tmpfile file; Done None)