Posts Tagged ‘ruby rbgrep’

rbgrep, born 2008.1.28: 3 files, 118 lines

Tuesday, January 29th, 2008

Last night, I checked in the first version of my rbgrep program to Rubyforge.

First, the problem.  When I’m working on a program, whether I wrote it or not, I’m constantly asking questions like “where did I define this method?”, or “who uses this class”?  There’s a classic program to search for text in files: grep(1).  Unfortunately, plain grep is stupid.  It doesn’t know not to search .svn/ folders.  It doesn’t know that “find” after a “#” is not a method call.  And if you want to do anything nontrivial, the escaping can quickly become unbearable.

I’ve always just been lazy and solved this with … more grep. Like this:

grep -r "def start" ../../|grep -v svn|grep -v log:|less

What a pain.  At some point, I realized that if I wrote a short program, I could be even lazier.

The turning point was probably seeing Ryan Davis’ ParseTree.  This allows you to pass in some Ruby source code, and get back its AST, roughly, as arrays of symbols.  (It’s kind of like Lisp but not as convenient.)  This actually reaches inside the Ruby interpreter, so if I search the AST for a node that looks like [:defn :start …], I know that Ruby thinks it’s a “def start”, and not a comment or string literal or something like that.  Pretty cool.

To download it:

svn checkout http://rbgrep.rubyforge.org/svn/trunk/ rbgrep

To use it, run ‘rbgrep’.  For the example above, I would search for “def start” with:

rbgrep start some/folder/

Right now, it’s stupidly simple: it just searches for method defs in *.rb files.  There’s more to come in the future, and I’ve got some ideas for really cool features, but I’ll probably only add them if I think they’ll save me more time than it’ll take.

Now the Java#++ programmers are saying “why did you need to write this yourself?  my whiz-bang-IDE-inator does this for me out-of-the-box!”.  One of my current side projects (i.e., I started it a few weeks ago and haven’t really touched it since) is working through The Art of the Metaobject Protocol; one of their premises is that the reason you need a good meta system is so programmers can build tools like this easily.  How much work would it be to do this in Java?  More than 100 lines and an hour of work, I suspect.  Your fancy IDE has this because it needs to: if they didn’t provide this, it would never be worth it for you to implement yourself.