Sha256: c2174acba54881a56724e7f6e61d7d53c7a96edd23998a14e6a190d49df09008

Contents?: true

Size: 1.48 KB

Versions: 10

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

module RuboCop
  # Common methods and behaviors for dealing with paths.
  module PathUtil
    module_function

    def relative_path(path, base_dir = PathUtil.pwd)
      # Optimization for the common case where path begins with the base
      # dir. Just cut off the first part.
      if path.start_with?(base_dir)
        base_dir_length = base_dir.length
        result_length = path.length - base_dir_length - 1
        return path[base_dir_length + 1, result_length]
      end

      path_name = Pathname.new(File.expand_path(path))
      begin
        path_name.relative_path_from(Pathname.new(base_dir)).to_s
      rescue ArgumentError
        path
      end
    end

    def smart_path(path)
      # Ideally, we calculate this relative to the project root.
      base_dir = PathUtil.pwd

      if path.start_with? base_dir
        relative_path(path, base_dir)
      else
        path
      end
    end

    def match_path?(pattern, path)
      case pattern
      when String
        File.fnmatch?(pattern, path, File::FNM_PATHNAME)
      when Regexp
        begin
          path =~ pattern
        rescue ArgumentError => e
          return false if e.message.start_with?('invalid byte sequence')
          raise e
        end
      end
    end

    # Returns true for an absolute Unix or Windows path.
    def absolute?(path)
      path =~ %r{\A([A-Z]:)?/}
    end

    def self.pwd
      @pwd ||= Dir.pwd
    end

    def self.reset_pwd
      @pwd = nil
    end
  end
end

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
rubocop-0.58.1 lib/rubocop/path_util.rb
rubocop-0.58.0 lib/rubocop/path_util.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/path_util.rb
rubocop-0.57.2 lib/rubocop/path_util.rb
rubocop-0.57.1 lib/rubocop/path_util.rb
rubocop-0.57.0 lib/rubocop/path_util.rb
rubocop-0.56.0 lib/rubocop/path_util.rb
rubocop-0.55.0 lib/rubocop/path_util.rb
rubocop-0.54.0 lib/rubocop/path_util.rb
rubocop-0.53.0 lib/rubocop/path_util.rb