Ruby in daily scripting
Ran into an issue where merges were getting corrupted for some reason, and adding a random garbage character to the end of some files. Whipping up a script that verifies the files is obviously the way to go in situations like that, and what I have been doing for years is using perl as a sort of glue language for unix command line utilities. As I get more comfortable with ruby, I find it is becoming more and more my weapon of choice in these situations.
There are three things that make a good "glue" language: great regex syntax, great file manipulation APIs, and great command line integration. Those three things were always my favorite things about perl, and thankfully, they have been copied over pretty much verbatim into ruby.
In this situation, I need to do a recursive search through a directory tree. Find does that in a pretty straightforward manner. Regex is great in ruby, using the =~ operator and standard regex syntax /pattern/, it will return the number of matches, or nil for nothing. Last piece is command line integration, anything inside of back ticks (`) will execute on the commandline, and then evaluate as the return value.
So, what we want to do is walk the source tree, look for source files (which should all end with >, since we are talking about xml-ish files), grab the last line, and make sure it ends with something valid (with a bit of experimentation, I found that for my site that meant >, space, tab, or newline)
What I ended up with is this
require 'find'
puts 'starting search....'
puts '-----'
Find.find(ARGV[0]) do |path| # walk the site tree
Find.prune if File.basename(path) == '.svn' # don't go into svn folders
if path =~ /(aspx|ascx|resx)$/ # only test aspx, ascx, or resx files
last = `tail -1 "#{path}"` # call out to tail
if last =~ /[^> \t\n]$/ # if it is not one of the safe characters
puts path
puts last
puts '-----'
end
end
end
puts 'done.'
Very fast to write, very straight forward to read.