Thursday, November 13, 2008

Grep is fun

I'm not what you would call a UNIX power user. I'm more of a UNIX casual user. I don't agree with the zealots who claim that the command line is king, and shell scripts keep the world spinning. It's a pain to remember the myriad of switches, and to remember the differences in those switches between platforms (BSD find requires a pathname, GNU find does not), etc. Maybe my distaste of the command line is why my primary computer is a Mac.

In any case, I was rooting around in the Android source code today, looking for examples involving the NotificationManager. I managed to whip up the following pipeline, of which I am proud.

grep -rl --include=*.java NotificationManager . | xargs grep -l "\.clear" | xargs mate

To break that down,

grep -rl --include=*.java NotificationManager . This will recurse in the current directory, finding all .java files which contain the word NotificationManager. The resulting list of files will be passed to the next step.
xargs grep -l "\.clear" This looks for the string ".clear" in any of the files that came from the first command. It outputs the list of matching files to the next command.
xargs mate This launches TextMate, my editor of choice, with all of the files found in the previous step.

To summarize, this pipeline opens a text editor with every .java file in the android source code that contains both of the strings "NotificationManager" and ".clear". In my case, I was looking for all invocations of NotificationManager.clear(). Since the Android source code seems to be pretty consistent about explicitly importing all classes used, this scheme works pretty well.

If anybody knows of any command-line tools for searching a code base for Java-aware constructs (such as method definition, method invocation, etc.), please let me know! Something like that would be really, really handy. Eclipse provides all that, but it doesn't look trivial to get all of the Android source code into Eclipse projects.

2 comments:

Anonymous said...

It's not free, but the structural search in IntelliJ IDEA is great.

Anonymous said...

I sometimes search for a method, but don't know where. I.e.: searching for shuffle () - where is it?

A script find_java_method.sh shuffle would be nice, which produces:
java.util.Collections.shuffle (java.util.List)
java.util.Collections.shuffle (java.util.List, java.util.Random)

Here it is:
http://home.arcor.de/hirnstrom/minis/index.html#find_javamethod