LoginSignup
13
7

More than 5 years have passed since last update.

Rubocop にひどいバグを見つけた話

Last updated at Posted at 2016-04-12

2016/09/14追記

ファイルを開く時のモードに関するバグは拙い英語力+機械翻訳で頑張ってissue登録した結果
修正されました

.rubocop.ymlの文字コード問題についても
多分修正されてます

短気向けまとめ

Windows でこそ必要な改行コードのLF強制がWindows環境で無効化される
原因は、テキストモード

processed_source.rb.diff
--- a/lib/rubocop/processed_source.rb   Fri Mar 25 11:24:05 2016
+++ b/lib/rubocop/processed_source.rb   Tue Apr 12 10:57:16 2016
@@ -14,7 +14,7 @@
                 :parser_error, :raw_source, :ruby_version

     def self.from_file(path, ruby_version)
-      file = File.read(path)
+      file = File.read(path, mode:'rb')
       new(file, ruby_version, path)
     rescue Errno::ENOENT
       raise RuboCop::Error, "No such file or directory: #{path}"

きっかけ

いつの間にか、改行コードがCRLF/LF入り混じったソースが混じってて
「あれ? Rubocopで検査してるはずなのに、こんなの通しちゃうの?」
と思って調べたら Style/EndOfLine で検査してる事が判明する。
.rubocop.yml でEnabled: true にしてみても通過してしまう。

調査

rubocop -rpry -C false <<crlf.rb>>

で pryを挿入して rubocopのソースの中に適宜 binding.pry を挿入してみると
あれ、\r が消えてる。

原因

十中八九テキストモードで
他にありうるケースとして入力文字列を自分で合成してたんだろ。
とアタリをつけて、おもむろに caller でコールスタック出して遡った結果
冒頭に書いた場所を書き換えると、

crlf.rb:1:1: C: Carriage return character detected.

警告きた!

コマンドラインからだと直ったけど

私は、Atom で編集して保存時に自動的にRubocop掛けてるのですが
このパッチ適用後でも\rを検知してくれませんでした。

そこで今度はソースを$stdin で検索して

options.diff
--- A/lib/rubocop/options.rb    Fri Mar 25 11:24:05 2016
+++ B/lib/rubocop/options.rb    Tue Apr 12 11:26:55 2016
@@ -131,7 +131,7 @@

       option(opts, '-v', '--version')
       option(opts, '-V', '--verbose-version')
-      option(opts, '-s', '--stdin') { @options[:stdin] = $stdin.read }
+      option(opts, '-s', '--stdin') { $stdin.binmode; @options[:stdin] = $stdin.read }
     end

     def add_list_options(opts)

Rubocop on Windows の他のバグ

他にも、ほぼWindows特有のバグとして
.rubocop.ymlの文字コードがデフォルトエンコーディングに依存するというものがある。

つまり、.rubocop.yml内にコメントを日本語で書くと
特別な設定なしの場合

  • 非windowsの場合: utf-8
  • windowsの場合: cp932

にしないといけない

以上2つのバグは私の英語力/RSpec力超えてて報告できないので
とりあえずQiitaに晒しときます。

13
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7