gkz / grasp

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

How can I find and rename a function declaration by id!? #104

Closed kristianmandrup closed 7 years ago

kristianmandrup commented 7 years ago

Can only make it work if I simply use selector #hello and replace goodbye using squery

How do I make the selector only apply for function declarations?

Error: Error processing selector ''func-dec#hello''

and if I try

const find = 'func-dec[id=#hello]'
const replace = 'goodbye'

it replaces the full declaration simply with goodbye, hmmm...

Then I try

const find = 'func-dec[id=#hello] $fun'
const replace = 'function goodbye {{fun}}'

But I get my original function right back. Wtf!?

If I try the same with equery

const find = 'function hello'
const replace = 'function goodbye'

const replacer = grasp.replace('equery', find, replace)

Error: Error processing selector 'function hello'.

Finally something:

const find = 'function hello($args) { $body }'
const replace = 'function goodbye({{args}}) { {{body}} }'

Is the correct way?

My code:

let code = `function hello(x) {
  console.log(x)
}`

let expResult = `function goodbye(x) {
  console.log(x)
}`

const find = 'function hello($args) { $body }'
const replace = 'function goodbye({{args}}) { {{body}} }'

const replacer = grasp.replace('squery', find, replace)
let result = replacer(code)

const log = console.log

test('replace function name', t => {
  log('result', result)
  t.is(result, expResult)
})
kristianmandrup commented 7 years ago

Took me all day, but now I finally got it working here