diff --git a/NEWS.md b/NEWS.md index 3bc140e77843c..ac9e84c88b934 100644 --- a/NEWS.md +++ b/NEWS.md @@ -67,6 +67,8 @@ New library functions * `Iterators.flatmap` was added ([#44792]). * New helper `Splat(f)` which acts like `x -> f(x...)`, with pretty printing for inspecting which function `f` was originally wrapped. ([#42717]) +* New `pkgversion(m::Module)` function to get the version of the package that loaded + a given module, similar to `pkgdir(m::Module)`. ([#45607]) Library changes --------------- diff --git a/base/exports.jl b/base/exports.jl index 6c1cdcc8b7d77..304d48d24bdcd 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -790,6 +790,7 @@ export parentmodule, pathof, pkgdir, + pkgversion, names, which, @isdefined, diff --git a/base/loading.jl b/base/loading.jl index f2cf385e33643..88ba1050d2b02 100644 --- a/base/loading.jl +++ b/base/loading.jl @@ -437,6 +437,26 @@ function pkgdir(m::Module, paths::String...) return joinpath(dirname(dirname(path)), paths...) end +""" + pkgversion(m::Module) + +Return the version of the package that imported module `m`, +or `nothing` if `m` was not imported from a package, or imported +from a package without a version field set. + +The version is read from the package's Project.toml during package +load. + +!!! compat "Julia 1.9" + This function was introduced in Julia 1.9. +""" +function pkgversion(m::Module) + rootmodule = moduleroot(m) + pkg = PkgId(rootmodule) + pkgorigin = get(pkgorigins, pkg, nothing) + return pkgorigin === nothing ? nothing : pkgorigin.version +end + ## generic project & manifest API ## const project_names = ("JuliaProject.toml", "Project.toml") diff --git a/doc/src/base/base.md b/doc/src/base/base.md index 65334e7c4b677..38d9d788eee35 100644 --- a/doc/src/base/base.md +++ b/doc/src/base/base.md @@ -418,6 +418,7 @@ Base.nameof(::Module) Base.parentmodule Base.pathof(::Module) Base.pkgdir(::Module) +Base.pkgversion(::Module) Base.moduleroot __module__ __source__ diff --git a/test/loading.jl b/test/loading.jl index 39e4790eee9d3..dd9aa66da196f 100644 --- a/test/loading.jl +++ b/test/loading.jl @@ -359,6 +359,13 @@ module NotPkgModule; end @test pkgdir(NotPkgModule, "src") === nothing end + @testset "pkgversion" begin + @test pkgversion(Foo) == v"1.2.3" + @test pkgversion(Foo.SubFoo1) == v"1.2.3" + @test pkgversion(Foo.SubFoo2) == v"1.2.3" + @test pkgversion(NotPkgModule) === nothing + end + end ## systematic generation of test environments ## diff --git a/test/project/deps/Foo1/Project.toml b/test/project/deps/Foo1/Project.toml new file mode 100644 index 0000000000000..b15bdfc656a64 --- /dev/null +++ b/test/project/deps/Foo1/Project.toml @@ -0,0 +1,3 @@ +name = "Foo" +uuid = "1a6589dc-c33c-4d54-9a54-f7fc4b3ff616" +version = "1.2.3"