|
| 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 |
0 commit comments