-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileutils.rb
2706 lines (2555 loc) · 79 KB
/
fileutils.rb
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
# frozen_string_literal: true
begin
require 'rbconfig'
rescue LoadError
# for make mjit-headers
end
# Namespace for file utility methods for copying, moving, removing, etc.
#
# == What's Here
#
# First, what’s elsewhere. \Module \FileUtils:
#
# - Inherits from {class Object}[rdoc-ref:Object].
# - Supplements {class File}[rdoc-ref:File]
# (but is not included or extended there).
#
# Here, module \FileUtils provides methods that are useful for:
#
# - {Creating}[rdoc-ref:FileUtils@Creating].
# - {Deleting}[rdoc-ref:FileUtils@Deleting].
# - {Querying}[rdoc-ref:FileUtils@Querying].
# - {Setting}[rdoc-ref:FileUtils@Setting].
# - {Comparing}[rdoc-ref:FileUtils@Comparing].
# - {Copying}[rdoc-ref:FileUtils@Copying].
# - {Moving}[rdoc-ref:FileUtils@Moving].
# - {Options}[rdoc-ref:FileUtils@Options].
#
# === Creating
#
# - ::mkdir: Creates directories.
# - ::mkdir_p, ::makedirs, ::mkpath: Creates directories,
# also creating ancestor directories as needed.
# - ::link_entry: Creates a hard link.
# - ::ln, ::link: Creates hard links.
# - ::ln_s, ::symlink: Creates symbolic links.
# - ::ln_sf: Creates symbolic links, overwriting if necessary.
# - ::ln_sr: Creates symbolic links relative to targets
#
# === Deleting
#
# - ::remove_dir: Removes a directory and its descendants.
# - ::remove_entry: Removes an entry, including its descendants if it is a directory.
# - ::remove_entry_secure: Like ::remove_entry, but removes securely.
# - ::remove_file: Removes a file entry.
# - ::rm, ::remove: Removes entries.
# - ::rm_f, ::safe_unlink: Like ::rm, but removes forcibly.
# - ::rm_r: Removes entries and their descendants.
# - ::rm_rf, ::rmtree: Like ::rm_r, but removes forcibly.
# - ::rmdir: Removes directories.
#
# === Querying
#
# - ::pwd, ::getwd: Returns the path to the working directory.
# - ::uptodate?: Returns whether a given entry is newer than given other entries.
#
# === Setting
#
# - ::cd, ::chdir: Sets the working directory.
# - ::chmod: Sets permissions for an entry.
# - ::chmod_R: Sets permissions for an entry and its descendants.
# - ::chown: Sets the owner and group for entries.
# - ::chown_R: Sets the owner and group for entries and their descendants.
# - ::touch: Sets modification and access times for entries,
# creating if necessary.
#
# === Comparing
#
# - ::compare_file, ::cmp, ::identical?: Returns whether two entries are identical.
# - ::compare_stream: Returns whether two streams are identical.
#
# === Copying
#
# - ::copy_entry: Recursively copies an entry.
# - ::copy_file: Copies an entry.
# - ::copy_stream: Copies a stream.
# - ::cp, ::copy: Copies files.
# - ::cp_lr: Recursively creates hard links.
# - ::cp_r: Recursively copies files, retaining mode, owner, and group.
# - ::install: Recursively copies files, optionally setting mode,
# owner, and group.
#
# === Moving
#
# - ::mv, ::move: Moves entries.
#
# === Options
#
# - ::collect_method: Returns the names of methods that accept a given option.
# - ::commands: Returns the names of methods that accept options.
# - ::have_option?: Returns whether a given method accepts a given option.
# - ::options: Returns all option names.
# - ::options_of: Returns the names of the options for a given method.
#
# == Path Arguments
#
# Some methods in \FileUtils accept _path_ arguments,
# which are interpreted as paths to filesystem entries:
#
# - If the argument is a string, that value is the path.
# - If the argument has method +:to_path+, it is converted via that method.
# - If the argument has method +:to_str+, it is converted via that method.
#
# == About the Examples
#
# Some examples here involve trees of file entries.
# For these, we sometimes display trees using the
# {tree command-line utility}[https://en.wikipedia.org/wiki/Tree_(command)],
# which is a recursive directory-listing utility that produces
# a depth-indented listing of files and directories.
#
# We use a helper method to launch the command and control the format:
#
# def tree(dirpath = '.')
# command = "tree --noreport --charset=ascii #{dirpath}"
# system(command)
# end
#
# To illustrate:
#
# tree('src0')
# # => src0
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
#
# == Avoiding the TOCTTOU Vulnerability
#
# For certain methods that recursively remove entries,
# there is a potential vulnerability called the
# {Time-of-check to time-of-use}[https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use],
# or TOCTTOU, vulnerability that can exist when:
#
# - An ancestor directory of the entry at the target path is world writable;
# such directories include <tt>/tmp</tt>.
# - The directory tree at the target path includes:
#
# - A world-writable descendant directory.
# - A symbolic link.
#
# To avoid that vulnerability, you can use this method to remove entries:
#
# - FileUtils.remove_entry_secure: removes recursively
# if the target path points to a directory.
#
# Also available are these methods,
# each of which calls \FileUtils.remove_entry_secure:
#
# - FileUtils.rm_r with keyword argument <tt>secure: true</tt>.
# - FileUtils.rm_rf with keyword argument <tt>secure: true</tt>.
#
# Finally, this method for moving entries calls \FileUtils.remove_entry_secure
# if the source and destination are on different file systems
# (which means that the "move" is really a copy and remove):
#
# - FileUtils.mv with keyword argument <tt>secure: true</tt>.
#
# \Method \FileUtils.remove_entry_secure removes securely
# by applying a special pre-process:
#
# - If the target path points to a directory, this method uses methods
# {File#chown}[rdoc-ref:File#chown]
# and {File#chmod}[rdoc-ref:File#chmod]
# in removing directories.
# - The owner of the target directory should be either the current process
# or the super user (root).
#
# WARNING: You must ensure that *ALL* parent directories cannot be
# moved by other untrusted users. For example, parent directories
# should not be owned by untrusted users, and should not be world
# writable except when the sticky bit is set.
#
# For details of this security vulnerability, see Perl cases:
#
# - {CVE-2005-0448}[https://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448].
# - {CVE-2004-0452}[https://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452].
#
module FileUtils
VERSION = "1.7.0"
def self.private_module_function(name) #:nodoc:
module_function name
private_class_method name
end
#
# Returns a string containing the path to the current directory:
#
# FileUtils.pwd # => "/rdoc/fileutils"
#
# FileUtils.getwd is an alias for FileUtils.pwd.
#
# Related: FileUtils.cd.
#
def pwd
Dir.pwd
end
module_function :pwd
alias getwd pwd
module_function :getwd
# Changes the working directory to the given +dir+, which
# should be {interpretable as a path}[rdoc-ref:FileUtils@Path+Arguments]:
#
# With no block given,
# changes the current directory to the directory at +dir+; returns zero:
#
# FileUtils.pwd # => "/rdoc/fileutils"
# FileUtils.cd('..')
# FileUtils.pwd # => "/rdoc"
# FileUtils.cd('fileutils')
#
# With a block given, changes the current directory to the directory
# at +dir+, calls the block with argument +dir+,
# and restores the original current directory; returns the block's value:
#
# FileUtils.pwd # => "/rdoc/fileutils"
# FileUtils.cd('..') { |arg| [arg, FileUtils.pwd] } # => ["..", "/rdoc"]
# FileUtils.pwd # => "/rdoc/fileutils"
#
# Keyword arguments:
#
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.cd('..')
# FileUtils.cd('fileutils')
#
# Output:
#
# cd ..
# cd fileutils
#
# FileUtils.chdir is an alias for FileUtils.cd.
#
# Related: FileUtils.pwd.
#
def cd(dir, verbose: nil, &block) # :yield: dir
fu_output_message "cd #{dir}" if verbose
result = Dir.chdir(dir, &block)
fu_output_message 'cd -' if verbose and block
result
end
module_function :cd
alias chdir cd
module_function :chdir
#
# Returns +true+ if the file at path +new+
# is newer than all the files at paths in array +old_list+;
# +false+ otherwise.
#
# Argument +new+ and the elements of +old_list+
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments]:
#
# FileUtils.uptodate?('Rakefile', ['Gemfile', 'README.md']) # => true
# FileUtils.uptodate?('Gemfile', ['Rakefile', 'README.md']) # => false
#
# A non-existent file is considered to be infinitely old.
#
# Related: FileUtils.touch.
#
def uptodate?(new, old_list)
return false unless File.exist?(new)
new_time = File.mtime(new)
old_list.each do |old|
if File.exist?(old)
return false unless new_time > File.mtime(old)
end
end
true
end
module_function :uptodate?
def remove_trailing_slash(dir) #:nodoc:
dir == '/' ? dir : dir.chomp(?/)
end
private_module_function :remove_trailing_slash
#
# Creates directories at the paths in the given +list+
# (a single path or an array of paths);
# returns +list+ if it is an array, <tt>[list]</tt> otherwise.
#
# Argument +list+ or its elements
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# With no keyword arguments, creates a directory at each +path+ in +list+
# by calling: <tt>Dir.mkdir(path, mode)</tt>;
# see {Dir.mkdir}[rdoc-ref:Dir.mkdir]:
#
# FileUtils.mkdir(%w[tmp0 tmp1]) # => ["tmp0", "tmp1"]
# FileUtils.mkdir('tmp4') # => ["tmp4"]
#
# Keyword arguments:
#
# - <tt>mode: <i>mode</i></tt> - also calls <tt>File.chmod(mode, path)</tt>;
# see {File.chmod}[rdoc-ref:File.chmod].
# - <tt>noop: true</tt> - does not create directories.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.mkdir(%w[tmp0 tmp1], verbose: true)
# FileUtils.mkdir(%w[tmp2 tmp3], mode: 0700, verbose: true)
#
# Output:
#
# mkdir tmp0 tmp1
# mkdir -m 700 tmp2 tmp3
#
# Raises an exception if any path points to an existing
# file or directory, or if for any reason a directory cannot be created.
#
# Related: FileUtils.mkdir_p.
#
def mkdir(list, mode: nil, noop: nil, verbose: nil)
list = fu_list(list)
fu_output_message "mkdir #{mode ? ('-m %03o ' % mode) : ''}#{list.join ' '}" if verbose
return if noop
list.each do |dir|
fu_mkdir dir, mode
end
end
module_function :mkdir
#
# Creates directories at the paths in the given +list+
# (a single path or an array of paths),
# also creating ancestor directories as needed;
# returns +list+ if it is an array, <tt>[list]</tt> otherwise.
#
# Argument +list+ or its elements
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# With no keyword arguments, creates a directory at each +path+ in +list+,
# along with any needed ancestor directories,
# by calling: <tt>Dir.mkdir(path, mode)</tt>;
# see {Dir.mkdir}[rdoc-ref:Dir.mkdir]:
#
# FileUtils.mkdir_p(%w[tmp0/tmp1 tmp2/tmp3]) # => ["tmp0/tmp1", "tmp2/tmp3"]
# FileUtils.mkdir_p('tmp4/tmp5') # => ["tmp4/tmp5"]
#
# Keyword arguments:
#
# - <tt>mode: <i>mode</i></tt> - also calls <tt>File.chmod(mode, path)</tt>;
# see {File.chmod}[rdoc-ref:File.chmod].
# - <tt>noop: true</tt> - does not create directories.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.mkdir_p(%w[tmp0 tmp1], verbose: true)
# FileUtils.mkdir_p(%w[tmp2 tmp3], mode: 0700, verbose: true)
#
# Output:
#
# mkdir -p tmp0 tmp1
# mkdir -p -m 700 tmp2 tmp3
#
# Raises an exception if for any reason a directory cannot be created.
#
# FileUtils.mkpath and FileUtils.makedirs are aliases for FileUtils.mkdir_p.
#
# Related: FileUtils.mkdir.
#
def mkdir_p(list, mode: nil, noop: nil, verbose: nil)
list = fu_list(list)
fu_output_message "mkdir -p #{mode ? ('-m %03o ' % mode) : ''}#{list.join ' '}" if verbose
return *list if noop
list.each do |item|
path = remove_trailing_slash(item)
stack = []
until File.directory?(path) || File.dirname(path) == path
stack.push path
path = File.dirname(path)
end
stack.reverse_each do |dir|
begin
fu_mkdir dir, mode
rescue SystemCallError
raise unless File.directory?(dir)
end
end
end
return *list
end
module_function :mkdir_p
alias mkpath mkdir_p
alias makedirs mkdir_p
module_function :mkpath
module_function :makedirs
def fu_mkdir(path, mode) #:nodoc:
path = remove_trailing_slash(path)
if mode
Dir.mkdir path, mode
File.chmod mode, path
else
Dir.mkdir path
end
end
private_module_function :fu_mkdir
#
# Removes directories at the paths in the given +list+
# (a single path or an array of paths);
# returns +list+, if it is an array, <tt>[list]</tt> otherwise.
#
# Argument +list+ or its elements
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# With no keyword arguments, removes the directory at each +path+ in +list+,
# by calling: <tt>Dir.rmdir(path)</tt>;
# see {Dir.rmdir}[rdoc-ref:Dir.rmdir]:
#
# FileUtils.rmdir(%w[tmp0/tmp1 tmp2/tmp3]) # => ["tmp0/tmp1", "tmp2/tmp3"]
# FileUtils.rmdir('tmp4/tmp5') # => ["tmp4/tmp5"]
#
# Keyword arguments:
#
# - <tt>parents: true</tt> - removes successive ancestor directories
# if empty.
# - <tt>noop: true</tt> - does not remove directories.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.rmdir(%w[tmp0/tmp1 tmp2/tmp3], parents: true, verbose: true)
# FileUtils.rmdir('tmp4/tmp5', parents: true, verbose: true)
#
# Output:
#
# rmdir -p tmp0/tmp1 tmp2/tmp3
# rmdir -p tmp4/tmp5
#
# Raises an exception if a directory does not exist
# or if for any reason a directory cannot be removed.
#
# Related: {methods for deleting}[rdoc-ref:FileUtils@Deleting].
#
def rmdir(list, parents: nil, noop: nil, verbose: nil)
list = fu_list(list)
fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if verbose
return if noop
list.each do |dir|
Dir.rmdir(dir = remove_trailing_slash(dir))
if parents
begin
until (parent = File.dirname(dir)) == '.' or parent == dir
dir = parent
Dir.rmdir(dir)
end
rescue Errno::ENOTEMPTY, Errno::EEXIST, Errno::ENOENT
end
end
end
end
module_function :rmdir
# Creates {hard links}[https://en.wikipedia.org/wiki/Hard_link].
#
# Arguments +src+ (a single path or an array of paths)
# and +dest+ (a single path)
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# When +src+ is the path to an existing file
# and +dest+ is the path to a non-existent file,
# creates a hard link at +dest+ pointing to +src+; returns zero:
#
# Dir.children('tmp0/') # => ["t.txt"]
# Dir.children('tmp1/') # => []
# FileUtils.ln('tmp0/t.txt', 'tmp1/t.lnk') # => 0
# Dir.children('tmp1/') # => ["t.lnk"]
#
# When +src+ is the path to an existing file
# and +dest+ is the path to an existing directory,
# creates a hard link at <tt>dest/src</tt> pointing to +src+; returns zero:
#
# Dir.children('tmp2') # => ["t.dat"]
# Dir.children('tmp3') # => []
# FileUtils.ln('tmp2/t.dat', 'tmp3') # => 0
# Dir.children('tmp3') # => ["t.dat"]
#
# When +src+ is an array of paths to existing files
# and +dest+ is the path to an existing directory,
# then for each path +target+ in +src+,
# creates a hard link at <tt>dest/target</tt> pointing to +target+;
# returns +src+:
#
# Dir.children('tmp4/') # => []
# FileUtils.ln(['tmp0/t.txt', 'tmp2/t.dat'], 'tmp4/') # => ["tmp0/t.txt", "tmp2/t.dat"]
# Dir.children('tmp4/') # => ["t.dat", "t.txt"]
#
# Keyword arguments:
#
# - <tt>force: true</tt> - overwrites +dest+ if it exists.
# - <tt>noop: true</tt> - does not create links.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.ln('tmp0/t.txt', 'tmp1/t.lnk', verbose: true)
# FileUtils.ln('tmp2/t.dat', 'tmp3', verbose: true)
# FileUtils.ln(['tmp0/t.txt', 'tmp2/t.dat'], 'tmp4/', verbose: true)
#
# Output:
#
# ln tmp0/t.txt tmp1/t.lnk
# ln tmp2/t.dat tmp3
# ln tmp0/t.txt tmp2/t.dat tmp4/
#
# Raises an exception if +dest+ is the path to an existing file
# and keyword argument +force+ is not +true+.
#
# FileUtils#link is an alias for FileUtils#ln.
#
# Related: FileUtils.link_entry (has different options).
#
def ln(src, dest, force: nil, noop: nil, verbose: nil)
fu_output_message "ln#{force ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if verbose
return if noop
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if force
File.link s, d
end
end
module_function :ln
alias link ln
module_function :link
# Creates {hard links}[https://en.wikipedia.org/wiki/Hard_link].
#
# Arguments +src+ (a single path or an array of paths)
# and +dest+ (a single path)
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# If +src+ is the path to a directory and +dest+ does not exist,
# creates links +dest+ and descendents pointing to +src+ and its descendents:
#
# tree('src0')
# # => src0
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
# File.exist?('dest0') # => false
# FileUtils.cp_lr('src0', 'dest0')
# tree('dest0')
# # => dest0
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
#
# If +src+ and +dest+ are both paths to directories,
# creates links <tt>dest/src</tt> and descendents
# pointing to +src+ and its descendents:
#
# tree('src1')
# # => src1
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
# FileUtils.mkdir('dest1')
# FileUtils.cp_lr('src1', 'dest1')
# tree('dest1')
# # => dest1
# # `-- src1
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
#
# If +src+ is an array of paths to entries and +dest+ is the path to a directory,
# for each path +filepath+ in +src+, creates a link at <tt>dest/filepath</tt>
# pointing to that path:
#
# tree('src2')
# # => src2
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
# FileUtils.mkdir('dest2')
# FileUtils.cp_lr(['src2/sub0', 'src2/sub1'], 'dest2')
# tree('dest2')
# # => dest2
# # |-- sub0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- sub1
# # |-- src2.txt
# # `-- src3.txt
#
# Keyword arguments:
#
# - <tt>dereference_root: false</tt> - if +src+ is a symbolic link,
# does not dereference it.
# - <tt>noop: true</tt> - does not create links.
# - <tt>remove_destination: true</tt> - removes +dest+ before creating links.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.cp_lr('src0', 'dest0', noop: true, verbose: true)
# FileUtils.cp_lr('src1', 'dest1', noop: true, verbose: true)
# FileUtils.cp_lr(['src2/sub0', 'src2/sub1'], 'dest2', noop: true, verbose: true)
#
# Output:
#
# cp -lr src0 dest0
# cp -lr src1 dest1
# cp -lr src2/sub0 src2/sub1 dest2
#
# Raises an exception if +dest+ is the path to an existing file or directory
# and keyword argument <tt>remove_destination: true</tt> is not given.
#
# Related: {methods for copying}[rdoc-ref:FileUtils@Copying].
#
def cp_lr(src, dest, noop: nil, verbose: nil,
dereference_root: true, remove_destination: false)
fu_output_message "cp -lr#{remove_destination ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if verbose
return if noop
fu_each_src_dest(src, dest) do |s, d|
link_entry s, d, dereference_root, remove_destination
end
end
module_function :cp_lr
# Creates {symbolic links}[https://en.wikipedia.org/wiki/Symbolic_link].
#
# Arguments +src+ (a single path or an array of paths)
# and +dest+ (a single path)
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# If +src+ is the path to an existing file:
#
# - When +dest+ is the path to a non-existent file,
# creates a symbolic link at +dest+ pointing to +src+:
#
# FileUtils.touch('src0.txt')
# File.exist?('dest0.txt') # => false
# FileUtils.ln_s('src0.txt', 'dest0.txt')
# File.symlink?('dest0.txt') # => true
#
# - When +dest+ is the path to an existing file,
# creates a symbolic link at +dest+ pointing to +src+
# if and only if keyword argument <tt>force: true</tt> is given
# (raises an exception otherwise):
#
# FileUtils.touch('src1.txt')
# FileUtils.touch('dest1.txt')
# FileUtils.ln_s('src1.txt', 'dest1.txt', force: true)
# FileTest.symlink?('dest1.txt') # => true
#
# FileUtils.ln_s('src1.txt', 'dest1.txt') # Raises Errno::EEXIST.
#
# If +dest+ is the path to a directory,
# creates a symbolic link at <tt>dest/src</tt> pointing to +src+:
#
# FileUtils.touch('src2.txt')
# FileUtils.mkdir('destdir2')
# FileUtils.ln_s('src2.txt', 'destdir2')
# File.symlink?('destdir2/src2.txt') # => true
#
# If +src+ is an array of paths to existing files and +dest+ is a directory,
# for each child +child+ in +src+ creates a symbolic link <tt>dest/child</tt>
# pointing to +child+:
#
# FileUtils.mkdir('srcdir3')
# FileUtils.touch('srcdir3/src0.txt')
# FileUtils.touch('srcdir3/src1.txt')
# FileUtils.mkdir('destdir3')
# FileUtils.ln_s(['srcdir3/src0.txt', 'srcdir3/src1.txt'], 'destdir3')
# File.symlink?('destdir3/src0.txt') # => true
# File.symlink?('destdir3/src1.txt') # => true
#
# Keyword arguments:
#
# - <tt>force: true</tt> - overwrites +dest+ if it exists.
# - <tt>relative: false</tt> - create links relative to +dest+.
# - <tt>noop: true</tt> - does not create links.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.ln_s('src0.txt', 'dest0.txt', noop: true, verbose: true)
# FileUtils.ln_s('src1.txt', 'destdir1', noop: true, verbose: true)
# FileUtils.ln_s('src2.txt', 'dest2.txt', force: true, noop: true, verbose: true)
# FileUtils.ln_s(['srcdir3/src0.txt', 'srcdir3/src1.txt'], 'destdir3', noop: true, verbose: true)
#
# Output:
#
# ln -s src0.txt dest0.txt
# ln -s src1.txt destdir1
# ln -sf src2.txt dest2.txt
# ln -s srcdir3/src0.txt srcdir3/src1.txt destdir3
#
# FileUtils.symlink is an alias for FileUtils.ln_s.
#
# Related: FileUtils.ln_sf.
#
def ln_s(src, dest, force: nil, relative: false, target_directory: true, noop: nil, verbose: nil)
if relative
return ln_sr(src, dest, force: force, noop: noop, verbose: verbose)
end
fu_output_message "ln -s#{force ? 'f' : ''} #{[src,dest].flatten.join ' '}" if verbose
return if noop
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if force
File.symlink s, d
end
end
module_function :ln_s
alias symlink ln_s
module_function :symlink
# Like FileUtils.ln_s, but always with keyword argument <tt>force: true</tt> given.
#
def ln_sf(src, dest, noop: nil, verbose: nil)
ln_s src, dest, force: true, noop: noop, verbose: verbose
end
module_function :ln_sf
# Like FileUtils.ln_s, but create links relative to +dest+.
#
def ln_sr(src, dest, target_directory: true, force: nil, noop: nil, verbose: nil)
options = "#{force ? 'f' : ''}#{target_directory ? '' : 'T'}"
dest = File.path(dest)
srcs = Array(src)
link = proc do |s, target_dir_p = true|
s = File.path(s)
if target_dir_p
d = File.join(destdirs = dest, File.basename(s))
else
destdirs = File.dirname(d = dest)
end
destdirs = fu_split_path(File.realpath(destdirs))
if fu_starting_path?(s)
srcdirs = fu_split_path((File.realdirpath(s) rescue File.expand_path(s)))
base = fu_relative_components_from(srcdirs, destdirs)
s = File.join(*base)
else
srcdirs = fu_clean_components(*fu_split_path(s))
base = fu_relative_components_from(fu_split_path(Dir.pwd), destdirs)
while srcdirs.first&. == ".." and base.last&.!=("..") and !fu_starting_path?(base.last)
srcdirs.shift
base.pop
end
s = File.join(*base, *srcdirs)
end
fu_output_message "ln -s#{options} #{s} #{d}" if verbose
next if noop
remove_file d, true if force
File.symlink s, d
end
case srcs.size
when 0
when 1
link[srcs[0], target_directory && File.directory?(dest)]
else
srcs.each(&link)
end
end
module_function :ln_sr
# Creates {hard links}[https://en.wikipedia.org/wiki/Hard_link]; returns +nil+.
#
# Arguments +src+ and +dest+
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# If +src+ is the path to a file and +dest+ does not exist,
# creates a hard link at +dest+ pointing to +src+:
#
# FileUtils.touch('src0.txt')
# File.exist?('dest0.txt') # => false
# FileUtils.link_entry('src0.txt', 'dest0.txt')
# File.file?('dest0.txt') # => true
#
# If +src+ is the path to a directory and +dest+ does not exist,
# recursively creates hard links at +dest+ pointing to paths in +src+:
#
# FileUtils.mkdir_p(['src1/dir0', 'src1/dir1'])
# src_file_paths = [
# 'src1/dir0/t0.txt',
# 'src1/dir0/t1.txt',
# 'src1/dir1/t2.txt',
# 'src1/dir1/t3.txt',
# ]
# FileUtils.touch(src_file_paths)
# File.directory?('dest1') # => true
# FileUtils.link_entry('src1', 'dest1')
# File.file?('dest1/dir0/t0.txt') # => true
# File.file?('dest1/dir0/t1.txt') # => true
# File.file?('dest1/dir1/t2.txt') # => true
# File.file?('dest1/dir1/t3.txt') # => true
#
# Keyword arguments:
#
# - <tt>dereference_root: true</tt> - dereferences +src+ if it is a symbolic link.
# - <tt>remove_destination: true</tt> - removes +dest+ before creating links.
#
# Raises an exception if +dest+ is the path to an existing file or directory
# and keyword argument <tt>remove_destination: true</tt> is not given.
#
# Related: FileUtils.ln (has different options).
#
def link_entry(src, dest, dereference_root = false, remove_destination = false)
Entry_.new(src, nil, dereference_root).traverse do |ent|
destent = Entry_.new(dest, ent.rel, false)
File.unlink destent.path if remove_destination && File.file?(destent.path)
ent.link destent.path
end
end
module_function :link_entry
# Copies files.
#
# Arguments +src+ (a single path or an array of paths)
# and +dest+ (a single path)
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# If +src+ is the path to a file and +dest+ is not the path to a directory,
# copies +src+ to +dest+:
#
# FileUtils.touch('src0.txt')
# File.exist?('dest0.txt') # => false
# FileUtils.cp('src0.txt', 'dest0.txt')
# File.file?('dest0.txt') # => true
#
# If +src+ is the path to a file and +dest+ is the path to a directory,
# copies +src+ to <tt>dest/src</tt>:
#
# FileUtils.touch('src1.txt')
# FileUtils.mkdir('dest1')
# FileUtils.cp('src1.txt', 'dest1')
# File.file?('dest1/src1.txt') # => true
#
# If +src+ is an array of paths to files and +dest+ is the path to a directory,
# copies from each +src+ to +dest+:
#
# src_file_paths = ['src2.txt', 'src2.dat']
# FileUtils.touch(src_file_paths)
# FileUtils.mkdir('dest2')
# FileUtils.cp(src_file_paths, 'dest2')
# File.file?('dest2/src2.txt') # => true
# File.file?('dest2/src2.dat') # => true
#
# Keyword arguments:
#
# - <tt>preserve: true</tt> - preserves file times.
# - <tt>noop: true</tt> - does not copy files.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.cp('src0.txt', 'dest0.txt', noop: true, verbose: true)
# FileUtils.cp('src1.txt', 'dest1', noop: true, verbose: true)
# FileUtils.cp(src_file_paths, 'dest2', noop: true, verbose: true)
#
# Output:
#
# cp src0.txt dest0.txt
# cp src1.txt dest1
# cp src2.txt src2.dat dest2
#
# Raises an exception if +src+ is a directory.
#
# FileUtils.copy is an alias for FileUtils.cp.
#
# Related: {methods for copying}[rdoc-ref:FileUtils@Copying].
#
def cp(src, dest, preserve: nil, noop: nil, verbose: nil)
fu_output_message "cp#{preserve ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if verbose
return if noop
fu_each_src_dest(src, dest) do |s, d|
copy_file s, d, preserve
end
end
module_function :cp
alias copy cp
module_function :copy
# Recursively copies files.
#
# Arguments +src+ (a single path or an array of paths)
# and +dest+ (a single path)
# should be {interpretable as paths}[rdoc-ref:FileUtils@Path+Arguments].
#
# The mode, owner, and group are retained in the copy;
# to change those, use FileUtils.install instead.
#
# If +src+ is the path to a file and +dest+ is not the path to a directory,
# copies +src+ to +dest+:
#
# FileUtils.touch('src0.txt')
# File.exist?('dest0.txt') # => false
# FileUtils.cp_r('src0.txt', 'dest0.txt')
# File.file?('dest0.txt') # => true
#
# If +src+ is the path to a file and +dest+ is the path to a directory,
# copies +src+ to <tt>dest/src</tt>:
#
# FileUtils.touch('src1.txt')
# FileUtils.mkdir('dest1')
# FileUtils.cp_r('src1.txt', 'dest1')
# File.file?('dest1/src1.txt') # => true
#
# If +src+ is the path to a directory and +dest+ does not exist,
# recursively copies +src+ to +dest+:
#
# tree('src2')
# # => src2
# # |-- dir0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- dir1
# # |-- src2.txt
# # `-- src3.txt
# FileUtils.exist?('dest2') # => false
# FileUtils.cp_r('src2', 'dest2')
# tree('dest2')
# # => dest2
# # |-- dir0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- dir1
# # |-- src2.txt
# # `-- src3.txt
#
# If +src+ and +dest+ are paths to directories,
# recursively copies +src+ to <tt>dest/src</tt>:
#
# tree('src3')
# # => src3
# # |-- dir0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- dir1
# # |-- src2.txt
# # `-- src3.txt
# FileUtils.mkdir('dest3')
# FileUtils.cp_r('src3', 'dest3')
# tree('dest3')
# # => dest3
# # `-- src3
# # |-- dir0
# # | |-- src0.txt
# # | `-- src1.txt
# # `-- dir1
# # |-- src2.txt
# # `-- src3.txt
#
# If +src+ is an array of paths and +dest+ is a directory,
# recursively copies from each path in +src+ to +dest+;
# the paths in +src+ may point to files and/or directories.
#
# Keyword arguments:
#
# - <tt>dereference_root: false</tt> - if +src+ is a symbolic link,
# does not dereference it.
# - <tt>noop: true</tt> - does not copy files.
# - <tt>preserve: true</tt> - preserves file times.
# - <tt>remove_destination: true</tt> - removes +dest+ before copying files.
# - <tt>verbose: true</tt> - prints an equivalent command:
#
# FileUtils.cp_r('src0.txt', 'dest0.txt', noop: true, verbose: true)
# FileUtils.cp_r('src1.txt', 'dest1', noop: true, verbose: true)
# FileUtils.cp_r('src2', 'dest2', noop: true, verbose: true)
# FileUtils.cp_r('src3', 'dest3', noop: true, verbose: true)
#
# Output:
#
# cp -r src0.txt dest0.txt
# cp -r src1.txt dest1
# cp -r src2 dest2
# cp -r src3 dest3
#
# Raises an exception of +src+ is the path to a directory
# and +dest+ is the path to a file.
#
# Related: {methods for copying}[rdoc-ref:FileUtils@Copying].
#
def cp_r(src, dest, preserve: nil, noop: nil, verbose: nil,
dereference_root: true, remove_destination: nil)
fu_output_message "cp -r#{preserve ? 'p' : ''}#{remove_destination ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if verbose
return if noop
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, preserve, dereference_root, remove_destination