Parse Elixir Module AST to replace functions and replace the original source file?

I am looking for a way to read in a elixir module and replace functions with code you want to run. Anyone know of any examples of code on how to parse a module’s AST to match against a function and replace it?

See example here:

path = “lib/test_module.ex”
  |> Code.string_to_quoted()
  |> Insert.print()

path = “some_path”
  |> get_file
  |> get_ast
  |> replace_function_that_matches_name
  |> ast_to_string
  |> string_to_file
  |> format_file
1 Like

TLDR: you can do this, but you can’t preserve code formatting, comments and other stuff which is not part of AST. I’ve been investigating a similar case here: Mix deps.add functionality

Thanks, formatting I don’t care about but want to support comments. Not having that sucks.

Checked out your thread and actually was looking to do the same thing. Maybe we can suggest adding comments to the AST.

I don’t believe that’s good idea. Even if we would still not have formatting saved. I think that looking at formatter mix task may give more ideas, because it’s actually do not remove comments when changing file.