Running the new Elixir formatter

Thank you for great formatting tool. I’ve found it very helpful.

After generating new umbrella project I started adding .formatter.exs file with the following contents:

[
  inputs: ["mix.exs", "{apps,config}/**/*.{ex,exs}"],
]

But mix format failed to format some files

mix format failed for file: apps/app_web/assets/node_modules/phoenix/priv/templates/phx.gen.schema/schema.ex
** (SyntaxError) apps/app_web/assets/node_modules/phoenix/priv/templates/phx.gen.schema/schema.ex:1: syntax error before: '='
    (elixir) lib/code.ex:442: Code.format_string!/2
    (mix) lib/mix/tasks/format.ex:293: Mix.Tasks.Format.format_file/3
    (elixir) lib/task/supervised.ex:88: Task.Supervised.do_apply/2
    (elixir) lib/task/supervised.ex:38: Task.Supervised.reply/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3

This error is due the file with .ex extension contains some string interpolations, like defmodule <%= inspect schema.module %> do. This fact is not a problem, because entire node_modules dir is in .gitignore, so .formatter.exs inputs must skip formatting this file. I would like to share my solution of this problem, because I think someone else could find it helpful.

Now my basic .formatter.exs file looks like:

inputs = "git ls-files | grep -E \"*\\.exs?$\""
         |> String.to_charlist()
         |> :os.cmd()
         |> to_string()
         |> String.split(~r{(\r\n\|\r|\n)}, trim: true)

[
  inputs: inputs,
]

So it formats elixir files only under the version source root.

2 Likes