From d965703d705351abad284d9ea8ccfd44f753d922 Mon Sep 17 00:00:00 2001 From: Fredrik Ekre Date: Wed, 1 Dec 2021 00:28:12 +0100 Subject: [PATCH] Fix (add|set)env to keep currently set dir for the command, fixes #42131. --- base/cmd.jl | 10 ++++++---- test/spawn.jl | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/base/cmd.jl b/base/cmd.jl index 9c9809454ad42..dc8fae2ab052f 100644 --- a/base/cmd.jl +++ b/base/cmd.jl @@ -233,7 +233,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 @@ -242,13 +242,15 @@ existing environment, create `env` through `copy(ENV)` and then setting `env["va as desired, or use [`addenv`](@ref). 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). See also [`Cmd`](@ref), [`addenv`](@ref), [`ENV`](@ref), [`pwd`](@ref). """ -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) diff --git a/test/spawn.jl b/test/spawn.jl index c5669709677c2..5007b7ef0f993 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -821,6 +821,29 @@ end cmd = Cmd(`$shcmd -c "echo \$FOO \$BAR"`, env=Dict("FOO" => "foo", "BAR" => "bar")) cmd2 = addenv(cmd, "FOO" => nothing) @test strip(String(read(cmd2))) == "bar" + # addenv keeps the cmd's dir (#42131) + dir = joinpath(pwd(), "dir") + cmd = addenv(setenv(`julia`; dir=dir), Dict()) + @test cmd.dir == dir +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