Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding sort=true keyword to readdir() #24675

Closed
wants to merge 8 commits into from
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,9 @@ Library improvements
This supersedes the old behavior of reinterpret on Arrays. As a result, reinterpreting
arrays with different alignment requirements (removed in 0.6) is once again allowed ([#23750]).

* `readdir()` output is now guaranteed to be sorted on any OS. A new `sort` keyword argument can
be used to disable explicit sorting ([#24626]).

Compiler/Runtime improvements
-----------------------------

Expand Down
8 changes: 6 additions & 2 deletions base/file.jl
Original file line number Diff line number Diff line change
Expand Up @@ -401,11 +401,12 @@ struct uv_dirent_t
end

"""
readdir(dir::AbstractString=".") -> Vector{String}
readdir(dir::AbstractString="."; sort::Bool=true) -> Vector{String}

Returns the files and directories in the directory `dir` (or the current working directory if not given).
If `sort=false`, the resulting list won't necessarily be sorted, but performance may improve slightly.
"""
function readdir(path::AbstractString)
function readdir(path::AbstractString; sort::Bool=true)
# Allocate space for uv_fs_t struct
uv_readdir_req = zeros(UInt8, ccall(:jl_sizeof_uv_fs_t, Int32, ()))

Expand All @@ -425,6 +426,9 @@ function readdir(path::AbstractString)
# Clean up the request string
ccall(:jl_uv_fs_req_cleanup, Void, (Ptr{UInt8},), uv_readdir_req)

# sort entries if not requested otherwise
sort && sort!(entries)

return entries
end

Expand Down
13 changes: 13 additions & 0 deletions test/file.jl
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,19 @@ cd(dirwalk) do
end
rm(dirwalk, recursive=true)

###################
# readdir #
###################

mktempdir() do path
cd(path) do
for k in 1:10
touch(randstring())
end
@test issorted(readdir())
end
end

############
# Clean up #
############
Expand Down