Created
June 30, 2014 16:59
-
-
Save monkseal/54c2640fd583437655c5 to your computer and use it in GitHub Desktop.
Ruby/Rails Whitespace Stripper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Original Author, Dan Kubb (https://github.com/dkubb) | |
# Modified by Kevin English (https://github.com/monkseal) | |
# encoding: utf-8 | |
require 'pathname' | |
# files and extensions to process | |
FILES = %w[ capfile Capfile Gemfile Gemfile.lock Guardfile CHANGELOG LICENSE Manifest README README.rdoc README_FOR_APP RUBY-STYLE RUNNING_UNIT_TESTS Rakefile RUBY-STYLE SPECS TODO USAGE .autotest .gitignore .htaccess .rspec .rcov .rvmrc Vagrantfile .yardopts ].freeze | |
EXTENSIONS = %w[ builder cgi coffee conf css deploy erb example fcgi feature gemspec haml hs htc htm html js json key liquid markdown md opts php rake ratom rb rcsv rdf rdoc reek rhtml rip rjs rpdf ru rxml sake sass scss sh slim smil sql thor txt vcf xml yml java rabl jade ].freeze | |
paths = ARGV.map { |arg| Pathname.glob(arg) }.flatten | |
paths.each do |path_in| | |
start_path = path_in.directory? ? path_in + '**/*' : path_in | |
Pathname.glob((start_path).to_s).each do |path| | |
unless path.file? && path.size? && path.readable? && path.writable? && (FILES.include?(path.basename.to_s) || EXTENSIONS.include?(path.extname[1..-1])) | |
next | |
end | |
# replace leading whitespace (including tabs) with spaces | |
# replace trailing whitespace with a newline | |
document = path.open('r') do |fh| | |
fh.collect { |line| line.gsub(/\G\s/, ' ').rstrip << "\n" }.join.rstrip.gsub(/\n{2,8}/, "\n\n") | |
end << "\n" | |
# truncate the file if it is empty | |
document = '' if document.strip.empty? | |
# skip it if the file was not modified | |
next if document == path.read | |
puts "Modifying #{path}" | |
path.open('w') { |fh| fh.write document } | |
end | |
end |
pre-commit:
#!/bin/sh
echo "Running pre-commit hook, to run with out do 'git commit -n'"
echo "Running ws_strip...."
output=`git diff --cached --name-only | xargs /Users/kenglish/bin/ws_strip.rb `
if [[ $output == *Modifying* ]]
then
echo "Extra whitespace, failing commit";
exit 1
fi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I usually place this in
/usr/local/bin/ws_strip.rb
.To run on a branch:
To run on staged filed: