Finding A Function With ast-grep
ast-grep is a brilliant tool for code search and transformation that I’ve written about in a previous byte. Finding function calls with specific arguments is an area where ast-grep shines and makes it much easier to understand usage of a specific function invocation throughout your codebase.
A recent example from work was finding all instances where we were calling
the function showToast where it contained one or more actions. Since
the actions property could be at the start, middle, or end of the options
object, we might think to write a pattern like this:
sg run -p 'showToast({ $$$, actions: [$$$], $$$ })'However, the default strictness setting of ast-grep does not match all
cases since it is expecting a property following the actions property and
will not match calls like this:
showToast({ message: '...', actions: [] }). To resolve this issue we can
set the strictness to ast which will correctly match all the variations
of this function call:
sg run --strictness ast -p 'showToast({ $$$, actions: [$$$], $$$ })'