Skip to content

Commit 90a3726

Browse files
fredrikekreKristofferC
authored andcommitted
Fix (add|set)env to keep currently set dir for the command, fixes #42131. (#43276)
(cherry picked from commit f53de73)
1 parent 68f0b35 commit 90a3726

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

base/cmd.jl

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ byteenv(env::Union{AbstractVector{Pair{T,V}}, Tuple{Vararg{Pair{T,V}}}}) where {
230230
String[cstr(k*"="*string(v)) for (k,v) in env]
231231

232232
"""
233-
setenv(command::Cmd, env; dir="")
233+
setenv(command::Cmd, env; dir)
234234
235235
Set environment variables to use when running the given `command`. `env` is either a
236236
dictionary mapping strings to strings, an array of strings of the form `"var=val"`, or
@@ -239,11 +239,13 @@ existing environment, create `env` through `copy(ENV)` and then setting `env["va
239239
as desired, or use `addenv`.
240240
241241
The `dir` keyword argument can be used to specify a working directory for the command.
242+
`dir` defaults to the currently set `dir` for `command` (which is the current working
243+
directory if not specified already).
242244
"""
243-
setenv(cmd::Cmd, env; dir="") = Cmd(cmd; env=byteenv(env), dir=dir)
244-
setenv(cmd::Cmd, env::Pair{<:AbstractString}...; dir="") =
245+
setenv(cmd::Cmd, env; dir=cmd.dir) = Cmd(cmd; env=byteenv(env), dir=dir)
246+
setenv(cmd::Cmd, env::Pair{<:AbstractString}...; dir=cmd.dir) =
245247
setenv(cmd, env; dir=dir)
246-
setenv(cmd::Cmd; dir="") = Cmd(cmd; dir=dir)
248+
setenv(cmd::Cmd; dir=cmd.dir) = Cmd(cmd; dir=dir)
247249

248250
"""
249251
addenv(command::Cmd, env...; inherit::Bool = true)

test/spawn.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,25 @@ end
735735
end
736736
end
737737

738+
@testset "setenv with dir (with tests for #42131)" begin
739+
dir1 = joinpath(pwd(), "dir1")
740+
dir2 = joinpath(pwd(), "dir2")
741+
cmd = Cmd(`julia`; dir=dir1)
742+
@test cmd.dir == dir1
743+
@test Cmd(cmd).dir == dir1
744+
@test Cmd(cmd; dir=dir2).dir == dir2
745+
@test Cmd(cmd; dir="").dir == ""
746+
@test setenv(cmd).dir == dir1
747+
@test setenv(cmd; dir=dir2).dir == dir2
748+
@test setenv(cmd; dir="").dir == ""
749+
@test setenv(cmd, "FOO"=>"foo").dir == dir1
750+
@test setenv(cmd, "FOO"=>"foo"; dir=dir2).dir == dir2
751+
@test setenv(cmd, "FOO"=>"foo"; dir="").dir == ""
752+
@test setenv(cmd, Dict("FOO"=>"foo")).dir == dir1
753+
@test setenv(cmd, Dict("FOO"=>"foo"); dir=dir2).dir == dir2
754+
@test setenv(cmd, Dict("FOO"=>"foo"); dir="").dir == ""
755+
end
756+
738757

739758
# clean up busybox download
740759
if Sys.iswindows()

0 commit comments

Comments
 (0)