When developing a package, how do you access files in the package directory structure?

I am working on a package that’s supposed to download and use files in the data directory inside the package directory structure.

Originally, I was using ./data as a path of the data directory. That worked fine for me as a developer, but when I tried to install the package as a user, the package stopped working as ./data was relative to the user’s project, not the install directory of my package.

So my first question is: what’s the correct way to get path relative to the installed package root directory? And a second question is how can I test that the package works correctly for end users before releasing a new version?

I saw a post recommending pathof(@__MODULE__), but I am not sure that is the correct way since it seems to return an incorrect path /Absolute/path/to/project/MyPackage/src/MyPackage.jl when I am developing the package.

Use a file-relative path. You can use joindir(@__DIR__, "..", "data", "somefile") from a file in your package/src directory to access a file somefile in your package/data directory.

3 Likes

You also can use pathof(MyModule) where MyModule is the module of the your package (you need to import it first). It will returns the path to the Project.toml. You can use dirname(dirname(pathof(MyModule))) to get the root folder path.

4 Likes

Oh, I now realize that it actually returns path to the file that defines the module. Thanks a lot for quick responses, I ended up going with pathof(MyModule).

1 Like