Class: Magic::Commenter

Inherits:
Object
  • Object
show all
Includes:
Open3
Defined in:
lib/magic-commenter.rb,
lib/magic-commenter/version.rb

Constant Summary collapse

VERSION =
"0.0.3"

Instance Method Summary collapse

Constructor Details

#initialize(files) ⇒ Commenter

Returns a new instance of Commenter.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/magic-commenter.rb', line 10

def initialize(files)
  files.sort!

  threads = []

  2.times do |i|
    threads << Thread.new do
      while(file = files.shift)
        puts "Thread-#{i}: checking #{file}"
        firstline = File.readlines(file).first
        if firstline && !firstline.include?("encoding: utf-8")
          stdin, stdout, stderr = popen3("ruby -c #{file}")
          errors = stderr.read

          if errors && errors.include?("invalid multibyte char")
            puts ">> Fixing #{file}"
            contents = "# -*- encoding: utf-8 -*-\n" + File.read(file)
            File.open(file,"w") do |f|
              f.write contents
              f.close
            end
          end
        end
      end
    end
  end

  threads.each(&:join)
end