From 1c3286e95cf2d8b513b4c24e0ef2e2241e72affb Mon Sep 17 00:00:00 2001 From: Fredrik Ekre Date: Wed, 1 Dec 2021 03:52:46 +0100 Subject: [PATCH] Fix (add|set)env to keep currently set dir for the command, fixes #42131. (#43276) (cherry picked from commit f53de735d8524304e0e4eb973d82432189135c83) --- base/cmd.jl | 10 ++++++---- test/spawn.jl | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/base/cmd.jl b/base/cmd.jl index 809bc0f3c0a57..4fc02e257e383 100644 --- a/base/cmd.jl +++ b/base/cmd.jl @@ -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 @@ -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) diff --git a/test/spawn.jl b/test/spawn.jl index 4f826b05df93d..17b616e889c26 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -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()