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 replace a class declaration by id!? #105

Closed kristianmandrup closed 7 years ago

kristianmandrup commented 7 years ago

Very difficult to see how to read/understand how to use docs to select AST nodes for replacement...

Been trying:

class-dec#hello, [class-dec=#hello]' and [class-dec='hello'] ...

Then tried equery

const find = 'class Model { $body }'
const replace = 'class Control { {{body}} }'

Error processing selector 'class Model { $body }'

help syntax grasp --help syntax is not been much help when you don't understand the basic operations

class-dec (ClassDeclaration) id, superClass, body

Why can't I do this!?

const find = 'class[id=#Model]'
const replace = 'class Control {{.body}}'

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

How do I use this in a concrete example!?

import test from 'ava'
import grasp from 'grasp'

const find = 'class-dec#Model'
const replace = 'Control'

let code = `export default class Model {
  constructor() {
  }

  display(x) {
    console.log(x)
  }
}`

let expResult = `export default class Control {
  constructor() {
  }

  display(x) {
    console.log(x)
  }
}`

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

const log = console.log

test('replace class 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