Skip to content

Instantly share code, notes, and snippets.

@dkubb
Last active December 21, 2015 20:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkubb/28403 to your computer and use it in GitHub Desktop.
Save dkubb/28403 to your computer and use it in GitHub Desktop.
Strips trailing whitespace from source files
#!/usr/bin/env ruby
require 'pathname'
# files and extensions to process
FILES = %w[ capfile Capfile Dockerfile Gemfile Gemfile.devtools Gemfile.lock Guardfile CHANGELOG LICENSE Manifest README README.rdoc README_FOR_APP RUNNING_UNIT_TESTS Rakefile RUBY-STYLE SPECS TODO USAGE Vagrantfile .autotest .gitattributes .gitignore .htaccess .rspec .rcov .rvmrc .travis.yml .vimrc ].freeze
EXTENSIONS = %w[ builder cabal cgi coffee conf css deface deploy erb example fcgi feature handlebars haml hs htc htm html jinja js json key markdown md opts pem php rabl rake ratom rb rcsv rdf rdoc reek rhtml rip rjs rpdf ru rxml sake sass scss sh sls smil sql svg thor txt vcf xml yml ].freeze
paths = ARGV.flat_map(&Pathname.method(:glob))
paths.each do |path_in|
# TODO: check to see if this excludes hidden fields
start_path = path_in.directory? ? path_in.join('**/*') : 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]))
# puts "Skipping #{path}" if path.file?
next
end
# replace leading whitespace (including tabs) with spaces
# replace trailing whitespace with a newline
document = path.open('r') do |fh|
fh.map { |line| line.gsub(/\G\t/, ' ').rstrip << "\n" }.join.rstrip
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment