Skip to content

Commit 38e60ff

Browse files
authored
Add custom regex rules for rubocop (#45)
1 parent bdaf0c1 commit 38e60ff

4 files changed

Lines changed: 60 additions & 2 deletions

File tree

Gemfile.lock

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ GIT
1010
PATH
1111
remote: .
1212
specs:
13-
umbrellio-utils (1.10.2)
13+
umbrellio-utils (1.11.0)
1414
memery (~> 1)
1515

1616
GEM

lib/umbrellio_utils/rubocop.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# frozen_string_literal: true
2+
3+
require "umbrellio_utils/rubocop/cop/custom/regex_rules"
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# frozen_string_literal: true
2+
3+
module RuboCop
4+
module Cop
5+
module Custom
6+
class RegexRules < Base
7+
def on_new_investigation
8+
return if processed_source.blank?
9+
10+
rules.each do |rule|
11+
next unless applies_to_file?(rule)
12+
13+
regex = Regexp.new(rule["regex"])
14+
processed_source.raw_source.each_line.with_index(1) do |line, lineno|
15+
next unless (match = regex.match(line))
16+
17+
range = range_for_match(lineno, match)
18+
add_offense(range, message: rule["message"])
19+
end
20+
end
21+
end
22+
23+
private
24+
25+
def rules
26+
cop_config["Rules"] || []
27+
end
28+
29+
def applies_to_file?(rule)
30+
path = processed_source.path.sub("#{Dir.pwd}/", "") # relative path
31+
32+
# Check exclusions first
33+
if rule["exclude_paths"]&.any? do |pattern|
34+
File.fnmatch?(pattern, path)
35+
end
36+
return false
37+
end
38+
39+
# Then check inclusions
40+
return true unless rule["paths"] # no restriction
41+
42+
rule["paths"].any? { |pattern| File.fnmatch?(pattern, path, File::FNM_PATHNAME) }
43+
end
44+
45+
def range_for_match(lineno, match)
46+
buffer = processed_source.buffer
47+
line_range = buffer.line_range(lineno)
48+
start_pos = line_range.begin_pos + match.begin(0)
49+
end_pos = line_range.begin_pos + match.end(0)
50+
Parser::Source::Range.new(buffer, start_pos, end_pos)
51+
end
52+
end
53+
end
54+
end
55+
end

lib/umbrellio_utils/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# frozen_string_literal: true
22

33
module UmbrellioUtils
4-
VERSION = "1.10.2"
4+
VERSION = "1.11.0"
55
end

0 commit comments

Comments
 (0)