Is there a simple way to map/traverse ast in Elixir project files?

Hey, I would like to ask if there is a simple way to map/traverse Elixir project (*.ex and *.exs) files …

defmodule Example do
  def get_app_project_files(app) do
    # …

  def traverse_ast(file_path) do
    # …

  def do_traverse_ast(_file_path, :atom), do: :new_atom
  def do_traverse_ast(_file_path, ast), do: ast

Enum.each(Example.get_app_project_files(:my_app), &traverse_ast/1)

Then using file_path send to GenServer I store changed file paths and at end I could run Elixir formatter on them …

I have lots of ideas for it. First things that comes to my mind are:

  1. add dependencies with simple command
  2. rename project
  3. Phoenix 1.2 -> 1.3 migration script :slight_smile:

and much more …

Why do you need a genserver?

Why would you want to do this?

While mutating the AST is much better than doing purely textual replacements, bear in mind that you might get some errors even with AST manipulation. Module names are just atoms, and changing all atoms with a certain name into atoms of another name can go wrong…

Why not?
mix my_lib.add_dep dep_name --latest :slight_smile:

Working with AST is much simpler in such case. Some people already asked about it on forum. Last time I changed also name of one project with sed commands.

I have just idea for some helpers which developers may find useful and AST manipulation looks much easier than plain replace.

I can do such things manually of course, but It could save me and others some time.

1 Like