ファイルの改行コードの判別

svnリポジトリ中に改行コードが、他のファイルとは異なるファイルを発見。
とりあえず他にも混じっていないか調べるスクリプトrubyで作成して確認した。

その時のスクリプトを、備忘録としてここに貼り付けておく。

#!/usr/bin/ruby

class Eol

  def initialize( fname )
    @fname = fname
    @result = nil
    counter_reset
  end

  def counter_reset
    @cr = 0
    @lf = 0
    @crlf = 0
  end

  def max_eol_code( cr , lf , crlf )
    [:CR, :LF, :CRLF][ max_between_3( cr , lf, crlf ) ]
  end

  def max_between_3( arg0 , arg1 , arg2 )
    (arg0 >= arg1) ? ( (arg0 >= arg2) ? 0 : 2 ) : ( (arg1 >= arg2) ? 1 : 2 )
  end

  def guess_eol_of_file
    max_eol_code( @cr , @lf , @crlf )
  end

  def guess_eol(string)
    cr = string.scan(/(\r)(?!\n)/no).size > 0 ? 1 : 0
    lf = string.scan(/(?:\A|[^\r])(\n)/no).size > 0 ? 1 : 0
    crlf = string.scan(/(\r\n)/no).size > 0 ? 1 : 0

    @cr += cr
    @lf += lf
    @crlf += crlf

    max_eol_code( cr , lf , crlf )
  end


  def analyze
    File.open( @fname , "r"){ |file|
      while (l = file.gets) 
        ret = guess_eol(l)
      end
      @result = guess_eol_of_file
    }
  end

  def printResult
      printf( "%-5s %s\n" , @result.to_s , @fname )
  end
end

ARGV.each{ |fname|
  x = Eol.new( fname )
  x.analyze
  x.printResult
}

使い方

 スクリプト名 ファイル名 [ ファイル名]*