Absolute path of the project root directory in Julia
Asked Answered
B

5

6

The project root directory of a file located in PROJECT_ROOT/lib/code.jl can be accessed with this code:

root = dirname(dirname(@__FILE__))

Using dirname() twice seems pretty ugly. Is there a better way to do this? With Ruby, I would use this code:

root = File.expand_path('../', File.dirname(__FILE__))
Bryonbryony answered 17/2, 2016 at 20:1 Comment(0)
T
5

Thanks for making me find out about:

"/"*relpath((@__FILE__)*"/../..","/")

According to ?relpath, it gives a path from the location of the second argument in the file-system, to the first argument. Is this better than the double dirname solution?

A variant of the same niceness is:

normpath(joinpath(@__FILE__,"..",".."))

Closest to Ruby equivalent might be:

realpath(dirname(@__FILE__)*"/..")
Trochilus answered 17/2, 2016 at 22:58 Comment(4)
To make it OS agnostic, it would have to be Base.path_separator*relpath(@__FILE__*"/../..",Base.path_separator). Ugh.Trochilus
The normpath version seems to me the stablest/cleanest.Trochilus
I can't get the first solution to work "/"*relpath(@__FILE__*"/../..","/"). The other solutions work perfectly :)Bryonbryony
Weird, seems like a parsing problem. Surrounding the @__FILE__ by parenthesis solves it. relpath((@__FILE__)*"/../..","/"))Trochilus
C
3

I like to use

module Foo

const PROJECT_ROOT = pkgdir(Foo)

end # module

where the definition of PROJECT_ROOT can also be replaced by

const PROJECT_ROOT = dirname(dirname(pathof(Foo)))

Or, you could use

const PROJECT_ROOT = pkdir(@__MODULE__)
Constitutionally answered 24/12, 2020 at 16:52 Comment(0)
A
0
Base.active_project()
# c:\path\to\Project.toml

will give you the Project.toml path of your current active project.

To activate the project in your current directory you can run

pkg> activate .

in the Julia package manager

Alpers answered 1/9, 2023 at 2:31 Comment(0)
C
0

I have created a Julia package for this task exactly: https://github.com/jolars/ProjectRoot.jl

To create a file path relative to the project root, you just need to call

using ProjectRoot

@projectroot("plots", "some_figure.png")

to for instance retrieve a path to a figure in plots/some_figure.png

Corwun answered 23/1, 2024 at 9:54 Comment(0)
I
-1

I just use

const PROJECT_ROOT = @__DIR__

from inside my _init.jl file, which resides in the project root directory (next to the src directory) and gives you a canonical path.

I get my _init.jl files automatically executed when opening a Julia session from inside that directories by having

isfile("_init.jl") && include(joinpath(pwd(), "_init.jl"))

in my ~/.julia/config/startup.jl file. If you started Julia elsewhere, you have to include("_init.jl") it (or respective relative path) manually.

Illusage answered 5/10, 2018 at 13:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.