Remove'em trailing whitespaces!

16 February 2010

Some of you reading this probably use TextMate. It is an excellent editor with two caveats. The first is that you can only see one file in the editing window (no screen split), the other is that there is no save hook. This latter gave me headaches since I can't stand any trailing whitespace in source code and the easiest solution would have been to run a script to remove those when the file is saved.

Without further ado I'll paste my solution below. Obviously this is not a difficult task to accomplish so the goal is to share not to show off. I use Git for SCM and the following solution parses out the files that have been modified and runs the whitespace eraser script for those. If you use something else (why do you?) you should obviously change the first building block:

1#!/usr/bin/env ruby -wn
2modified_file_pattern = /^#\s+(?:modified|new file):\s+(.*)$/
3puts $1  if modified_file_pattern =~ $_
1#!/usr/bin/env ruby -wn
2$:.unshift(File.dirname(__FILE__))
3
4require "trailing_whitespace_eraser"
5TrailingWhiteSpaceEraser.rm_trailing_whitespace!($_)
 1
 2class TrailingWhiteSpaceEraser
 3  FILE_TYPES = ["rb", "feature", "yml", "erb", "haml"]
 4
 5  def self.rm_trailing_whitespace_from_file!(file)
 6    trimmed = File.readlines(file).map do |line|
 7      line.gsub(/[\t ]+$/, "")
 8    end
 9    open(file, "w") { |f| f.write(trimmed) }
10  end
11
12  def self.rm_trailing_whitespace!(root)
13    root = File.expand_path(root)
14    files = File.directory?(root) ? Dir.glob("#{root}/**/*.{#{FILE_TYPES.join(',')}}") : [root]
15    files.each { |file| rm_trailing_whitespace_from_file!(file.chomp) }
16  end
17end

And then you run it by typing:

1git status | parse_modified_files_from_git_status.rb | rm_trailing_whitespace.rb

If you decide to use this, it is more convenient to download the raw source

Hopefully I did my tiny bit to have less trailing whitespace in OS code.

Share on Twitter