Skip to content

Commit

Permalink
Fix (add|set)env to keep currently set dir for the command, fixes #42131
Browse files Browse the repository at this point in the history
. (#43276)

(cherry picked from commit f53de73)
  • Loading branch information
fredrikekre authored and KristofferC committed Mar 15, 2022
1 parent 4867656 commit 1c3286e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
10 changes: 6 additions & 4 deletions base/cmd.jl
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ byteenv(env::Union{AbstractVector{Pair{T,V}}, Tuple{Vararg{Pair{T,V}}}}) where {
String[cstr(k*"="*string(v)) for (k,v) in env]

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

"""
addenv(command::Cmd, env...; inherit::Bool = true)
Expand Down
19 changes: 19 additions & 0 deletions test/spawn.jl
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,25 @@ end
end
end

@testset "setenv with dir (with tests for #42131)" begin
dir1 = joinpath(pwd(), "dir1")
dir2 = joinpath(pwd(), "dir2")
cmd = Cmd(`julia`; dir=dir1)
@test cmd.dir == dir1
@test Cmd(cmd).dir == dir1
@test Cmd(cmd; dir=dir2).dir == dir2
@test Cmd(cmd; dir="").dir == ""
@test setenv(cmd).dir == dir1
@test setenv(cmd; dir=dir2).dir == dir2
@test setenv(cmd; dir="").dir == ""
@test setenv(cmd, "FOO"=>"foo").dir == dir1
@test setenv(cmd, "FOO"=>"foo"; dir=dir2).dir == dir2
@test setenv(cmd, "FOO"=>"foo"; dir="").dir == ""
@test setenv(cmd, Dict("FOO"=>"foo")).dir == dir1
@test setenv(cmd, Dict("FOO"=>"foo"); dir=dir2).dir == dir2
@test setenv(cmd, Dict("FOO"=>"foo"); dir="").dir == ""
end


# clean up busybox download
if Sys.iswindows()
Expand Down

0 comments on commit 1c3286e

Please sign in to comment.