Pkg API for getting UUID of another package

How can I look up the UUID of a package by name in the current project using the Pkg API?

julia> import Pkg; Pkg.status()
    Status `~/.julia/environments/v1.1/Project.toml`
  [6e4b80f9] BenchmarkTools v0.4.1
  [31c24e10] Distributions v0.16.4

julia> Pkg.gimme_UUID("Distributions") # hypothetical function
"31c24e10-a181-5473-b8eb-7969acd0382f"
julia> using Pkg

julia> Pkg.METADATA_compatible_uuid("Distributions")
UUID("31c24e10-a181-5473-b8eb-7969acd0382f")

(note that I think this is just temporary until METADATA is a thing of the past)

Evizeros version works as long as we have METADATA as the truth of the General registry. Here is a more “correct” version:

julia> function find_uuid(name)
           packages = merge!((Pkg.TOML.parsefile(joinpath(x, "Registry.toml"))["packages"] for x in Pkg.Types.registries())...)
           out = Pair{String,String}[]
           for (k, v) in packages
               if get(v, "name", nothing) == name
                   push!(out, name => k)
               end
           end
           return out
       end
find_uuid (generic function with 1 method)

julia> find_uuid("JSON")
1-element Array{Pair{String,String},1}:
 "JSON" => "682c06a0-de6a-54ab-a142-c8b1cf79cde6"

See also A show command to display package information · Issue #381 · JuliaLang/Pkg.jl · GitHub for the long term solution.

2 Likes

Thank you and @evizero for the solutions. Sorry I wasn’t specific enough: I want to UUID of a local, unregistered package. Eg just after running pkg> generate. I guess the above issue will be the solution.

If you have it installed as a deps in your project:

julia> function find_uuid_in_project(name)
           get(Pkg.Types.EnvCache().project["deps"], name, nothing)
       end
find_uuid_in_project (generic function with 1 method)

julia> find_uuid_in_project("JSON")
"682c06a0-de6a-54ab-a142-c8b1cf79cde6"
1 Like

@fredrikekre
What would be the actual approach. Your function does not work for me :frowning:

Here is my proposal:

function find_uuid_in_current_environment(package::AbstractString="Revise")
    UUID = ""
    for (_key, _value) in TOML.tryparsefile(Base.active_project())
        # global UUID # not needed inside a function
        if isa(_value, Dict)
            # println("_value: ", _value)
            println("_key: ", _key)
            if cmp(_key, "deps") == 0
                if haskey(_value, package)
                    UUID = _value[package]
                end
            end
        end
    end
    return package, UUID
end

or much more compact:

TOML.parsefile(Base.active_project())["deps"]["Revise"]

(found in old version of package Tulip.jl)
or as function:

show_uuid(package_name::AbstractString) = TOML.parsefile(Base.active_project())["deps"][package_name]