forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_util.rb
100 lines (83 loc) · 2.65 KB
/
path_util.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# frozen_string_literal: true
module RuboCop
# Common methods and behaviors for dealing with paths.
module PathUtil
module_function
def relative_path(path, base_dir = Dir.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 = Dir.pwd
if path.start_with? base_dir
relative_path(path, base_dir)
else
path
end
end
# rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity
def match_path?(pattern, path)
case pattern
when String
matches =
if pattern == path
true
elsif glob?(pattern)
File.fnmatch?(pattern, path, File::FNM_PATHNAME | File::FNM_EXTGLOB)
end
matches || hidden_file_in_not_hidden_dir?(pattern, path)
when Regexp
begin
pattern.match?(path)
rescue ArgumentError => e
return false if e.message.start_with?('invalid byte sequence')
raise e
end
end
end
# rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity
# Returns true for an absolute Unix or Windows path.
def absolute?(path)
%r{\A([A-Z]:)?/}i.match?(path)
end
# Returns true for a glob
def glob?(path)
path.match?(/[*{\[?]/)
end
def hidden_file_in_not_hidden_dir?(pattern, path)
hidden_file?(path) &&
File.fnmatch?(
pattern, path,
File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
) &&
!hidden_dir?(path)
end
def hidden_file?(path)
maybe_hidden_file?(path) && File.basename(path).start_with?('.')
end
HIDDEN_FILE_PATTERN = "#{File::SEPARATOR}."
# Loose check to reduce memory allocations
def maybe_hidden_file?(path)
return false unless path.include?(HIDDEN_FILE_PATTERN)
separator_index = path.rindex(File::SEPARATOR)
return false unless separator_index
dot_index = path.index('.', separator_index + 1)
dot_index == separator_index + 1
end
def hidden_dir?(path)
File.dirname(path).split(File::SEPARATOR).any? { |dir| dir.start_with?('.') }
end
end
end