Ruby: how to add “# encoding: UTF-8” automatically?

前端 未结 6 1037
时光说笑
时光说笑 2020-12-05 00:21

Is there any gem which adds # encoding: UTF-8 to each Ruby file automatically?

Or is there any other way to prevent from the invalid multibyte cha

6条回答
  •  情话喂你
    2020-12-05 01:09

    How about just running a script?

    #!/usr/bin/env ruby1.9.1
    require 'find'
    
    fixfile = []
    
    Find.find('.') do |path|
      next unless /\.rb$/.match(path);
      File.open(path) do |file|
        count = 0;
        type = :lib
        file.each do |line|
          if count == 0 and /#!/.match(line)
            type = :script
          end
          if  /utf/.match(line)
            break
          end
          if (count += 1) > 10 then
            fixfile.push path:path, type:type
            break
          end
        end
        if file.eof?
            fixfile.push path:path, type:type
        end
      end
    end
    
    fixfile.each do |info|
      path = info[:path]
      backuppath = path + '~'
      type = info[:type]
      begin
         File.delete(backuppath) if File.exist?(backuppath)
         File.link(path, backuppath)
      rescue Errno::ENOENT => x
         puts "could not make backup file '#{backuppath}' for '#{ path }': #{$!}"
         raise
      end
      begin
        inputfile = File.open(backuppath, 'r')
        File.unlink(path)
        File.open(path, 'w') do |outputfile|
          if type == :script
            line = inputfile.readline
            outputfile.write line
          end
          outputfile.write "# encoding: utf-8\n"
          inputfile.each do |line|
            outputfile.write line
          end
          inputfile.close
          outputfile.close
        end
      rescue => x
        puts "error: #{x} #{$!}"
        exit
      end
    

    To make it automatic add this to your Rakefile.

    You could run file -bi #{path} and look for charset=utf-8 if you only want to update files that have utf-8 chars.

提交回复
热议问题