zorn
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://github.com/elixir-lang/elixir/pull/11246
https://hexdocs.pm/mix/master/Mix.Tasks.Format.html#module-plugins
Most Liked
dorgan
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.
axelson
Ah, that extension looks helpful! Although one downside is that (if I understand it correctly) is that you need to run it on each list of aliases you have.
There’s an elixir project that was started after this thread (and is based on Sourceror) that makes this even easier:
https://github.com/hrzndhrn/recode
Recode has a Task.AliasOrder that if configured will auto-sort your aliases when you run mix recode ![]()
Fl4m3Ph03n1x
Although auto-sorting aliases on save is still not a thing the formatter has (at the time of this writing), I have found this VSCode extension to do the job just fine:
Highly recommend it.
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










