Skip to content

Commit

Permalink
Fix shell cd error when working dir has been deleted (#41244)
Browse files Browse the repository at this point in the history
root cause:
if current dir has been deleted, then pwd() will throw an IOError:
pwd(): no such file or directory (ENOENT)

---------

Co-authored-by: Ian Butterworth <[email protected]>
  • Loading branch information
norci and IanButterworth authored Sep 17, 2024
1 parent 61c044c commit 48ddd2d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
13 changes: 9 additions & 4 deletions base/client.jl
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function repl_cmd(cmd, out)
if isempty(cmd.exec)
throw(ArgumentError("no cmd to execute"))
elseif cmd.exec[1] == "cd"
new_oldpwd = pwd()
if length(cmd.exec) > 2
throw(ArgumentError("cd method only takes one argument"))
elseif length(cmd.exec) == 2
Expand All @@ -52,11 +51,17 @@ function repl_cmd(cmd, out)
end
dir = ENV["OLDPWD"]
end
cd(dir)
else
cd()
dir = homedir()
end
ENV["OLDPWD"] = new_oldpwd
try
ENV["OLDPWD"] = pwd()
catch ex
ex isa IOError || rethrow()
# if current dir has been deleted, then pwd() will throw an IOError: pwd(): no such file or directory (ENOENT)
delete!(ENV, "OLDPWD")
end
cd(dir)
println(out, pwd())
else
@static if !Sys.iswindows()
Expand Down
20 changes: 20 additions & 0 deletions test/file.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1908,6 +1908,26 @@ end
end
end

@testset "pwd tests" begin
mktempdir() do dir
cd(dir) do
withenv("OLDPWD" => nothing) do
io = IOBuffer()
Base.repl_cmd(@cmd("cd"), io)
Base.repl_cmd(@cmd("cd -"), io)
@test realpath(pwd()) == realpath(dir)
if !Sys.iswindows()
# Delete the working directory and check we can cd out of it
# Cannot delete the working directory on Windows
rm(dir)
@test_throws Base._UVError("pwd()", Base.UV_ENOENT) pwd()
Base.repl_cmd(@cmd("cd \\~"), io)
end
end
end
end
end

@testset "readdir tests" begin
(a, b) = sort(a) == sort(b)
mktempdir() do dir
Expand Down

0 comments on commit 48ddd2d

Please sign in to comment.