Is it possible to get the compiler to exit early, failing the build, if a compile time warning is raised?

会有一股神秘感。 提交于 2019-12-01 15:52:48

Possible to some extent. There is a flag --warnings-as-errors in elixirc command.

☁  hello_elixir [master] ⚡ elixirc
Usage: elixirc [elixir switches] [compiler switches] [.ex files]

  -o               The directory to output compiled files
  --no-docs        Do not attach documentation to compiled modules
  --no-debug-info  Do not attach debug info to compiled modules
  --ignore-module-conflict
  --warnings-as-errors Treat warnings as errors and return non-zero exit code
  --verbose        Print informational messages.

** Options given after -- are passed down to the executed code
** Options can be passed to the erlang runtime using ELIXIR_ERL_OPTIONS
** Options can be passed to the erlang compiler using ERL_COMPILER_OPTIONS

For a module like this, with a warning:

defmodule Useless do
  defp another_userless, do: nil
end

When you compile without the flag:

☁  01_language [master] ⚡ elixirc useless.ex
useless.ex:2: warning: function another_userless/0 is unused
☁  01_language [master] ⚡ echo $?
0

You get the return code as 0.

But when you compile with the flag --warnings-as-errors, it returns an exit code of 1.

☁  01_language [master] ⚡ elixirc --warnings-as-errors useless.ex
useless.ex:1: warning: redefining module Useless
useless.ex:2: warning: function another_userless/0 is unused
☁  01_language [master] ⚡ echo $?
1

You can use this return code in your compile script for break the build process.

In your mix.exs:

def project do
  [...,
   aliases: aliases]
end

defp aliases do
  ["compile": ["compile --warnings-as-errors"]]
end

Then mix compile will pass --warnings-as-errors to the compile.elixir subtask.

This also works for mix test since it runs the compile task implicitly.


If you don't add an alias, you can still run mix compile --warnings-as-errors and it will do what you expect, but mix test --warnings-as-errors will not do what you expect, since the flag does not reach the compile.elixir task.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!