Skip to content

Instantly share code, notes, and snippets.

@Marak
Forked from jpignata/whitespace
Created August 19, 2010 22:43
Show Gist options
  • Save Marak/539124 to your computer and use it in GitHub Desktop.
Save Marak/539124 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 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`.split("\n").select { |file| file =~ /^#\t(modified|new file|renamed):/ && !(file =~ /\(new commits\)/) }
puts "* Stripping whitespace from modified files."
end
files.each do |line|
line = line.split(/[\t\s]+/).last
puts " processing #{line}..."
code = File.read(line)
File.open(line, 'w+') { |f| f << (WhitespaceProcessor.process(code)) }
end
puts "* DONE"
@atmos
Copy link

atmos commented Aug 19, 2010

You can also set this in your ~/.gitconfig

whitespace = trailing-space,space-before-tab

@Marak
Copy link
Author

Marak commented Aug 19, 2010

ohh word? someone at work is getting an email yo!

@Marak
Copy link
Author

Marak commented Aug 19, 2010

pivot says you are wrong

@atmos
Copy link

atmos commented Aug 19, 2010

LOL! In the future I will keep my opinions to myself.

Try it for a few weeks and see if you still find yourself needing such a script. :D

We used to do shit like that back in the day as a part of our test suite. https://gist.github.com/03e30c6f12dbb6c96601

@Marak
Copy link
Author

Marak commented Aug 19, 2010

to my understanding this only throws warning / stops you from committing, but it doesn't actually strip the whitespace?

@atmos
Copy link

atmos commented Aug 19, 2010

Yup,

It appears you guys are right, it just ignores whitespace added when diff'd. I guess my team at the time just started pruning the trailing whitespace we were seeing. :)

@Marak
Copy link
Author

Marak commented Aug 19, 2010

True Life : I learn shit on Github

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment