- Download
git-fixws.rb
to~/bin/git-fixws.rb
chmod +x ~/bin/git-fixws.rb
git config --global alias.fixws '!ruby ~/bin/git-fixws.rb'
With a dirty tree, you can then run git fixws
to have trailing whitespace removed.
#!/usr/bin/env ruby | |
class File | |
def self.binary?(file) | |
s = (read(file, stat(file).blksize) || "").split(//) | |
s.size > 0 && ((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30 | |
end | |
def self.fix_trailing_space(file) | |
content = read(file) | |
if content =~ /\r\n/ | |
p :crlf => file | |
end | |
content.gsub!(/[\t ]+$/, '') | |
open(file, "w") { |f| f << content } | |
end | |
end | |
if ARGV.empty? | |
status = `git status`.split("\n") | |
files = status.map do |e| | |
e[/(modified|new file):\s*(.+?)$/, 2] || e[/renamed:.+->\s*(.+?)$/, 1] | |
end.compact | |
else | |
files = ARGV | |
end | |
abort "no modified files" if files.empty? | |
files.each do |file| | |
next if !File.file?(file) | |
if File.binary?(file) | |
p :binary => file | |
else | |
p :fixing => file | |
File.fix_trailing_space file.strip | |
end | |
end | |