/
file.ex
1793 lines (1436 loc) · 52.8 KB
/
file.ex
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
defmodule File do
@moduledoc ~S"""
This module contains functions to manipulate files.
Some of those functions are low-level, allowing the user
to interact with files or IO devices, like `open/2`,
`copy/3` and others. This module also provides higher
level functions that work with filenames and have their naming
based on Unix variants. For example, one can copy a file
via `cp/3` and remove files and directories recursively
via `rm_rf/1`.
Paths given to functions in this module can be either relative to the
current working directory (as returned by `File.cwd/0`), or absolute
paths. Shell conventions like `~` are not expanded automatically.
To use paths like `~/Downloads`, you can use `Path.expand/1` or
`Path.expand/2` to expand your path to an absolute path.
## Encoding
In order to write and read files, one must use the functions
in the `IO` module. By default, a file is opened in binary mode,
which requires the functions `IO.binread/2` and `IO.binwrite/2`
to interact with the file. A developer may pass `:utf8` as an
option when opening the file, then the slower `IO.read/2` and
`IO.write/2` functions must be used as they are responsible for
doing the proper conversions and providing the proper data guarantees.
Note that filenames when given as charlists in Elixir are
always treated as UTF-8. In particular, we expect that the
shell and the operating system are configured to use UTF-8
encoding. Binary filenames are considered raw and passed
to the operating system as is.
## API
Most of the functions in this module return `:ok` or
`{:ok, result}` in case of success, `{:error, reason}`
otherwise. Those functions also have a variant
that ends with `!` which returns the result (instead of the
`{:ok, result}` tuple) in case of success or raises an
exception in case it fails. For example:
File.read("hello.txt")
#=> {:ok, "World"}
File.read("invalid.txt")
#=> {:error, :enoent}
File.read!("hello.txt")
#=> "World"
File.read!("invalid.txt")
#=> raises File.Error
In general, a developer should use the former in case they want
to react if the file does not exist. The latter should be used
when the developer expects their software to fail in case the
file cannot be read (i.e. it is literally an exception).
## Processes and raw files
Every time a file is opened, Elixir spawns a new process. Writing
to a file is equivalent to sending messages to the process that
writes to the file descriptor.
This means files can be passed between nodes and message passing
guarantees they can write to the same file in a network.
However, you may not always want to pay the price for this abstraction.
In such cases, a file can be opened in `:raw` mode. The options `:read_ahead`
and `:delayed_write` are also useful when operating on large files or
working with files in tight loops.
Check `:file.open/2` for more information about such options and
other performance considerations.
"""
@type posix :: :file.posix()
@type io_device :: :file.io_device()
@type stat_options :: [time: :local | :universal | :posix]
@type mode ::
:append
| :binary
| :charlist
| :compressed
| :delayed_write
| :exclusive
| :raw
| :read
| :read_ahead
| :sync
| :write
| {:read_ahead, pos_integer}
| {:delayed_write, non_neg_integer, non_neg_integer}
| encoding_mode()
@type encoding_mode ::
:utf8
| {
:encoding,
:latin1
| :unicode
| :utf8
| :utf16
| :utf32
| {:utf16, :big | :little}
| {:utf32, :big | :little}
}
@type stream_mode ::
encoding_mode()
| :trim_bom
| {:read_ahead, pos_integer | false}
| {:delayed_write, non_neg_integer, non_neg_integer}
@type erlang_time ::
{{year :: non_neg_integer(), month :: 1..12, day :: 1..31},
{hour :: 0..23, minute :: 0..59, second :: 0..59}}
@type posix_time :: integer()
@doc """
Returns `true` if the path is a regular file.
This function follows symbolic links, so if a symbolic link points to a
regular file, `true` is returned.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.regular?(__ENV__.file)
#=> true
"""
@spec regular?(Path.t(), [regular_option]) :: boolean
when regular_option: :raw
def regular?(path, opts \\ []) do
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :regular}
end
@doc """
Returns `true` if the given path is a directory.
This function follows symbolic links, so if a symbolic link points to a
directory, `true` is returned.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.dir?("./test")
#=> true
File.dir?("test")
#=> true
File.dir?("/usr/bin")
#=> true
File.dir?("~/Downloads")
#=> false
"~/Downloads" |> Path.expand() |> File.dir?()
#=> true
"""
@spec dir?(Path.t(), [dir_option]) :: boolean
when dir_option: :raw
def dir?(path, opts \\ []) do
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :directory}
end
@doc """
Returns `true` if the given path exists.
It can be a regular file, directory, socket, symbolic link, named pipe, or device file.
Returns `false` for symbolic links pointing to non-existing targets.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.exists?("test/")
#=> true
File.exists?("missing.txt")
#=> false
File.exists?("/dev/null")
#=> true
"""
@spec exists?(Path.t(), [exists_option]) :: boolean
when exists_option: :raw
def exists?(path, opts \\ []) do
opts = [{:time, :posix}] ++ opts
match?({:ok, _}, :file.read_file_info(IO.chardata_to_string(path), opts))
end
@doc """
Tries to create the directory `path`.
Missing parent directories are not created.
Returns `:ok` if successful, or `{:error, reason}` if an error occurs.
Typical error reasons are:
* `:eacces` - missing search or write permissions for the parent
directories of `path`
* `:eexist` - there is already a file or directory named `path`
* `:enoent` - a component of `path` does not exist
* `:enospc` - there is no space left on the device
* `:enotdir` - a component of `path` is not a directory;
on some platforms, `:enoent` is returned instead
"""
@spec mkdir(Path.t()) :: :ok | {:error, posix}
def mkdir(path) do
:file.make_dir(IO.chardata_to_string(path))
end
@doc """
Same as `mkdir/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
"""
@spec mkdir!(Path.t()) :: :ok
def mkdir!(path) do
case mkdir(path) do
:ok ->
:ok
{:error, reason} ->
raise File.Error,
reason: reason,
action: "make directory",
path: IO.chardata_to_string(path)
end
end
@doc """
Tries to create the directory `path`.
Missing parent directories are created. Returns `:ok` if successful, or
`{:error, reason}` if an error occurs.
Typical error reasons are:
* `:eacces` - missing search or write permissions for the parent
directories of `path`
* `:enospc` - there is no space left on the device
* `:enotdir` - a component of `path` is not a directory
"""
@spec mkdir_p(Path.t()) :: :ok | {:error, posix}
def mkdir_p(path) do
do_mkdir_p(IO.chardata_to_string(path))
end
defp do_mkdir_p("/") do
:ok
end
defp do_mkdir_p(path) do
if dir?(path) do
:ok
else
parent = Path.dirname(path)
if parent == path do
# Protect against infinite loop
{:error, :einval}
else
_ = do_mkdir_p(parent)
case :file.make_dir(path) do
{:error, :eexist} = error ->
if dir?(path), do: :ok, else: error
other ->
other
end
end
end
end
@doc """
Same as `mkdir_p/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
"""
@spec mkdir_p!(Path.t()) :: :ok
def mkdir_p!(path) do
case mkdir_p(path) do
:ok ->
:ok
{:error, reason} ->
raise File.Error,
reason: reason,
action: "make directory (with -p)",
path: IO.chardata_to_string(path)
end
end
@doc """
Returns `{:ok, binary}`, where `binary` is a binary data object that contains the contents
of `path`, or `{:error, reason}` if an error occurs.
Typical error reasons:
* `:enoent` - the file does not exist
* `:eacces` - missing permission for reading the file,
or for searching one of the parent directories
* `:eisdir` - the named file is a directory
* `:enotdir` - a component of the file name is not a directory;
on some platforms, `:enoent` is returned instead
* `:enomem` - there is not enough memory for the contents of the file
You can use `:file.format_error/1` to get a descriptive string of the error.
"""
@spec read(Path.t()) :: {:ok, binary} | {:error, posix}
def read(path) do
:file.read_file(IO.chardata_to_string(path))
end
@doc """
Returns a binary with the contents of the given filename,
or raises a `File.Error` exception if an error occurs.
"""
@spec read!(Path.t()) :: binary
def read!(path) do
case read(path) do
{:ok, binary} ->
binary
{:error, reason} ->
raise File.Error, reason: reason, action: "read file", path: IO.chardata_to_string(path)
end
end
@doc """
Returns information about the `path`. If it exists, it
returns a `{:ok, info}` tuple, where info is a
`File.Stat` struct. Returns `{:error, reason}` with
the same reasons as `read/1` if a failure occurs.
## Options
The accepted options are:
* `:time` - configures how the file timestamps are returned
The values for `:time` can be:
* `:universal` - returns a `{date, time}` tuple in UTC (default)
* `:local` - returns a `{date, time}` tuple using the same time zone as the
machine
* `:posix` - returns the time as integer seconds since epoch
Note: Since file times are stored in POSIX time format on most operating systems,
it is faster to retrieve file information with the `time: :posix` option.
"""
@spec stat(Path.t(), stat_options) :: {:ok, File.Stat.t()} | {:error, posix}
def stat(path, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
case :file.read_file_info(IO.chardata_to_string(path), opts) do
{:ok, fileinfo} ->
{:ok, File.Stat.from_record(fileinfo)}
error ->
error
end
end
@doc """
Same as `stat/2` but returns the `File.Stat` directly,
or raises a `File.Error` exception if an error is returned.
"""
@spec stat!(Path.t(), stat_options) :: File.Stat.t()
def stat!(path, opts \\ []) do
case stat(path, opts) do
{:ok, info} ->
info
{:error, reason} ->
raise File.Error,
reason: reason,
action: "read file stats",
path: IO.chardata_to_string(path)
end
end
@doc """
Returns information about the `path`. If the file is a symlink, sets
the `type` to `:symlink` and returns a `File.Stat` struct for the link. For any
other file, returns exactly the same values as `stat/2`.
For more details, see `:file.read_link_info/2`.
## Options
The accepted options are:
* `:time` - configures how the file timestamps are returned
The values for `:time` can be:
* `:universal` - returns a `{date, time}` tuple in UTC (default)
* `:local` - returns a `{date, time}` tuple using the machine time
* `:posix` - returns the time as integer seconds since epoch
Note: Since file times are stored in POSIX time format on most operating systems,
it is faster to retrieve file information with the `time: :posix` option.
"""
@spec lstat(Path.t(), stat_options) :: {:ok, File.Stat.t()} | {:error, posix}
def lstat(path, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
case :file.read_link_info(IO.chardata_to_string(path), opts) do
{:ok, fileinfo} ->
{:ok, File.Stat.from_record(fileinfo)}
error ->
error
end
end
@doc """
Same as `lstat/2` but returns the `File.Stat` struct directly,
or raises a `File.Error` exception if an error is returned.
"""
@spec lstat!(Path.t(), stat_options) :: File.Stat.t()
def lstat!(path, opts \\ []) do
case lstat(path, opts) do
{:ok, info} ->
info
{:error, reason} ->
raise File.Error,
reason: reason,
action: "read file stats",
path: IO.chardata_to_string(path)
end
end
@doc """
Reads the symbolic link at `path`.
If `path` exists and is a symlink, returns `{:ok, target}`, otherwise returns
`{:error, reason}`.
For more details, see `:file.read_link/1`.
Typical error reasons are:
* `:einval` - path is not a symbolic link
* `:enoent` - path does not exist
* `:enotsup` - symbolic links are not supported on the current platform
"""
@doc since: "1.5.0"
@spec read_link(Path.t()) :: {:ok, binary} | {:error, posix}
def read_link(path) do
case path |> IO.chardata_to_string() |> :file.read_link() do
{:ok, target} -> {:ok, IO.chardata_to_string(target)}
error -> error
end
end
@doc """
Same as `read_link/1` but returns the target directly,
or raises a `File.Error` exception if an error is returned.
"""
@doc since: "1.5.0"
@spec read_link!(Path.t()) :: binary
def read_link!(path) do
case read_link(path) do
{:ok, resolved} ->
resolved
{:error, reason} ->
raise File.Error, reason: reason, action: "read link", path: IO.chardata_to_string(path)
end
end
@doc """
Writes the given `File.Stat` back to the file system at the given
path. Returns `:ok` or `{:error, reason}`.
"""
@spec write_stat(Path.t(), File.Stat.t(), stat_options) :: :ok | {:error, posix}
def write_stat(path, stat, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
:file.write_file_info(IO.chardata_to_string(path), File.Stat.to_record(stat), opts)
end
@doc """
Same as `write_stat/3` but raises a `File.Error` exception if it fails.
Returns `:ok` otherwise.
"""
@spec write_stat!(Path.t(), File.Stat.t(), stat_options) :: :ok
def write_stat!(path, stat, opts \\ []) do
case write_stat(path, stat, opts) do
:ok ->
:ok
{:error, reason} ->
raise File.Error,
reason: reason,
action: "write file stats",
path: IO.chardata_to_string(path)
end
end
@doc """
Updates modification time (mtime) and access time (atime) of
the given file.
The file is created if it doesn't exist. Requires datetime in UTC
(as returned by `:erlang.universaltime()`) or an integer
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
In Unix-like systems, changing the modification time may require
you to be either `root` or the owner of the file. Having write
access may not be enough. In those cases, touching the file the
first time (to create it) will succeed, but touching an existing
file with fail with `{:error, :eperm}`.
## Examples
File.touch("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
#=> :ok
File.touch("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
{:error, :enoent}
File.touch("/tmp/a.txt", 1544519753)
#=> :ok
"""
@spec touch(Path.t(), erlang_time() | posix_time()) :: :ok | {:error, posix}
def touch(path, time \\ System.os_time(:second))
def touch(path, time) when is_tuple(time) do
path = IO.chardata_to_string(path)
with {:error, :enoent} <- :elixir_utils.change_universal_time(path, time),
:ok <- write(path, "", [:append]),
do: :elixir_utils.change_universal_time(path, time)
end
def touch(path, time) when is_integer(time) do
path = IO.chardata_to_string(path)
with {:error, :enoent} <- :elixir_utils.change_posix_time(path, time),
:ok <- write(path, "", [:append]),
do: :elixir_utils.change_posix_time(path, time)
end
@doc """
Same as `touch/2` but raises a `File.Error` exception if it fails.
Returns `:ok` otherwise.
The file is created if it doesn't exist. Requires datetime in UTC
(as returned by `:erlang.universaltime()`) or an integer
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
## Examples
File.touch!("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
#=> :ok
File.touch!("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
** (File.Error) could not touch "/fakedir/b.txt": no such file or directory
File.touch!("/tmp/a.txt", 1544519753)
"""
@spec touch!(Path.t(), erlang_time() | posix_time()) :: :ok
def touch!(path, time \\ System.os_time(:second)) do
case touch(path, time) do
:ok ->
:ok
{:error, reason} ->
raise File.Error, reason: reason, action: "touch", path: IO.chardata_to_string(path)
end
end
@doc """
Creates a hard link `new` to the file `existing`.
Returns `:ok` if successful, `{:error, reason}` otherwise.
If the operating system does not support hard links, returns
`{:error, :enotsup}`.
"""
@doc since: "1.5.0"
@spec ln(Path.t(), Path.t()) :: :ok | {:error, posix}
def ln(existing, new) do
:file.make_link(IO.chardata_to_string(existing), IO.chardata_to_string(new))
end
@doc """
Same as `ln/2` but raises a `File.LinkError` exception if it fails.
Returns `:ok` otherwise.
"""
@doc since: "1.5.0"
@spec ln!(Path.t(), Path.t()) :: :ok
def ln!(existing, new) do
case ln(existing, new) do
:ok ->
:ok
{:error, reason} ->
raise File.LinkError,
reason: reason,
action: "create hard link",
existing: IO.chardata_to_string(existing),
new: IO.chardata_to_string(new)
end
end
@doc """
Creates a symbolic link `new` to the file or directory `existing`.
Returns `:ok` if successful, `{:error, reason}` otherwise.
If the operating system does not support symlinks, returns
`{:error, :enotsup}`.
"""
@doc since: "1.5.0"
@spec ln_s(Path.t(), Path.t()) :: :ok | {:error, posix}
def ln_s(existing, new) do
:file.make_symlink(IO.chardata_to_string(existing), IO.chardata_to_string(new))
end
@doc """
Same as `ln_s/2` but raises a `File.LinkError` exception if it fails.
Returns `:ok` otherwise.
"""
@spec ln_s!(Path.t(), Path.t()) :: :ok
def ln_s!(existing, new) do
case ln_s(existing, new) do
:ok ->
:ok
{:error, reason} ->
raise File.LinkError,
reason: reason,
action: "create symlink",
existing: IO.chardata_to_string(existing),
new: IO.chardata_to_string(new)
end
end
@doc """
Copies the contents of `source` to `destination`.
Both parameters can be a filename or an IO device opened
with `open/2`. `bytes_count` specifies the number of
bytes to copy, the default being `:infinity`.
If file `destination` already exists, it is overwritten
by the contents in `source`.
Returns `{:ok, bytes_copied}` if successful,
`{:error, reason}` otherwise.
Compared to the `cp/3`, this function is more low-level,
allowing a copy from device to device limited by a number of
bytes. On the other hand, `cp/3` performs more extensive
checks on both source and destination and it also preserves
the file mode after copy.
Typical error reasons are the same as in `open/2`,
`read/1` and `write/3`.
"""
@spec copy(Path.t() | io_device, Path.t() | io_device, pos_integer | :infinity) ::
{:ok, non_neg_integer} | {:error, posix}
def copy(source, destination, bytes_count \\ :infinity) do
:file.copy(maybe_to_string(source), maybe_to_string(destination), bytes_count)
end
@doc """
The same as `copy/3` but raises a `File.CopyError` exception if it fails.
Returns the `bytes_copied` otherwise.
"""
@spec copy!(Path.t() | io_device, Path.t() | io_device, pos_integer | :infinity) ::
non_neg_integer
def copy!(source, destination, bytes_count \\ :infinity) do
case copy(source, destination, bytes_count) do
{:ok, bytes_count} ->
bytes_count
{:error, reason} ->
raise File.CopyError,
reason: reason,
action: "copy",
source: maybe_to_string(source),
destination: maybe_to_string(destination)
end
end
@doc """
Renames the `source` file to `destination` file. It can be used to move files
(and directories) between directories. If moving a file, you must fully
specify the `destination` filename, it is not sufficient to simply specify
its directory.
Returns `:ok` in case of success, `{:error, reason}` otherwise.
Note: The command `mv` in Unix-like systems behaves differently depending on
whether `source` is a file and the `destination` is an existing directory.
We have chosen to explicitly disallow this behaviour.
## Examples
# Rename file "a.txt" to "b.txt"
File.rename("a.txt", "b.txt")
# Rename directory "samples" to "tmp"
File.rename("samples", "tmp")
"""
@spec rename(Path.t(), Path.t()) :: :ok | {:error, posix}
def rename(source, destination) do
:file.rename(source, destination)
end
@doc """
The same as `rename/2` but raises a `File.RenameError` exception if it fails.
Returns `:ok` otherwise.
"""
@doc since: "1.9.0"
@spec rename!(Path.t(), Path.t()) :: :ok
def rename!(source, destination) do
case rename(source, destination) do
:ok ->
:ok
{:error, reason} ->
raise File.RenameError,
reason: reason,
action: "rename",
source: IO.chardata_to_string(source),
destination: IO.chardata_to_string(destination)
end
end
@doc """
Copies the contents in `source_file` to `destination_file` preserving its modes.
`source_file` and `destination_file` must be a file or a symbolic link to one,
or in the case of destination, a path to a non-existent file. If either one of
them is a directory, `{:error, :eisdir}` will be returned.
If a file already exists in the destination, it invokes a
callback which should return `true` if the existing file
should be overwritten, `false` otherwise. The callback defaults to return `true`.
The function returns `:ok` in case of success. Otherwise, it returns
`{:error, reason}`.
If you want to copy contents from an IO device to another device
or do a straight copy from a source to a destination without
preserving modes, check `copy/3` instead.
Note: The command `cp` in Unix-like systems behaves differently depending on
whether the destination is an existing directory or not. We have chosen to
explicitly disallow copying to a destination which is a directory,
and an error will be returned if tried.
"""
@spec cp(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok | {:error, posix}
def cp(source_file, destination_file, callback \\ fn _, _ -> true end) do
source_file = IO.chardata_to_string(source_file)
destination_file = IO.chardata_to_string(destination_file)
case do_cp_file(source_file, destination_file, callback, []) do
{:error, reason, _} -> {:error, reason}
_ -> :ok
end
end
defp path_differs?(path, path), do: false
defp path_differs?(p1, p2) do
Path.expand(p1) !== Path.expand(p2)
end
@doc """
The same as `cp/3`, but raises a `File.CopyError` exception if it fails.
Returns `:ok` otherwise.
"""
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok
def cp!(source_file, destination_file, callback \\ fn _, _ -> true end) do
case cp(source_file, destination_file, callback) do
:ok ->
:ok
{:error, reason} ->
raise File.CopyError,
reason: reason,
action: "copy",
source: IO.chardata_to_string(source_file),
destination: IO.chardata_to_string(destination_file)
end
end
@doc ~S"""
Copies the contents in `source` to `destination` recursively, maintaining the
source directory structure and modes.
If `source` is a file or a symbolic link to it, `destination` must be a path
to an existent file, a symbolic link to one, or a path to a non-existent file.
If `source` is a directory, or a symbolic link to it, then `destination` must
be an existent `directory` or a symbolic link to one, or a path to a non-existent directory.
If the source is a file, it copies `source` to
`destination`. If the `source` is a directory, it copies
the contents inside source into the `destination` directory.
If a file already exists in the destination, it invokes `callback`.
`callback` must be a function that takes two arguments: `source` and `destination`.
The callback should return `true` if the existing file should be overwritten and `false` otherwise.
This function may fail while copying files,
in such cases, it will leave the destination
directory in a dirty state, where file which have already been copied
won't be removed.
The function returns `{:ok, files_and_directories}` in case of
success, `files_and_directories` lists all files and directories copied in no
specific order. It returns `{:error, reason, file}` otherwise.
Note: The command `cp` in Unix-like systems behaves differently depending on
whether `destination` is an existing directory or not. We have chosen to
explicitly disallow this behaviour. If `source` is a `file` and `destination`
is a directory, `{:error, :eisdir}` will be returned.
## Examples
# Copies file "a.txt" to "b.txt"
File.cp_r("a.txt", "b.txt")
# Copies all files in "samples" to "tmp"
File.cp_r("samples", "tmp")
# Same as before, but asks the user how to proceed in case of conflicts
File.cp_r("samples", "tmp", fn source, destination ->
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm. ") == "y\n"
end)
"""
@spec cp_r(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) ::
{:ok, [binary]} | {:error, posix, binary}
def cp_r(source, destination, callback \\ fn _, _ -> true end) when is_function(callback, 2) do
source =
source
|> IO.chardata_to_string()
|> assert_no_null_byte!("File.cp_r/3")
destination =
destination
|> IO.chardata_to_string()
|> assert_no_null_byte!("File.cp_r/3")
case do_cp_r(source, destination, callback, []) do
{:error, _, _} = error -> error
res -> {:ok, res}
end
end
@doc """
The same as `cp_r/3`, but raises a `File.CopyError` exception if it fails.
Returns the list of copied files otherwise.
"""
@spec cp_r!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: [binary]
def cp_r!(source, destination, callback \\ fn _, _ -> true end) do
case cp_r(source, destination, callback) do
{:ok, files} ->
files
{:error, reason, file} ->
raise File.CopyError,
reason: reason,
action: "copy recursively",
on: file,
source: IO.chardata_to_string(source),
destination: IO.chardata_to_string(destination)
end
end
defp do_cp_r(src, dest, callback, acc) when is_list(acc) do
case :elixir_utils.read_link_type(src) do
{:ok, :regular} ->
do_cp_file(src, dest, callback, acc)
{:ok, :symlink} ->
case :file.read_link(src) do
{:ok, link} -> do_cp_link(link, src, dest, callback, acc)
{:error, reason} -> {:error, reason, src}
end
{:ok, :directory} ->
case :file.list_dir(src) do
{:ok, files} ->
case mkdir(dest) do
success when success in [:ok, {:error, :eexist}] ->
Enum.reduce(files, [dest | acc], fn x, acc ->
do_cp_r(Path.join(src, x), Path.join(dest, x), callback, acc)
end)
{:error, reason} ->
{:error, reason, dest}
end
{:error, reason} ->
{:error, reason, src}
end
{:ok, _} ->
{:error, :eio, src}
{:error, reason} ->
{:error, reason, src}
end
end
# If we reach this clause, there was an error while
# processing a file.
defp do_cp_r(_, _, _, acc) do
acc
end
defp copy_file_mode!(src, dest) do
write_stat!(dest, %{stat!(dest) | mode: stat!(src).mode})
end
# Both src and dest are files.
defp do_cp_file(src, dest, callback, acc) do
case :file.copy(src, {dest, [:exclusive]}) do
{:ok, _} ->
copy_file_mode!(src, dest)
[dest | acc]
{:error, :eexist} ->
if path_differs?(src, dest) and callback.(src, dest) do
case copy(src, dest) do
{:ok, _} ->
copy_file_mode!(src, dest)
[dest | acc]
{:error, reason} ->
{:error, reason, src}
end
else
acc
end
{:error, reason} ->
{:error, reason, src}
end
end
# Both src and dest are files.
defp do_cp_link(link, src, dest, callback, acc) do
case :file.make_symlink(link, dest) do
:ok ->
[dest | acc]
{:error, :eexist} ->
if path_differs?(src, dest) and callback.(src, dest) do
# If rm/1 fails, :file.make_symlink/2 will fail
_ = rm(dest)
case :file.make_symlink(link, dest) do
:ok -> [dest | acc]
{:error, reason} -> {:error, reason, src}
end
else
acc
end
{:error, reason} ->
{:error, reason, src}
end