From 66791313f1f92fec070f5356caabccd970f451f5 Mon Sep 17 00:00:00 2001 From: Elliot Saba Date: Thu, 21 May 2020 17:04:12 -0700 Subject: [PATCH] Add `Pkg.API.get_uuid()` and `Pkg.API.get_version()` These functions provide a nice interface for determining the currently-running package's UUID and VersionNumber, identified by loaded `Module`. We explicitly do not include a lookup by name, in expectation of potential future naming clashes due to having multiple packages with the same name but different UUIDs. --- src/API.jl | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/API.jl b/src/API.jl index 5cbbf36b51..c1619b6dc8 100644 --- a/src/API.jl +++ b/src/API.jl @@ -1047,4 +1047,31 @@ Package(name::AbstractString) = PackageSpec(name) Package(name::AbstractString, uuid::UUID) = PackageSpec(name, uuid) Package(name::AbstractString, uuid::UUID, version::VersionTypes) = PackageSpec(name, uuid, version) + +""" + get_uuid(m::Module) + +Given a `Module`, find the `UUID` of the parent package to that `Module`. If none can be +found (e.g. `Main`, `Base`, anonymous modules, etc...) returns `nothing`. +""" +function get_uuid(m::Module) + return Base.PkgId(m).uuid +end + +""" + get_version(pkg) + +Given a `UUID` identifying a package, returns the version of that package within the +current project. If the package cannot be found by the given UUID, throws an +`ArgumentError`. +""" +function get_version(uuid::UUID) + ctx = Pkg.Types.Context() + matching_pkgs = filter(((u, e),) -> u == uuid, ctx.env.manifest) + if isempty(matching_pkgs) + throw(ArgumentError("Unable to find given UUID in environment")) + end + return first(matching_pkgs)[2].version +end + end # module