Module: RuboCop::PathUtil

Overview

Common methods and behaviors for dealing with paths.

Class Method Summary collapse

Class Method Details

.absolute?(path) ⇒ Boolean

Returns true for an absolute Unix or Windows path.

Returns:

  • (Boolean)


51
52
53
# File 'lib/rubocop/path_util.rb', line 51

def absolute?(path)
  path =~ %r{\A([A-Z]:)?/}
end

.match_path?(pattern, path) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rubocop/path_util.rb', line 36

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

.pwdObject



55
56
57
# File 'lib/rubocop/path_util.rb', line 55

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

.relative_path(path, base_dir = PathUtil.pwd) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rubocop/path_util.rb', line 8

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

.reset_pwdObject



59
60
61
# File 'lib/rubocop/path_util.rb', line 59

def self.reset_pwd
  @pwd = nil
end

.smart_path(path) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/rubocop/path_util.rb', line 25

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