Sunday, April 22, 2012

Simple recursive file traversal in Elisp

Really quick: I wrote a simple bit of elisp to eval a body over each of the files in a directory, recursively. Looking around for a little bit, I found a couple of options, including Findr, which has its own queue implementation (pretty short), and whose main function is a whopping 55 lines!

There has to be a quicker way, I thought. I didn't need anything terribly fancy, I just wanted something that worked cross-platform (which ruled out find) and was simple. I ended up with this little guy:

11 lines for the main function, recursive-files itself, and another 3 (including docstring) for simplifying macro. It's main weakness at this point is that it incorrectly ignores any files with leading dots. So not only does it (wisely) avoid . and .., it rather foolishly avoids .foo as well. I couldn't easily figure out how to exclude . and .. in a single regex easily without also excluding leading-dot files. For what I'm doing, it's not important.

Also, note that this barfs on symlinks. It thinks they're directories and tries to call directory-files-and-attributes on them. Again, a more careful implementation would deal with this.

I was surprised that Emacs didn't have a "recursively visit files" function or macro built in, but this gets me close enough. Enjoy!

No comments:

Post a Comment