Sha256: 16f539b6b06ac2184dd528a36867ebf6af6dff75d4371610e792a8ae82a064bc

Contents?: true

Size: 1.63 KB

Versions: 58

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Bundler
      # Gems should be alphabetically sorted within groups.
      #
      # @example
      #   # bad
      #   gem 'rubocop'
      #   gem 'rspec'
      #
      #   # good
      #   gem 'rspec'
      #   gem 'rubocop'
      #
      #   # good
      #   gem 'rubocop'
      #
      #   gem 'rspec'
      #
      #   # good only if TreatCommentsAsGroupSeparators is true
      #   # For code quality
      #   gem 'rubocop'
      #   # For tests
      #   gem 'rspec'
      class OrderedGems < Base
        extend AutoCorrector
        include OrderedGemNode

        MSG = 'Gems should be sorted in an alphabetical order within their ' \
              'section of the Gemfile. ' \
              'Gem `%<previous>s` should appear before `%<current>s`.'

        def on_new_investigation
          return if processed_source.blank?

          gem_declarations(processed_source.ast)
            .each_cons(2) do |previous, current|
            next unless consecutive_lines(previous, current)
            next unless case_insensitive_out_of_order?(gem_name(current), gem_name(previous))

            register_offense(previous, current)
          end
        end

        private

        def previous_declaration(node)
          declarations = gem_declarations(processed_source.ast)
          node_index = declarations.map(&:location).find_index(node.location)
          declarations.to_a[node_index - 1]
        end

        # @!method gem_declarations(node)
        def_node_search :gem_declarations, <<~PATTERN
          (:send nil? :gem str ...)
        PATTERN
      end
    end
  end
end

Version data entries

58 entries across 51 versions & 8 rubygems

Version Path
rubocop-1.42.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.41.1 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.41.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.40.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.39.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.38.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.37.1 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.37.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.36.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.35.1 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.35.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.34.1 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.34.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.33.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.32.0 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.31.2 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.31.1 lib/rubocop/cop/bundler/ordered_gems.rb
rubocop-1.31.0 lib/rubocop/cop/bundler/ordered_gems.rb