Skip to content

Instantly share code, notes, and snippets.

@jarib
Last active December 14, 2015 06:19
Show Gist options
  • Save jarib/5041277 to your computer and use it in GitHub Desktop.
Save jarib/5041277 to your computer and use it in GitHub Desktop.
  1. Download git-fixws.rb to ~/bin/git-fixws.rb
  2. chmod +x ~/bin/git-fixws.rb
  3. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment