gkz / grasp

JavaScript structural search, replace, and refactor
http://graspjs.com
MIT License
1.28k stars 33 forks source link

question: how to match call with specific arguments? #19

Open salomvary opened 10 years ago

salomvary commented 10 years ago

Given this example:

foo('baz', 'bar')
bar('bar')
baz(x)

I want to match things like:

Experimented with call[arguments] and putting different things after arguments without success. I guess the answer should be at complex attributes but I couldn't figure it out.

Using grasp 0.2.1.

Awesome tool btw, I have high hopes for using it in complicated refactorings.

gkz commented 10 years ago

Some of this stuff is easier with equery

A call with the first argument as the string 'baz': grasp -e "__('baz', _$)" A function call where the arguments are exactly 'bar': grasp -e "__('bar')" A function call where the arguments are exactly x: grasp -e "__(x)" There isn't a way to do OR with equery at the moment, so you just need to do it separately.

You can do OR in squery, but you can't specify calls with a certain number of arguments, you can find however all calls with the first argument being either 'bar' or x: grasp 'call.args:first:matches(#x, "bar")'

salomvary commented 10 years ago

Hmm, thanks, it did the job. Looks like I was overcomplicating it by using squery.

Actually the problem I was trying to solve is renaming CommonJS modules. Here is an example for (for those who come later with the same problem):

var bar = require('lib/bar'),
    foo = require('foo'),
    FooBar = require('lib/foo-bar');

require('foo').whatever();
something(require('foo'));
foo.bax();

And the command is: grasp -e "require('foo')" --replace "require('bar')"

(Renaming the variables the module is assigned to should be easy from this point).