2

How to log the relative file location to its project root?

"my-project" is the root directory of the Phoenix Framework project. Inside users/me/apps/my-project/my-file.txt, if I do :

IO.puts __ENV__.file

The console outputs the absolute path: users/me/apps/my-project/my-file.txt.

How to output the relative path, e.g. my-project/my-file.txt ?

1 Answer 1

3

You can fetch the root directory using File.cwd!() and then do a leading trim of __ENV__.file with it:

defmodule A do
  def a do
    __ENV__.file |> String.trim_leading(File.cwd!)
  end
end

Sample output:

iex(1)> A.a
"/lib/a.ex"
Sign up to request clarification or add additional context in comments.

2 Comments

is File.cwd! always the "project" directory ( where the app was compiled ), or is it the directory where the compiled app is running ?
File.cwd! at run time will point to the directory you're running mix from. If you want it to always point to its own project's root (which I think you do), you can call the function at compile time: @cwd File.cwd!() and then use @cwd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.