Skip to content

Instantly share code, notes, and snippets.

@quirkey
Created January 4, 2013 22:55
Show Gist options
  • Save quirkey/4458251 to your computer and use it in GitHub Desktop.
Save quirkey/4458251 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# script/whitespace
#
# Strips whitespace from any files modified in git
# Also:
# - converts tabs to spaces
# - ensures a single newline at the end
class WhitespaceProcessor
def self.process(code)
result = []
code.each_line do |line|
line.gsub!(/(\s+)$/, "\n")
line.gsub!(/\t/, ' ')
result << line
end
while result.last =~ /^$/
result.pop
end
unless result.last =~ /\n$/
result << "\n"
end
code = result.join
code.gsub!(/\A\n*/, '')
code
end
end
if ARGV.include?('--all')
files = `find . -type file | grep -v .git | grep -v ./vendor | grep -v ./tmp | egrep ".(rb|js|haml|html|css|sass)$"`.split(/\n/)
puts "* Stripping whitespace from all project files"
else
files = `git status | egrep ".(rb|js|haml|html|css|sass)$"`.split("\n").select { |file| file =~ /^#\t(modified|new file|renamed):/ }
puts "* Stripping whitespace from modified files."
end
files.each do |line|
line = line.split(/[\t\s]+/).last
if File.file?(line)
puts " processing #{line}..."
code = File.read(line)
File.open(line, 'w+') { |f| f << (WhitespaceProcessor.process(code)) }
end
end
puts "* DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment