Anyone have a regex to de-nest alaises in an Elixir code base?

My team is considering enabling the credo rule https://hexdocs.pm/credo/Credo.Check.Readability.MultiAlias.html that would force you to not nest aliases.

We have a lot of code like:

      alias MyApp.{
        Cat,
        Dog,
        Parrot
      }

And I’m looking for an automated way to do a search and replace into something like:

      alias MyApp.Cat
      alias MyApp.Dog
      alias MyApp.Parrot

I suspect this might be doable with regex but I have very little skills for that. Any chance someone here has that sitting around in a notebook somewhere or other suggestion?

PS: As to why we want to do this, it is to improve the grep-ability of the source. We want to have confidence when we search for MyApp.Dog we find those module references.

That kind of transformation is safer to do on AST (versus regexing code). The formatter provides some inspiration:

In between calls to Code.string_to_quoted_with_comments! and Code.Formatter.to_algebra, you could find alias nodes in the AST and transform them into the desired shape.

OR

You (could use the already-baked version included as a tutorial in the Sourceror docs! :tada:

See also the release announcement thread:

6 Likes

What would be wrong with using the aforementioned regex (assuming you have one) with grep leaving the code as-is for better readability?

grep -Pz '(?s)alias\s+(MyApp\.Dog|MyApp.{.*?,\s*Dog.*?})' $FILES

Just make the shell function to wrap this grep call, or even create an escript using Elixir regexes (the regex itself would be simpler, I believe.)

1 Like