CLI tool to get function name from line of source code

Has anyone written a CLI tool/script that when given a file path (to a .ex or .exs) file and a line number, will return the module name and function? i.e.

$ extract_line_number.bash ~/code/my_cool_proj/lib/utils.ex:15
MyCoolProj.Utils.find_by_id/2

This could be probably be built using the Elixir treesitter grammar (are there already any CLI tools that use the grammar in similar ways?). Before I embark on writing such a tool/script I wanted to see if anyone has already written one.

3 Likes

You should be able to use ast-grep for this.

8 Likes

Ah, that’s a good idea. I’ll give that a try when I have a chance. Thanks!

1 Like

I never tried ast-grep for that in particular but anything that uses TreeSitter (like that tool) should be able to do it.

It would have to be in conjunction with a scripting language. Maybe a terser way but I was thinking along these lines:

ast-grep scan --inline-rules '
id: find-def
language: Elixir
rule:
  any: 
    - pattern: def $$$
    - pattern: def $$$()
    - pattern: def $$$($$$)
' --json=compact -- path/to/file.ex

giving you all the (public) function definitions in path/to/file.ex. The json includes their start and end lines.

2 Likes