Skip to content

Commit

Permalink
Add set_preferences!(name::String, ...) method which pulls UUID fro…
Browse files Browse the repository at this point in the history
…m `Project.toml`

This makes it much more convenient to set preferences as previously you
either had to know (1) the `UUID` or (2) have the `Module` handy, and
sometimes you don't want to load an entire package just to set a
preference for it.
  • Loading branch information
staticfloat committed Nov 11, 2023
1 parent 281b5f4 commit 329b15f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Preferences.jl
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,14 @@ end
function set_preferences!(m::Module, prefs::Pair{String,<:Any}...; kwargs...)
return set_preferences!(get_uuid(m), prefs...; kwargs...)
end
function set_preferences!(name::String, prefs::Pair{String,<:Any}...; kwargs...)
# Look up UUID
pkg_and_path = Base.identify_package_env(name)
if pkg_and_path === nothing
throw(ArgumentError("Cannot resolve package '$(name)' in load path; have you added the package as a top-level dependency?"))
end
return set_preferences!(pkg_and_path[1].uuid, prefs...; kwargs...)
end

"""
@set_preferences!(prefs...)
Expand Down
20 changes: 20 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,26 @@ up_path = joinpath(@__DIR__, "UsesPreferences")
end
end

@testset "Loading UUID from Project.toml" begin
with_temp_depot() do; mktempdir() do dir
activate(dir) do
push!(Base.LOAD_PATH, dir)
try
# Can't do this unless `UsesPreferences` is added as a dep
@test_throws ArgumentError Preferences.set_preferences!("UsesPreferences", "location" => "exists")

Pkg.develop(;path=up_path)

# After `dev`'ing `up_path`, it works.
Preferences.set_preferences!("UsesPreferences", "location" => "exists")
@test load_preference(up_uuid, "location") == "exists"
finally
pop!(Base.LOAD_PATH)
end
end
end; end
end

# Load UsesPreferences, as we need it loaded to satisfy `set_preferences!()` below,
# otherwise it can't properly map from a UUID to a name when installing into a package
# that doesn't have UsesPreferences added yet.
Expand Down

0 comments on commit 329b15f

Please sign in to comment.