Sha256: d9497f65ed2f3e70dacd2af5598f5c3471fde6b19d9c7365fe0037066b29b9db

Contents?: true

Size: 1.94 KB

Versions: 8

Compression:

Stored size: 1.94 KB

Contents

# frozen_string_literal: true

require "pathname"

module RuboCop
  module Cop
    module Sorbet
      # Makes sure that RBI files are always located under the defined allowed paths.
      #
      # Options:
      #
      # * `AllowedPaths`: A list of the paths where RBI files are allowed (default: ["rbi/**", "sorbet/rbi/**"])
      #
      # @example
      #   # bad
      #   # lib/some_file.rbi
      #   # other_file.rbi
      #
      #   # good
      #   # rbi/external_interface.rbi
      #   # sorbet/rbi/some_file.rbi
      #   # sorbet/rbi/any/path/for/file.rbi
      class ForbidRBIOutsideOfAllowedPaths < RuboCop::Cop::Cop # rubocop:todo InternalAffairs/InheritDeprecatedCopClass
        include RangeHelp

        def investigate(processed_source)
          paths = allowed_paths

          if paths.nil?
            add_offense(
              nil,
              location: source_range(processed_source.buffer, 1, 0),
              message: "AllowedPaths expects an array",
            )
            return
          elsif paths.empty?
            add_offense(
              nil,
              location: source_range(processed_source.buffer, 1, 0),
              message: "AllowedPaths cannot be empty",
            )
            return
          end

          # When executed the path to the source file is absolute.
          # We need to remove the exec path directory prefix before matching with the filename regular expressions.
          rel_path = processed_source.file_path.sub("#{Dir.pwd}/", "")

          add_offense(
            nil,
            location: source_range(processed_source.buffer, 1, 0),
            message: "RBI file path should match one of: #{paths.join(", ")}",
          ) if paths.none? { |pattern| File.fnmatch(pattern, rel_path) }
        end

        private

        def allowed_paths
          paths = cop_config["AllowedPaths"]
          return unless paths.is_a?(Array)

          paths.compact
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
rubocop-sorbet-0.8.3 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.8.2 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.8.1 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.8.0 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.7.8 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.7.7 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.7.6 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb
rubocop-sorbet-0.7.5 lib/rubocop/cop/sorbet/rbi/forbid_rbi_outside_of_allowed_paths.rb