Skip to content

Commit

Permalink
port over withenv from JuliaLang/julia#10914
Browse files Browse the repository at this point in the history
  • Loading branch information
jrevels committed Jan 26, 2016
1 parent 39871be commit 3a4013b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,17 @@ function rewrite_split(ex, f)
end
end

# rewrites all subexpressions of the form `a => b` to `(a, b)`
function rewrite_pairs_to_tuples!(expr::Expr)
if expr.head == :(=>)
expr.head = :tuple
end
for subexpr in expr.args
isa(subexpr, Expr) && rewrite_pairs_to_tuples!(subexpr)
end
return expr
end

if VERSION < v"0.4.0-dev+707"
macro inline(ex)
esc(ex)
Expand Down Expand Up @@ -395,6 +406,8 @@ function _compat(ex::Expr)
else
ex = Expr(:call, :Array, f.args[2], ex.args[2:end]...)
end
elseif VERSION < v"0.4.0-dev+4389" && f == :withenv
rewrite_pairs_to_tuples!(ex)
end
elseif ex.head == :curly
f = ex.args[1]
Expand Down Expand Up @@ -690,6 +703,26 @@ if VERSION < v"0.4.0-dev+3837"
const OutOfMemoryError = MemoryError
end


if VERSION < v"0.4.0-dev+4389"
export withenv
# temporarily set and then restore an environment value
function withenv(f::Function, keyvals...)
old = Dict{typeof(first(first(keyvals))),Any}()
for (key,val) in keyvals
old[key] = get(ENV, key, nothing)
val !== nothing ? (ENV[key]=val) : Base._unsetenv(key)
end
try f()
finally
for (key,val) in old
val !== nothing ? (ENV[key]=val) : Base._unsetenv(key)
end
end
end
withenv(f::Function) = f() # handle empty keyvals case; see #10853
end

import Base: remotecall, remotecall_fetch, remotecall_wait, remote_do
if VERSION < v"0.5.0-dev+431"
for f in (:remotecall, :remotecall_fetch, :remotecall_wait, :remote_do)
Expand Down
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -551,3 +551,9 @@ Base.remote_do(() -> true, 1) # Doesn't return anything so cannot be `@test`ed b

# JuliaLang/julia#14338
@test supertype(Int) == Signed

# withenv
@test "1234" == @compat withenv(() -> ENV["_TESTVAR"], "_TESTVAR" => 1234)
@test "1234" == @compat withenv("_TESTVAR" => 1234) do
return ENV["_TESTVAR"]
end

0 comments on commit 3a4013b

Please sign in to comment.