trisolaran
Is there an elegant way to ensure that a Mix.Task is compiled only in a specific environment?
Hello everyone,
I wrote a Mix.Task that’s supposed to be run in a specific environment (:test) and nowhere else.
The task uses dependencies that are present only in the test environment.
I can set preferred_cli_env to make sure that the task automatically runs in the test environment when I invoke it, so that’s good.
However, when I compile my app in another environment (e.g. :dev) mix will try to compile that task, resulting in errors or at the very least compiler’s warnings due to the missing dependencies.
Is there an elegant way to solve this problem? I can think of a few options:
- Make the test-only dependencies used by the task available in all environments
- Enclose the code in my task in a huge
if Mix.env() == :test do ... endclause - Split tasks into directories: (i.e.
task/test,task/devetc.) and play around with theelixirc_pathsoption to disable compilation in specific environments
The last option is the only one appealing to me, but I think elixirc_paths only accepts a list of directories, and since lib is already in there, the tasks would have be moved out of lib. I wish there was a way to selectively exclude a directory, or even better a single file, but I believe that’s not possible.
Any ideas? Thank you very much in advance! ![]()
Marked As Solved
dimitarvp
You can always wrap the entire module code? ![]()
if Mix.env() == :dev do
defmodule XYZ do
# ...
end
end
Also Liked
josevalim
This should work. Elixir generally does not care which files define a module.
LostKobrakai
Option 4: Make the mix task not fail in other envs by just printing an error message instead of doing what it normally does.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









