Sha256: 865d3319923ec505a95c8835dee29ea273cb67efa2bd7900c76a4e85a98e9050

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

require 'pathname'
require 'rubycritic/configuration'

module RubyCritic
  class SourceLocator
    RUBY_EXTENSION = '.rb'.freeze
    RUBY_FILES = File.join('**', "*#{RUBY_EXTENSION}")
    RUBY_SHEBANG = '#!/usr/bin/env ruby'.freeze

    def initialize(paths)
      @initial_paths = Array(paths)
    end

    def paths
      @paths ||= pathnames.map(&:to_s)
    end

    def pathnames
      @pathnames ||= expand_paths
    end

    private

    def deduplicate_symlinks(path_list)
      # sort the symlinks to the end so files are preferred
      path_list.sort_by! { |path| File.symlink?(path.cleanpath) ? 'z' : 'a' }
      if defined?(JRUBY_VERSION)
        require 'java'
        path_list.uniq! do |path|
          java.io.File.new(path.realpath.to_s).canonical_path
        end
      else
        path_list.uniq!(&:realpath)
      end
    end

    def expand_paths
      path_list = @initial_paths.flat_map do |path|
        if File.directory?(path)
          Pathname.glob(File.join(path, RUBY_FILES))
        elsif File.exist?(path) && ruby_file?(path)
          Pathname.new(path)
        end
      end.compact

      deduplicate_symlinks(path_list) if Config.deduplicate_symlinks

      path_list.map(&:cleanpath)
    end

    def ruby_file?(path)
      Config.ruby_extensions.include?(File.extname(path)) || File.open(path, &:gets).to_s.match?(RUBY_SHEBANG)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubycritic-4.9.1 lib/rubycritic/source_locator.rb
rubycritic-4.9.0 lib/rubycritic/source_locator.rb
rubycritic-4.8.1 lib/rubycritic/source_locator.rb
rubycritic-4.8.0 lib/rubycritic/source_locator.rb