Can I configure the Elixir formatter to auto-sort my alias calls?

I often will get reminded by credo to sort my alias calls like below.

Is there a way I could configure the Elixir formatter (that is kicked by VS Code) to auto-sort these for me?

┃ [R] ↘ The alias `RetroTaxi.JoinBoard` is not alphabetically ordered among its group.
┃       lib/retro_taxi/board_creation.ex:12:9 #(RetroTaxi.BoardCreation)

It looks like formatter Plugins are a recent/upcoming (1.13) thing. Anyone ever try to do this?

https://hexdocs.pm/mix/master/Mix.Tasks.Format.html#module-plugins

3 Likes

I am also interested in the answer of this question.
Are there some examples how to do something like this?
Chrichton

For now, formatter plugins only support sigils and custom file extensions. For what you want, you’d need to find a way to run code before or after the formatter, with Code.string_to_quoted_with_comments and Code.quoted_to_algebra + Inspect.Algebra.format. The challenge is in syncing the changes you did to the AST with the comments.

I created Sourceror specifically for this. Here is an example to sort dependencies in mix.exs:

source
|> Sourceror.parse_string!()
|> Macro.postwalk(fn
  {:defp, meta, [{:deps, _, _} = fun, body]} ->
    [{{_, _, [:do]}, block_ast}] = body
    {:__block__, block_meta, [deps]} = block_ast

    deps =
      Enum.sort_by(deps, fn {:__block__, _, [{{_, _, [name]}, _}]} ->
        Atom.to_string(name)
      end)

    {:defp, meta, [fun, [do: {:__block__, block_meta, [deps]}]]}

  quoted ->
    quoted
end)
|> Sourceror.to_string()
|> IO.puts()

You can do something similar to sort aliases.

Note: There is currently a bug affecting the ordering of comments under certain circumstances that I need to fix.

7 Likes