Skip to content

Instantly share code, notes, and snippets.

@veszig
Created April 10, 2010 16:11
Show Gist options
  • Save veszig/362102 to your computer and use it in GitHub Desktop.
Save veszig/362102 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -w
# find . -type f -iname '*.rb' -exec fix_whitespace {} \;
require 'fileutils'
# set to nil if you don't want to backup anything
backup_dir = File.expand_path('~/.whitespace-backup')
unless backup_dir.nil? || File.directory?(backup_dir)
FileUtils.mkdir_p(backup_dir)
end
while filename = ARGV.shift
if File.file?(filename)
# remove trailing white spaces
filelines = File.readlines(filename)
nicelines = filelines.map { |line| line.gsub(/[\t\ ]+\Z/, '') }
# ensure that there are no empty lines at the end of the file
nicelines.pop while nicelines[-1] == "\n"
# the last line should end in a newline character
nicelines[-1] += "\n" if nicelines[-1] !~ /\n\Z/
# overwrite file if anything changed
unless filelines == nicelines
unless backup_dir.nil?
# create backup
timestamped = filename.split("/").last + '.' + Time.now.strftime("%Y%m%d%H%M%S")
backup_file = File.expand_path(timestamped, backup_dir)
FileUtils.copy(filename, backup_file)
puts "backed up #{filename} to #{backup_file}"
end
File.open(filename, "w") { |f| f << nicelines }
puts "changed #{filename}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment