-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathfile.jl
1471 lines (1266 loc) · 47.8 KB
/
file.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
# Operations with the file system (paths) ##
export
cd,
chmod,
chown,
cp,
cptree,
diskstat,
hardlink,
mkdir,
mkpath,
mktemp,
mktempdir,
mv,
pwd,
rename,
readlink,
readdir,
rm,
samefile,
sendfile,
symlink,
tempdir,
tempname,
touch,
unlink,
walkdir
# get and set current directory
"""
pwd() -> String
Get the current working directory.
See also: [`cd`](@ref), [`tempdir`](@ref).
# Examples
```julia-repl
julia> pwd()
"/home/JuliaUser"
julia> cd("/home/JuliaUser/Projects/julia")
julia> pwd()
"/home/JuliaUser/Projects/julia"
```
"""
function pwd()
buf = Base.StringVector(AVG_PATH - 1) # space for null-terminator implied by StringVector
sz = RefValue{Csize_t}(length(buf) + 1) # total buffer size including null
while true
rc = ccall(:uv_cwd, Cint, (Ptr{UInt8}, Ptr{Csize_t}), buf, sz)
if rc == 0
resize!(buf, sz[])
return String(buf)
elseif rc == Base.UV_ENOBUFS
resize!(buf, sz[] - 1) # space for null-terminator implied by StringVector
else
uv_error("pwd()", rc)
end
end
end
"""
cd(dir::AbstractString=homedir())
Set the current working directory.
See also: [`pwd`](@ref), [`mkdir`](@ref), [`mkpath`](@ref), [`mktempdir`](@ref).
# Examples
```julia-repl
julia> cd("/home/JuliaUser/Projects/julia")
julia> pwd()
"/home/JuliaUser/Projects/julia"
julia> cd()
julia> pwd()
"/home/JuliaUser"
```
"""
function cd(dir::AbstractString)
err = ccall(:uv_chdir, Cint, (Cstring,), dir)
err < 0 && uv_error("cd($(repr(dir)))", err)
return nothing
end
cd() = cd(homedir())
if Sys.iswindows()
function cd(f::Function, dir::AbstractString)
old = pwd()
try
cd(dir)
f()
finally
cd(old)
end
end
else
function cd(f::Function, dir::AbstractString)
fd = ccall(:open, Int32, (Cstring, Int32, UInt32...), :., 0)
systemerror(:open, fd == -1)
try
cd(dir)
f()
finally
systemerror(:fchdir, ccall(:fchdir, Int32, (Int32,), fd) != 0)
systemerror(:close, ccall(:close, Int32, (Int32,), fd) != 0)
end
end
end
"""
cd(f::Function, dir::AbstractString=homedir())
Temporarily change the current working directory to `dir`, apply function `f` and
finally return to the original directory.
# Examples
```julia-repl
julia> pwd()
"/home/JuliaUser"
julia> cd(readdir, "/home/JuliaUser/Projects/julia")
34-element Vector{String}:
".circleci"
".freebsdci.sh"
".git"
".gitattributes"
".github"
⋮
"test"
"ui"
"usr"
"usr-staging"
julia> pwd()
"/home/JuliaUser"
```
"""
cd(f::Function) = cd(f, homedir())
function checkmode(mode::Integer)
if !(0 <= mode <= 511)
throw(ArgumentError("Mode must be between 0 and 511 = 0o777"))
end
mode
end
"""
mkdir(path::AbstractString; mode::Unsigned = 0o777)
Make a new directory with name `path` and permissions `mode`. `mode` defaults to `0o777`,
modified by the current file creation mask. This function never creates more than one
directory. If the directory already exists, or some intermediate directories do not exist,
this function throws an error. See [`mkpath`](@ref) for a function which creates all
required intermediate directories.
Return `path`.
# Examples
```julia-repl
julia> mkdir("testingdir")
"testingdir"
julia> cd("testingdir")
julia> pwd()
"/home/JuliaUser/testingdir"
```
"""
function mkdir(path::AbstractString; mode::Integer = 0o777)
req = Libc.malloc(_sizeof_uv_fs)
try
ret = ccall(:uv_fs_mkdir, Cint,
(Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Cint, Ptr{Cvoid}),
C_NULL, req, path, checkmode(mode), C_NULL)
if ret < 0
uv_fs_req_cleanup(req)
uv_error("mkdir($(repr(path)); mode=0o$(string(mode,base=8)))", ret)
end
uv_fs_req_cleanup(req)
return path
finally
Libc.free(req)
end
end
"""
mkpath(path::AbstractString; mode::Unsigned = 0o777)
Create all intermediate directories in the `path` as required. Directories are created with
the permissions `mode` which defaults to `0o777` and is modified by the current file
creation mask. Unlike [`mkdir`](@ref), `mkpath` does not error if `path` (or parts of it)
already exists. However, an error will be thrown if `path` (or parts of it) points to an
existing file. Return `path`.
If `path` includes a filename you will probably want to use `mkpath(dirname(path))` to
avoid creating a directory using the filename.
# Examples
```julia-repl
julia> cd(mktempdir())
julia> mkpath("my/test/dir") # creates three directories
"my/test/dir"
julia> readdir()
1-element Vector{String}:
"my"
julia> cd("my")
julia> readdir()
1-element Vector{String}:
"test"
julia> readdir("test")
1-element Vector{String}:
"dir"
julia> mkpath("intermediate_dir/actually_a_directory.txt") # creates two directories
"intermediate_dir/actually_a_directory.txt"
julia> isdir("intermediate_dir/actually_a_directory.txt")
true
julia> mkpath("my/test/dir/") # returns the original `path`
"my/test/dir/"
```
"""
function mkpath(path::AbstractString; mode::Integer = 0o777)
parent = dirname(path)
# stop recursion for `""`, `"/"`, or existing dir
(path == parent || isdir(path)) && return path
mkpath(parent, mode = checkmode(mode))
try
# The `isdir` check could be omitted, then `mkdir` will throw an error in cases like `x/`.
# Although the error will not be rethrown, we avoid it in advance for performance reasons.
isdir(path) || mkdir(path, mode = mode)
catch err
# If there is a problem with making the directory, but the directory
# does in fact exist, then ignore the error. Else re-throw it.
if !isa(err, IOError) || !isdir(path)
rethrow()
end
end
return path
end
# Files that were requested to be deleted but can't be by the current process
# i.e. loaded DLLs on Windows
delayed_delete_dir() = joinpath(tempdir(), "julia_delayed_deletes")
"""
rm(path::AbstractString; force::Bool=false, recursive::Bool=false)
Delete the file, link, or empty directory at the given path. If `force=true` is passed, a
non-existing path is not treated as error. If `recursive=true` is passed and the path is a
directory, then all contents are removed recursively.
# Examples
```jldoctest
julia> mkpath("my/test/dir");
julia> rm("my", recursive=true)
julia> rm("this_file_does_not_exist", force=true)
julia> rm("this_file_does_not_exist")
ERROR: IOError: unlink("this_file_does_not_exist"): no such file or directory (ENOENT)
Stacktrace:
[...]
```
"""
function rm(path::AbstractString; force::Bool=false, recursive::Bool=false, allow_delayed_delete::Bool=true)
# allow_delayed_delete is used by Pkg.gc() but is otherwise not part of the public API
if islink(path) || !isdir(path)
try
unlink(path)
catch err
if isa(err, IOError)
force && err.code==Base.UV_ENOENT && return
@static if Sys.iswindows()
if allow_delayed_delete && err.code==Base.UV_EACCES && endswith(path, ".dll")
# Loaded DLLs cannot be deleted on Windows, even with posix delete mode
# but they can be moved. So move out to allow the dir to be deleted.
# Pkg.gc() cleans up this dir when possible
dir = mkpath(delayed_delete_dir())
temp_path = tempname(dir, cleanup = false, suffix = string("_", basename(path)))
@debug "Could not delete DLL most likely because it is loaded, moving to tempdir" path temp_path
mv(path, temp_path)
return
end
end
end
rethrow()
end
else
if recursive
try
for p in readdir(path)
try
rm(joinpath(path, p), force=force, recursive=true)
catch err
(isa(err, IOError) && err.code==Base.UV_EACCES) || rethrow()
end
end
catch err
(isa(err, IOError) && err.code==Base.UV_EACCES) || rethrow()
end
end
req = Libc.malloc(_sizeof_uv_fs)
try
ret = ccall(:uv_fs_rmdir, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Ptr{Cvoid}), C_NULL, req, path, C_NULL)
uv_fs_req_cleanup(req)
if ret < 0 && !(force && ret == Base.UV_ENOENT)
uv_error("rm($(repr(path)))", ret)
end
nothing
finally
Libc.free(req)
end
end
end
# The following use Unix command line facilities
function checkfor_mv_cp_cptree(src::AbstractString, dst::AbstractString, txt::AbstractString;
force::Bool=false)
if ispath(dst)
if force
# Check for issue when: (src == dst) or when one is a link to the other
# https://github.com/JuliaLang/julia/pull/11172#issuecomment-100391076
if Base.samefile(src, dst)
abs_src = islink(src) ? abspath(readlink(src)) : abspath(src)
abs_dst = islink(dst) ? abspath(readlink(dst)) : abspath(dst)
throw(ArgumentError(string("'src' and 'dst' refer to the same file/dir. ",
"This is not supported.\n ",
"`src` refers to: $(abs_src)\n ",
"`dst` refers to: $(abs_dst)\n")))
end
rm(dst; recursive=true, force=true)
else
throw(ArgumentError(string("'$dst' exists. `force=true` ",
"is required to remove '$dst' before $(txt).")))
end
end
end
function cptree(src::String, dst::String; force::Bool=false,
follow_symlinks::Bool=false)
isdir(src) || throw(ArgumentError("'$src' is not a directory. Use `cp(src, dst)`"))
checkfor_mv_cp_cptree(src, dst, "copying"; force=force)
mkdir(dst)
for name in readdir(src)
srcname = joinpath(src, name)
if !follow_symlinks && islink(srcname)
symlink(readlink(srcname), joinpath(dst, name))
elseif isdir(srcname)
cptree(srcname, joinpath(dst, name); force=force,
follow_symlinks=follow_symlinks)
else
sendfile(srcname, joinpath(dst, name))
end
end
end
cptree(src::AbstractString, dst::AbstractString; kwargs...) =
cptree(String(src)::String, String(dst)::String; kwargs...)
"""
cp(src::AbstractString, dst::AbstractString; force::Bool=false, follow_symlinks::Bool=false)
Copy the file, link, or directory from `src` to `dst`.
`force=true` will first remove an existing `dst`.
If `follow_symlinks=false`, and `src` is a symbolic link, `dst` will be created as a
symbolic link. If `follow_symlinks=true` and `src` is a symbolic link, `dst` will be a copy
of the file or directory `src` refers to.
Return `dst`.
!!! note
The `cp` function is different from the `cp` Unix command. The `cp` function always operates on
the assumption that `dst` is a file, while the command does different things depending
on whether `dst` is a directory or a file.
Using `force=true` when `dst` is a directory will result in loss of all the contents present
in the `dst` directory, and `dst` will become a file that has the contents of `src` instead.
"""
function cp(src::AbstractString, dst::AbstractString; force::Bool=false,
follow_symlinks::Bool=false)
checkfor_mv_cp_cptree(src, dst, "copying"; force=force)
if !follow_symlinks && islink(src)
symlink(readlink(src), dst)
elseif isdir(src)
cptree(src, dst; force=force, follow_symlinks=follow_symlinks)
else
sendfile(src, dst)
end
dst
end
"""
mv(src::AbstractString, dst::AbstractString; force::Bool=false)
Move the file, link, or directory from `src` to `dst`.
`force=true` will first remove an existing `dst`.
Return `dst`.
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> write("hello.txt", "world");
julia> mv("hello.txt", "goodbye.txt")
"goodbye.txt"
julia> "hello.txt" in readdir()
false
julia> readline("goodbye.txt")
"world"
julia> write("hello.txt", "world2");
julia> mv("hello.txt", "goodbye.txt")
ERROR: ArgumentError: 'goodbye.txt' exists. `force=true` is required to remove 'goodbye.txt' before moving.
Stacktrace:
[1] #checkfor_mv_cp_cptree#10(::Bool, ::Function, ::String, ::String, ::String) at ./file.jl:293
[...]
julia> mv("hello.txt", "goodbye.txt", force=true)
"goodbye.txt"
julia> rm("goodbye.txt");
```
!!! note
The `mv` function is different from the `mv` Unix command. The `mv` function by
default will error if `dst` exists, while the command will delete
an existing `dst` file by default.
Also the `mv` function always operates on
the assumption that `dst` is a file, while the command does different things depending
on whether `dst` is a directory or a file.
Using `force=true` when `dst` is a directory will result in loss of all the contents present
in the `dst` directory, and `dst` will become a file that has the contents of `src` instead.
"""
function mv(src::AbstractString, dst::AbstractString; force::Bool=false)
if force
_mv_replace(src, dst)
else
_mv_noreplace(src, dst)
end
end
function _mv_replace(src::AbstractString, dst::AbstractString)
# This check is copied from checkfor_mv_cp_cptree
if ispath(dst) && Base.samefile(src, dst)
abs_src = islink(src) ? abspath(readlink(src)) : abspath(src)
abs_dst = islink(dst) ? abspath(readlink(dst)) : abspath(dst)
throw(ArgumentError(string("'src' and 'dst' refer to the same file/dir. ",
"This is not supported.\n ",
"`src` refers to: $(abs_src)\n ",
"`dst` refers to: $(abs_dst)\n")))
end
# First try to do a regular rename, because this might avoid a situation
# where dst is deleted or truncated.
try
rename(src, dst)
catch err
err isa IOError || rethrow()
err.code==Base.UV_ENOENT && rethrow()
# on rename error try to delete dst if it exists and isn't the same as src
checkfor_mv_cp_cptree(src, dst, "moving"; force=true)
try
rename(src, dst)
catch err
err isa IOError || rethrow()
# on second error, default to force cp && rm
cp(src, dst; force=true, follow_symlinks=false)
rm(src; recursive=true)
end
end
dst
end
function _mv_noreplace(src::AbstractString, dst::AbstractString)
# Error if dst exists.
# This check currently has TOCTTOU issues.
checkfor_mv_cp_cptree(src, dst, "moving"; force=false)
try
rename(src, dst)
catch err
err isa IOError || rethrow()
err.code==Base.UV_ENOENT && rethrow()
# on error, default to cp && rm
cp(src, dst; force=false, follow_symlinks=false)
rm(src; recursive=true)
end
dst
end
"""
touch(path::AbstractString)
touch(fd::File)
Update the last-modified timestamp on a file to the current time.
If the file does not exist a new file is created.
Return `path`.
# Examples
```julia-repl
julia> write("my_little_file", 2);
julia> mtime("my_little_file")
1.5273815391135583e9
julia> touch("my_little_file");
julia> mtime("my_little_file")
1.527381559163435e9
```
We can see the [`mtime`](@ref) has been modified by `touch`.
"""
function touch(path::AbstractString)
f = open(path, JL_O_WRONLY | JL_O_CREAT, 0o0666)
try
touch(f)
finally
close(f)
end
path
end
"""
tempdir()
Gets the path of the temporary directory. On Windows, `tempdir()` uses the first environment
variable found in the ordered list `TMP`, `TEMP`, `USERPROFILE`. On all other operating
systems, `tempdir()` uses the first environment variable found in the ordered list `TMPDIR`,
`TMP`, `TEMP`, and `TEMPDIR`. If none of these are found, the path `"/tmp"` is used.
"""
function tempdir()
buf = Base.StringVector(AVG_PATH - 1) # space for null-terminator implied by StringVector
sz = RefValue{Csize_t}(length(buf) + 1) # total buffer size including null
while true
rc = ccall(:uv_os_tmpdir, Cint, (Ptr{UInt8}, Ptr{Csize_t}), buf, sz)
if rc == 0
resize!(buf, sz[])
break
elseif rc == Base.UV_ENOBUFS
resize!(buf, sz[] - 1) # space for null-terminator implied by StringVector
else
uv_error("tempdir()", rc)
end
end
tempdir = String(buf)
try
s = stat(tempdir)
if !ispath(s)
@warn "tempdir path does not exist" tempdir
elseif !isdir(s)
@warn "tempdir path is not a directory" tempdir
end
catch ex
ex isa IOError || ex isa SystemError || rethrow()
@warn "accessing tempdir path failed" _exception=ex
end
return tempdir
end
"""
prepare_for_deletion(path::AbstractString)
Prepares the given `path` for deletion by ensuring that all directories within that
`path` have write permissions, so that files can be removed from them. This is
automatically invoked by methods such as `mktempdir()` to ensure that no matter what
weird permissions a user may have created directories with within the temporary prefix,
it will always be deleted.
"""
function prepare_for_deletion(path::AbstractString)
# Nothing to do for non-directories
if !isdir(path)
return
end
try
chmod(path, filemode(path) | 0o333)
catch ex
ex isa IOError || ex isa SystemError || rethrow()
end
for (root, dirs, files) in walkdir(path; onerror=x->())
for dir in dirs
dpath = joinpath(root, dir)
try
chmod(dpath, filemode(dpath) | 0o333)
catch ex
ex isa IOError || ex isa SystemError || rethrow()
end
end
end
end
const TEMP_CLEANUP_MIN = Ref(1024)
const TEMP_CLEANUP_MAX = Ref(1024)
const TEMP_CLEANUP = Dict{String,Bool}()
const TEMP_CLEANUP_LOCK = ReentrantLock()
function temp_cleanup_later(path::AbstractString; asap::Bool=false)
@lock TEMP_CLEANUP_LOCK begin
# each path should only be inserted here once, but if there
# is a collision, let !asap win over asap: if any user might
# still be using the path, don't delete it until process exit
TEMP_CLEANUP[path] = get(TEMP_CLEANUP, path, true) & asap
if length(TEMP_CLEANUP) > TEMP_CLEANUP_MAX[]
temp_cleanup_purge_prelocked(false)
TEMP_CLEANUP_MAX[] = max(TEMP_CLEANUP_MIN[], 2*length(TEMP_CLEANUP))
end
end
nothing
end
function temp_cleanup_forget(path::AbstractString)
@lock TEMP_CLEANUP_LOCK delete!(TEMP_CLEANUP, path)
nothing
end
function temp_cleanup_purge_prelocked(force::Bool)
filter!(TEMP_CLEANUP) do (path, asap)
try
ispath(path) || return false
if force || asap
prepare_for_deletion(path)
rm(path, recursive=true, force=true)
end
return ispath(path)
catch ex
@warn """
Failed to clean up temporary path $(repr(path))
$ex
""" _group=:file
ex isa InterruptException && rethrow()
return true
end
end
nothing
end
function temp_cleanup_purge_all()
may_need_gc = false
@lock TEMP_CLEANUP_LOCK filter!(TEMP_CLEANUP) do (path, asap)
try
ispath(path) || return false
may_need_gc = true
return true
catch ex
ex isa InterruptException && rethrow()
return true
end
end
if may_need_gc
# this is only usually required on Sys.iswindows(), but may as well do it everywhere
GC.gc(true)
end
@lock TEMP_CLEANUP_LOCK temp_cleanup_purge_prelocked(true)
nothing
end
# deprecated internal function used by some packages
temp_cleanup_purge(; force=false) = force ? temp_cleanup_purge_all() : @lock TEMP_CLEANUP_LOCK temp_cleanup_purge_prelocked(false)
function __postinit__()
Base.atexit(temp_cleanup_purge_all)
end
const temp_prefix = "jl_"
# Use `Libc.rand()` to generate random strings
function _rand_filename(len = 10)
slug = Base.StringVector(len)
chars = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i = 1:len
slug[i] = chars[(Libc.rand() % length(chars)) + 1]
end
return String(slug)
end
# Obtain a temporary filename.
function tempname(parent::AbstractString=tempdir(); max_tries::Int = 100, cleanup::Bool=true, suffix::AbstractString="")
isdir(parent) || throw(ArgumentError("$(repr(parent)) is not a directory"))
prefix = joinpath(parent, temp_prefix)
filename = nothing
for i in 1:max_tries
filename = string(prefix, _rand_filename(), suffix)
if ispath(filename)
filename = nothing
else
break
end
end
if filename === nothing
error("tempname: max_tries exhausted")
end
cleanup && temp_cleanup_later(filename)
return filename
end
if Sys.iswindows()
# While this isn't a true analog of `mkstemp`, it _does_ create an
# empty file for us, ensuring that other simultaneous calls to
# `_win_mkstemp()` won't collide, so it's a better name for the
# function than `tempname()`.
function _win_mkstemp(temppath::AbstractString)
tempp = cwstring(temppath)
temppfx = cwstring(temp_prefix)
tname = Vector{UInt16}(undef, 32767)
uunique = ccall(:GetTempFileNameW, stdcall, UInt32,
(Ptr{UInt16}, Ptr{UInt16}, UInt32, Ptr{UInt16}),
tempp, temppfx, UInt32(0), tname)
windowserror("GetTempFileName", uunique == 0)
lentname = something(findfirst(iszero, tname))
@assert lentname > 0
resize!(tname, lentname - 1)
return transcode(String, tname)
end
function mktemp(parent::AbstractString=tempdir(); cleanup::Bool=true)
filename = _win_mkstemp(parent)
cleanup && temp_cleanup_later(filename)
return (filename, Base.open(filename, "r+"))
end
else # !windows
# Create and return the name of a temporary file along with an IOStream
function mktemp(parent::AbstractString=tempdir(); cleanup::Bool=true)
b = joinpath(parent, temp_prefix * "XXXXXX")
p = ccall(:mkstemp, Int32, (Cstring,), b) # modifies b
systemerror(:mktemp, p == -1)
cleanup && temp_cleanup_later(b)
return (b, fdio(p, true))
end
end # os-test
"""
tempname(parent=tempdir(); cleanup=true, suffix="") -> String
Generate a temporary file path. This function only returns a path; no file is
created. The path is likely to be unique, but this cannot be guaranteed due to
the very remote possibility of two simultaneous calls to `tempname` generating
the same file name. The name is guaranteed to differ from all files already
existing at the time of the call to `tempname`.
When called with no arguments, the temporary name will be an absolute path to a
temporary name in the system temporary directory as given by `tempdir()`. If a
`parent` directory argument is given, the temporary path will be in that
directory instead. If a suffix is given the tempname will end with that suffix
and be tested for uniqueness with that suffix.
The `cleanup` option controls whether the process attempts to delete the
returned path automatically when the process exits. Note that the `tempname`
function does not create any file or directory at the returned location, so
there is nothing to cleanup unless you create a file or directory there. If
you do and `cleanup` is `true` it will be deleted upon process termination.
!!! compat "Julia 1.4"
The `parent` and `cleanup` arguments were added in 1.4. Prior to Julia 1.4
the path `tempname` would never be cleaned up at process termination.
!!! compat "Julia 1.12"
The `suffix` keyword argument was added in Julia 1.12.
!!! warning
This can lead to security holes if another process obtains the same
file name and creates the file before you are able to. Open the file with
`JL_O_EXCL` if this is a concern. Using [`mktemp()`](@ref) is also
recommended instead.
"""
tempname()
"""
mktemp(parent=tempdir(); cleanup=true) -> (path, io)
Return `(path, io)`, where `path` is the path of a new temporary file in `parent`
and `io` is an open file object for this path. The `cleanup` option controls whether
the temporary file is automatically deleted when the process exits.
!!! compat "Julia 1.3"
The `cleanup` keyword argument was added in Julia 1.3. Relatedly, starting from 1.3,
Julia will remove the temporary paths created by `mktemp` when the Julia process exits,
unless `cleanup` is explicitly set to `false`.
"""
mktemp(parent)
"""
mktempdir(parent=tempdir(); prefix=$(repr(temp_prefix)), cleanup=true) -> path
Create a temporary directory in the `parent` directory with a name
constructed from the given `prefix` and a random suffix, and return its path.
Additionally, on some platforms, any trailing `'X'` characters in `prefix` may be replaced
with random characters.
If `parent` does not exist, throw an error. The `cleanup` option controls whether
the temporary directory is automatically deleted when the process exits.
!!! compat "Julia 1.2"
The `prefix` keyword argument was added in Julia 1.2.
!!! compat "Julia 1.3"
The `cleanup` keyword argument was added in Julia 1.3. Relatedly, starting from 1.3,
Julia will remove the temporary paths created by `mktempdir` when the Julia process
exits, unless `cleanup` is explicitly set to `false`.
See also: [`mktemp`](@ref), [`mkdir`](@ref).
"""
function mktempdir(parent::AbstractString=tempdir();
prefix::AbstractString=temp_prefix, cleanup::Bool=true)
if isempty(parent) || occursin(path_separator_re, parent[end:end])
# append a path_separator only if parent didn't already have one
tpath = "$(parent)$(prefix)XXXXXX"
else
tpath = "$(parent)$(path_separator)$(prefix)XXXXXX"
end
req = Libc.malloc(_sizeof_uv_fs)
try
ret = ccall(:uv_fs_mkdtemp, Cint,
(Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Ptr{Cvoid}),
C_NULL, req, tpath, C_NULL)
if ret < 0
uv_fs_req_cleanup(req)
uv_error("mktempdir($(repr(parent)))", ret)
end
path = unsafe_string(ccall(:jl_uv_fs_t_path, Cstring, (Ptr{Cvoid},), req))
uv_fs_req_cleanup(req)
cleanup && temp_cleanup_later(path)
return path
finally
Libc.free(req)
end
end
"""
mktemp(f::Function, parent=tempdir())
Apply the function `f` to the result of [`mktemp(parent)`](@ref) and remove the
temporary file upon completion.
See also: [`mktempdir`](@ref).
"""
function mktemp(fn::Function, parent::AbstractString=tempdir())
(tmp_path, tmp_io) = mktemp(parent)
try
fn(tmp_path, tmp_io)
finally
temp_cleanup_forget(tmp_path)
try
close(tmp_io)
ispath(tmp_path) && rm(tmp_path)
catch ex
@error "mktemp cleanup" _group=:file exception=(ex, catch_backtrace())
# might be possible to remove later
temp_cleanup_later(tmp_path, asap=true)
end
end
end
"""
mktempdir(f::Function, parent=tempdir(); prefix=$(repr(temp_prefix)))
Apply the function `f` to the result of [`mktempdir(parent; prefix)`](@ref) and remove the
temporary directory and all of its contents upon completion.
See also: [`mktemp`](@ref), [`mkdir`](@ref).
!!! compat "Julia 1.2"
The `prefix` keyword argument was added in Julia 1.2.
"""
function mktempdir(fn::Function, parent::AbstractString=tempdir();
prefix::AbstractString=temp_prefix)
tmpdir = mktempdir(parent; prefix=prefix)
try
fn(tmpdir)
finally
temp_cleanup_forget(tmpdir)
try
if ispath(tmpdir)
prepare_for_deletion(tmpdir)
rm(tmpdir, recursive=true)
end
catch ex
@error "mktempdir cleanup" _group=:file exception=(ex, catch_backtrace())
# might be possible to remove later
temp_cleanup_later(tmpdir, asap=true)
end
end
end
struct uv_dirent_t
name::Ptr{UInt8}
typ::Cint
end
"""
readdir(dir::AbstractString=pwd();
join::Bool = false,
sort::Bool = true,
) -> Vector{String}
Return the names in the directory `dir` or the current working directory if not
given. When `join` is false, `readdir` returns just the names in the directory
as is; when `join` is true, it returns `joinpath(dir, name)` for each `name` so
that the returned strings are full paths. If you want to get absolute paths
back, call `readdir` with an absolute directory path and `join` set to true.
By default, `readdir` sorts the list of names it returns. If you want to skip
sorting the names and get them in the order that the file system lists them,
you can use `readdir(dir, sort=false)` to opt out of sorting.
See also: [`walkdir`](@ref).
!!! compat "Julia 1.4"
The `join` and `sort` keyword arguments require at least Julia 1.4.
# Examples
```julia-repl
julia> cd("/home/JuliaUser/dev/julia")
julia> readdir()
30-element Vector{String}:
".appveyor.yml"
".git"
".gitattributes"
⋮
"ui"
"usr"
"usr-staging"
julia> readdir(join=true)
30-element Vector{String}:
"/home/JuliaUser/dev/julia/.appveyor.yml"
"/home/JuliaUser/dev/julia/.git"
"/home/JuliaUser/dev/julia/.gitattributes"
⋮
"/home/JuliaUser/dev/julia/ui"
"/home/JuliaUser/dev/julia/usr"
"/home/JuliaUser/dev/julia/usr-staging"
julia> readdir("base")
145-element Vector{String}:
".gitignore"
"Base.jl"
"Enums.jl"
⋮
"version_git.sh"
"views.jl"
"weakkeydict.jl"
julia> readdir("base", join=true)
145-element Vector{String}:
"base/.gitignore"
"base/Base.jl"
"base/Enums.jl"
⋮
"base/version_git.sh"
"base/views.jl"
"base/weakkeydict.jl"
julia> readdir(abspath("base"), join=true)
145-element Vector{String}:
"/home/JuliaUser/dev/julia/base/.gitignore"
"/home/JuliaUser/dev/julia/base/Base.jl"
"/home/JuliaUser/dev/julia/base/Enums.jl"
⋮
"/home/JuliaUser/dev/julia/base/version_git.sh"
"/home/JuliaUser/dev/julia/base/views.jl"
"/home/JuliaUser/dev/julia/base/weakkeydict.jl"
```
"""
readdir(; join::Bool=false, kwargs...) = readdir(join ? pwd() : "."; join, kwargs...)::Vector{String}
readdir(dir::AbstractString; kwargs...) = _readdir(dir; return_objects=false, kwargs...)::Vector{String}
# this might be better as an Enum but they're not available here
# UV_DIRENT_T