Inferring correct environment based on file being run?

I have a local package (call it Foo) that I have devd. In the src folder I have a file called main.jl that I’d like to run by calling julia src/main.jl. Currently, I have to call julia --project main.jl to use the correct Foo environment (otherwise imports added to Foo won’t work in main.jl). Is there a way to avoid having to specify --project, and instead have julia correctly infer the environment given that the file in question is in a the devd directory?

This becomes more annoying when I’m not currently in the Foo directory. If I’m in the parent directory, I’d have to call julia --project=Foo Foo/src/main.jl, which is quite verbose.

You could put something like this at the beginning of src/main.jl:

using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))

FWIW, I tend to put such “main” scripts directly at the project root (i.e. in the same directory as Project.toml), in order to make it clear which source files define the package (under src), and which source files use the package (for example to turn it into an application, by activate the relevant environment and calling the entry point).

I’m not sure if this is common practice, but this has served me well so far…

You can export JULIA_PROJECT=@. in .bashrc (or equivalent for your system). This will effectively mean --project at every Julia start.

IIUC, this activates the project in the current working directory; not the project where the julia source file resides.

I might have misunderstood, but I’m not sure this is the behavior the OP wanted to achieve…

True, I only read the first part of the question.

Thanks both. Good to know about JULIA_PROJECT, though that isn’t what I was looking for since it sets a fixed path.

I’ll try the Pkg idea in main.jl.