Sha256: 4fcd8f477fe49628332cbc09102375baca0bf10fe1c7ace835010e5f303b431e

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks whether the source file has a utf-8 encoding comment or
      # not. This check makes sense only in Ruby 1.9, since in 2.0+ utf-8 is
      # the default source file encoding. There are two style:
      #
      # when_needed - only enforce an encoding comment if there are non ASCII
      #               characters, otherwise report an offense
      # always - enforce encoding comment in all files
      class Encoding < Cop
        include ConfigurableEnforcedStyle

        MSG_MISSING = 'Missing utf-8 encoding comment.'
        MSG_UNNECESSARY = 'Unnecessary utf-8 encoding comment.'

        def investigate(processed_source)
          return if RUBY_VERSION >= '2.0.0'
          return if processed_source.buffer.source.empty?

          line_number = encoding_line_number(processed_source)
          message = offense(processed_source, line_number)

          return unless message

          range = source_range(processed_source.buffer, line_number + 1, 0)
          add_offense(nil, range, message)
        end

        private

        def offense(processed_source, line_number)
          line = processed_source[line_number]
          encoding_present = line =~ /#.*coding\s?[:=]\s?(UTF|utf)-8/
          ascii_only = processed_source.buffer.source.ascii_only?
          always_encode = style == :always

          if !encoding_present && (always_encode || !ascii_only)
            MSG_MISSING
          elsif !always_encode && ascii_only && encoding_present
            MSG_UNNECESSARY
          end
        end

        def encoding_line_number(processed_source)
          line_number = 0
          line_number += 1 if processed_source[line_number] =~ /^#!/
          line_number
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubocop-0.25.0 lib/rubocop/cop/style/encoding.rb
rubocop-0.24.1 lib/rubocop/cop/style/encoding.rb
rubocop-0.24.0 lib/rubocop/cop/style/encoding.rb