Skip to content
This repository

Syntactically-aware grep for JavaScript

tree: 8bb3d60606

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 tests
Octocat-spinner-32 .gitignore Initial import January 06, 2012
Octocat-spinner-32 README.mdown
Octocat-spinner-32 jsgrep
README.mdown

jsgrep: a syntactically-aware grep for JavaScript

Jsgrep is program that searches for a particular JavaScript pattern using the abstract syntax tree (AST) of the program. This enables matching expressions based on their JavaScript meaning, rather than based on simple strings.

Examples

Find calls to window.setTimeout with a 0 timeout

$ jsgrep 'setTimeout(A, 0)' tests/*.js
tests/jquery.js:        setTimeout( function() {
tests/jquery.js:    setTimeout( clearFxNow, 0 );

Jsgrep uses metavariables as wildcards. Metavariables match any valid JavaScript chunk, so in this case, the first match was an entire inline function. In both cases, the second parameter to setTimeout was a literal value of 0.

Find value defaulting

$ jsgrep "A = A || B;" tests/*.js
tests/jquery.js:            args = args || [];
tests/jquery.js:    dataType = dataType || options.dataTypes[ 0 ];

When the pattern references the same metavariable multiple times, jsgrep ensures that the value of the metavariable is the same throughout the match.

Find the names of all invoked events

$ ./jsgrep -p B "A.fire(B, ...)" tests/*.j
tests/connect.js: 'auth.logout'
tests/connect.js: 'auth.login'

The ... operator matches 0 or more expressions in function calls and array initializers.

Find classes that have a 'path' property

$ jsgrep -p C "JX.install(C, { properties: { path: X } })" tests/*.js
tests/javelin.js: 'Event'
tests/javelin.js: 'URI'

Jsgrep allows you to search object initializations partially, which enables easily drilling into the structure of JavaScript classes. This example also uses the -p flag to print only a particular matched variable.

TODO

  • Consider a metavar that matches but doesn't save, to prevent ambiguities.
  • Consider support for --where/--eval and/or not-patterns
  • Support for most statements in patterns
  • Testing

Contributors

Jsgrep was written by Ryan Patterson at Facebook. Inspiration for this project draws heavily from pfff, a source code analyzer written at Facebook.

Something went wrong with that request. Please try again.