How to use Pkg.dependencies() instead of Pkg.installed()

Since my last post, I’ve made a few more improvements to the code

input_prompt() = splitpath(Base.active_project())[end-1] * " > "

atreplinit() do repl
    repl.options.iocontext[:compact] = false # Display all Digits
    #colorscheme!("GitHubDarkDimmed") # Optional
    OhMyREPL.input_prompt!(input_prompt, :magenta)
end

if !isfile("Project.toml")
    # Make sure all needed Pkg's are ready to go in standard Environment. Don't touch it in a Package
    neededPackages = [:Revise, :OhMyREPL, :BenchmarkTools, :IJulia, :Documenter] 
    using Pkg;
    for neededPackage in neededPackages
        (String(neededPackage) in keys(Pkg.project().dependencies)) || Pkg.add(String(neededPackage))
        @eval using $neededPackage
    end
end

using OhMyREPL

I just want to add an alternative approach. It bases itself on the function Base.identify_package, which can be used to get the UUID of a package based on its name:

julia> using Pkg

julia> haskey(Pkg.dependencies(), Base.identify_package("Revise").uuid)
true

There are two caveats. The first is that the docstring of Pkg.dependencies states that “This feature is considered experimental.”, so I am not 100% sure that this is what things will look like forever. But given the stability of Pkg, I am certain that this will work for a long time.

The second is that if the package does not exist, Base.identify_package returns nothing, meaning that when we try to get the field uuid, we get an error:

julia> haskey(Pkg.dependencies(), Base.identify_package("NotAPackage").uuid)
ERROR: type Nothing has no field uuid
Stacktrace:
 [1] getproperty(x::Nothing, f::Symbol)
   @ Base ./Base.jl:37
 [2] top-level scope
   @ REPL[10]:1

A complete solution would therefore require the rather verbose

julia> haskey(Pkg.dependencies(), Base.identify_package("NotAPackage")===nothing ? nothing : Base.identify_package("NotAPackage").uuid)
false

So I guess something like haskey(Pkg.project().dependencies, "Revise"), posted previously, is actually more robust and shorter.

1 Like