rubocop-metz 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7a70996428c4b11c07460d7eaf12494f2e675d1b574e4f92af1ddbc245e8ecfc
4
- data.tar.gz: af4ae4bd83391bf13da58d62c3a87c5a07be076713167fa34e349449ebf6c756
3
+ metadata.gz: 254fcc6071ff08ba5fac392e60bdfe75531f6e41b7d180a6fb833d2e11825c55
4
+ data.tar.gz: 4dc301e32f9805313fd68cfc8c7d415d946bf8ebc03d0067837f3994323cd827
5
5
  SHA512:
6
- metadata.gz: 47086b1fb0e8244ab9f249b69b76e722cce8685647a938ca7a6387815a315d4e28da0870cf848eadd10b70150c8cc3100f327a53d4861b74e681d19ff7f29816
7
- data.tar.gz: f5f13b5c4ffdf5e9a72e9baede758c77ab2d460a7137d0ddc658116279eabc37f4aa35555166b7436744189facc2f0b65aa2000c69e617d4b3ffd864dc86db37
6
+ metadata.gz: 0b8cbca1694e4e1b5f7f4cdf631c0a99bd0fb054242dd5e5e96feab03c867bee3f2bfaac34038c58caa18f318489887680210b5f27b6e8dbdbe47f5e807ef218
7
+ data.tar.gz: 7865e226ade783613d45f16ae841ce34665a1b9f130330abc9e27df885541cfd52268cae2bb88a472fc63aba7103bd25476c7fe32e4fc2b62be1bb52a3946561
data/config/default.yml CHANGED
@@ -133,6 +133,56 @@ Metz/ViewsDeepNavigation:
133
133
  Enabled: true
134
134
  Severity: refactor
135
135
  MaxChainLength: 3
136
+ AllowedReceivers: []
136
137
  Include:
137
138
  - 'app/views/**/*.{erb,haml,slim}'
138
139
  VersionAdded: '0.1'
140
+
141
+ # MetzProject/* entries are configuration only: no RuboCop cop runs under
142
+ # these names. They let a project's .rubocop.yml set `Enabled: false` or
143
+ # `Exclude` for metz-scan's project analyzers without RuboCop rejecting the
144
+ # key as an unrecognized cop.
145
+ MetzProject/RepeatedBranching:
146
+ Description: 'Project analyzer: the same state or type check branched on in several files.'
147
+ Enabled: true
148
+ VersionAdded: '0.7'
149
+
150
+ MetzProject/ServiceSoup:
151
+ Description: 'Project analyzer: one method coordinating several distinct service objects.'
152
+ Enabled: true
153
+ VersionAdded: '0.7'
154
+
155
+ MetzProject/DeepInheritanceTree:
156
+ Description: 'Project analyzer: base classes with a large spread of descendants.'
157
+ Enabled: true
158
+ VersionAdded: '0.7'
159
+
160
+ MetzProject/PackageDependencyPressure:
161
+ Description: 'Project analyzer: declarations referenced from several files outside their package.'
162
+ Enabled: true
163
+ VersionAdded: '0.7'
164
+
165
+ MetzProject/NamespaceLeakPressure:
166
+ Description: 'Project analyzer: internal namespace constants referenced outside their namespace.'
167
+ Enabled: true
168
+ VersionAdded: '0.7'
169
+
170
+ MetzProject/ImplicitContextPressure:
171
+ Description: 'Project analyzer: repeated ambient CurrentAttributes-style context access.'
172
+ Enabled: true
173
+ VersionAdded: '0.7'
174
+
175
+ MetzProject/RepeatedQueryCriteria:
176
+ Description: 'Project analyzer: repeated hash-style ActiveRecord query predicates across packages.'
177
+ Enabled: true
178
+ VersionAdded: '0.7'
179
+
180
+ MetzProject/SubclassOverridePressure:
181
+ Description: 'Project analyzer: base classes whose descendants repeatedly override the same method.'
182
+ Enabled: true
183
+ VersionAdded: '0.7'
184
+
185
+ MetzProject/TestCallsPrivateMethod:
186
+ Description: 'Project analyzer: tests that call private methods of the code under test.'
187
+ Enabled: true
188
+ VersionAdded: '0.7'
@@ -1,28 +1,29 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "file_classifier"
3
+ require_relative "template_ruby_fragment"
4
4
 
5
5
  module Metz
6
- # Ruby extractor for ERB / HAML / SLIM view templates. Registered with
6
+ # Ruby extractor for ERB templates. Registered with
7
7
  # `RuboCop::Runner.ruby_extractors` so that view-aware Metz cops (currently
8
8
  # `Metz/ViewsDeepNavigation`) can run against ERB content. RuboCop's parser
9
9
  # would otherwise emit `Lint/Syntax` for any `.erb` file because the raw
10
- # template is not a valid Ruby program.
10
+ # template is not a valid Ruby program. Every `.erb` file is extracted;
11
+ # each cop's own scope decides which files it checks.
11
12
  #
12
- # The extractor scans for ERB tags, hands each `<% ... %>` / `<%= ... %>`
13
- # body to RuboCop as its own `ProcessedSource`, and records the byte offset
13
+ # The extractor scans for ERB tags, hands each `<% ... %>`, `<%= ... %>`, and
14
+ # `<%== ... %>` body to RuboCop as its own `ProcessedSource`, and records the byte offset
14
15
  # of the body inside the original template. RuboCop adds that offset back
15
16
  # to every offense location, so reported line / column numbers point at
16
17
  # the original `.erb` file -- not the synthetic snippet.
17
18
  #
18
- # Control-flow openers such as `<% if ... %>` are reduced to the condition
19
- # expression. Other invalid fragments are skipped to avoid `Lint/Syntax`
20
- # noise. ERB comments (`<%# ... %>`) are skipped as well.
19
+ # Control-flow openers such as `<% if ... %>` and block openers such as
20
+ # `<%= form_with(...) do |f| %>` are reduced to their expression (see
21
+ # `Metz::TemplateRubyFragment`). ERB comments (`<%# ... %>`) and escaped
22
+ # tags (`<%%= ... %>`) are skipped.
21
23
  module ErbRubyExtractor
22
- ERB_TAG = /<%(?<kind>[-=#]?)(?<body>.*?)-?%>/m
23
- CONTROL_CONDITION = /\A(?<prefix>\s*(?:if|unless|while|until|elsif|case)\b\s*)(?<expr>.*?)(?:\s+then)?\s*\z/m
24
- TRAILING_DO_BLOCK = /\A(?<expr>.*?)(?<suffix>\s+do\b(?:\s*\|[^|]*\|)?\s*)\z/m
25
- MAGIC_COMMENT = "# frozen_string_literal: true\n\n"
24
+ ERB_TAG = /<%(?<kind>==|[-=#%]?)(?<body>.*?)-?%>/m
25
+ # `<%#` is a comment and `<%%` an escaped literal `<%`; neither holds Ruby.
26
+ SKIPPED_KINDS = %w[# %].freeze
26
27
 
27
28
  module_function
28
29
 
@@ -31,12 +32,12 @@ module Metz
31
32
  return nil unless path && handles?(path)
32
33
 
33
34
  snippets = extract_snippets(processed_source)
34
- snippets << empty_snippet(processed_source) if snippets.empty?
35
+ snippets << TemplateRubyFragment.empty(processed_source) if snippets.empty?
35
36
  snippets
36
37
  end
37
38
 
38
39
  def handles?(path)
39
- File.extname(path.to_s) == ".erb" && ::Metz::FileClassifier.view?(path)
40
+ File.extname(path.to_s) == ".erb"
40
41
  end
41
42
 
42
43
  def install!
@@ -60,48 +61,9 @@ module Metz
60
61
  end
61
62
 
62
63
  def snippet_for(match, processed_source)
63
- return if match[:kind] == "#"
64
+ return if SKIPPED_KINDS.include?(match[:kind])
64
65
 
65
- ruby_version = processed_source.ruby_version || RUBY_VERSION.to_f
66
- ps, offset = source_and_offset(match, ruby_version, processed_source.path)
67
- return unless ps
68
-
69
- { offset: offset, processed_source: ps }
70
- end
71
-
72
- def source_and_offset(match, ruby_version, path)
73
- body = match[:body]
74
- ps = RuboCop::ProcessedSource.new(body, ruby_version, path)
75
- return [ps, match.begin(:body)] if ps.valid_syntax?
76
- return unless code_tag?(match[:kind])
77
-
78
- expression_source(body, ruby_version, path, match.begin(:body))
79
- end
80
-
81
- def code_tag?(kind)
82
- kind.empty? || kind == "-"
83
- end
84
-
85
- def expression_source(body, ruby_version, path, body_offset)
86
- match = body.match(CONTROL_CONDITION) || body.match(TRAILING_DO_BLOCK)
87
- return unless match
88
-
89
- ps = RuboCop::ProcessedSource.new(control_expression(match[:expr]), ruby_version, path)
90
- [ps, expression_offset(body_offset, match)] if ps.valid_syntax?
91
- end
92
-
93
- def control_expression(expr)
94
- "#{MAGIC_COMMENT}#{expr}\n"
95
- end
96
-
97
- def expression_offset(body_offset, match)
98
- body_offset + match.begin(:expr) - MAGIC_COMMENT.bytesize
99
- end
100
-
101
- def empty_snippet(processed_source)
102
- ruby_version = processed_source.ruby_version || RUBY_VERSION.to_f
103
- ps = RuboCop::ProcessedSource.new("", ruby_version, processed_source.path)
104
- { offset: 0, processed_source: ps }
66
+ TemplateRubyFragment.snippet(match[:body], match.begin(:body), processed_source)
105
67
  end
106
68
  end
107
69
  end
@@ -20,6 +20,7 @@ module Metz
20
20
  module FileClassifier
21
21
  CONTROLLER_PATTERN = %r{(?:\A|/)app/controllers/[^\0]+\.rb\z}
22
22
  VIEW_PATTERN = %r{(?:\A|/)app/views/[^\0]+\.(?:erb|haml|slim)\z}
23
+ TEMPLATE_PATTERN = /\.(?:erb|haml|slim)\z/
23
24
  MODEL_PATTERN = %r{(?:\A|/)app/models/[^\0]+\.rb\z}
24
25
  OPERATION_PATTERN = %r{(?:\A|/)app/(?:services|operations)/[^\0]+\.rb\z}
25
26
 
@@ -33,6 +34,10 @@ module Metz
33
34
  normalize(path).match?(VIEW_PATTERN)
34
35
  end
35
36
 
37
+ def template?(path)
38
+ normalize(path).match?(TEMPLATE_PATTERN)
39
+ end
40
+
36
41
  def model?(path)
37
42
  normalize(path).match?(MODEL_PATTERN)
38
43
  end
@@ -7,27 +7,85 @@ module Metz
7
7
  # registered with `RuboCop::Runner.ruby_extractors` so view-aware Metz cops
8
8
  # (currently `Metz/ViewsDeepNavigation`) can run against HAML content.
9
9
  #
10
- # Recognises three HAML constructs that carry Ruby:
10
+ # Recognises the HAML constructs that carry Ruby:
11
11
  #
12
- # * `= ruby_expr` - output script (escaped)
13
- # * `- ruby_stmt` - silent script
14
- # * `:ruby` filter - indented block of plain Ruby
12
+ # * `= expr`, `!= expr`, `&= expr`, `~ expr` - output script, bare or
13
+ # after an element (`%p= expr`, `.note{ ... }!= expr`)
14
+ # * `- stmt` - silent script, including control openers
15
+ # (`- if cond`, `- items.each do |item|`)
16
+ # * `%p{ key: expr }` - a single-line Ruby attribute hash
17
+ # * `:ruby` filter - indented block of plain Ruby
15
18
  #
16
- # Each tag's body is handed to RuboCop as its own `ProcessedSource` whose
17
- # offset points at the body's column in the original template. Tags whose
18
- # body is not valid Ruby on its own are silently skipped (we never want to
19
- # surface `Lint/Syntax` from a partial HAML fragment).
19
+ # `-#` comments, `==` interpolated text, other filters' bodies (`:css`,
20
+ # `:javascript`, ...), and HTML-style `(...)` or object reference `[...]`
21
+ # attributes are not extracted; output after those attribute groups still
22
+ # is. Every `.haml` file is extracted; each cop's own scope decides which
23
+ # files it checks. Each fragment is handed
24
+ # to RuboCop as its own `ProcessedSource` whose offset points at the
25
+ # fragment's column in the original template; fragments that are not valid
26
+ # Ruby on their own are skipped.
20
27
  module HamlRubyExtractor
21
28
  extend TemplateRubyExtractor
22
29
 
23
- EXPR_LINE = /\A(?<lead>[ \t]*(?:[%.#][^\s=]*)?)=\s(?<body>.*)$/
24
- STMT_LINE = /\A(?<lead>[ \t]*)-(?!#)\s(?<body>.*)$/
25
- FILTER_LINE = /\A(?<indent>[ \t]*):ruby[ \t]*$/
30
+ SILENT_LINE = /\A[ \t]*-(?!#)[ \t]*(?<body>.*)$/
31
+ ELEMENT = /\A[ \t]*(?<name>(?:%[\w:-]+)?(?:[.#][\w-]+)*)/
32
+ OUTPUT = /\G[<>]*(?:[!&]?=|~)(?!=)[ \t]*(?<body>.*)$/
33
+ GROUPS = { "(" => ")", "[" => "]" }.freeze
34
+ FILTER_LINE = /\A(?<indent>[ \t]*):(?<name>\w+)[ \t]*$/
26
35
 
27
36
  module_function
28
37
 
29
38
  def handles?(path)
30
- File.extname(path.to_s) == ".haml" && ::Metz::FileClassifier.view?(path)
39
+ File.extname(path.to_s) == ".haml"
40
+ end
41
+
42
+ def line_fragments(line, processed_source)
43
+ silent = line.match(SILENT_LINE)
44
+ return [[silent[:body], silent.begin(:body)]] if silent
45
+
46
+ hashes, stop = element_attributes(line, line.match(ELEMENT), processed_source)
47
+ [*hashes, output(line, stop)].compact
48
+ end
49
+
50
+ def element_attributes(line, element, processed_source)
51
+ return [[], element.end(0)] if element[:name].empty?
52
+
53
+ attribute_groups(line, element.end(0), processed_source)
54
+ end
55
+
56
+ # Walks the `{...}`, `(...)`, and `[...]` groups after an element name and
57
+ # returns the Ruby attribute hashes among them plus the column past them.
58
+ def attribute_groups(line, start, processed_source)
59
+ stop = group_end(line, start, processed_source)
60
+ return [[], start] unless stop
61
+
62
+ hashes, past = attribute_groups(line, stop + 1, processed_source)
63
+ hashes.unshift([line[start..stop], start]) if line[start] == "{"
64
+ [hashes, past]
65
+ end
66
+
67
+ # The shortest `{...}` that parses as Ruby is a hash; `(...)` and `[...]`
68
+ # end at their balancing bracket.
69
+ def group_end(line, start, processed_source)
70
+ case line[start]
71
+ when "{" then (start...line.length).find { |i| hash_end?(line, start, i, processed_source) }
72
+ when "(", "[" then balanced_end(line, start)
73
+ end
74
+ end
75
+
76
+ def hash_end?(line, start, stop, processed_source)
77
+ line[stop] == "}" && TemplateRubyFragment.valid?(line[start..stop], processed_source)
78
+ end
79
+
80
+ def balanced_end(line, start)
81
+ steps = { line[start] => 1, GROUPS.fetch(line[start]) => -1 }
82
+ depth = 0
83
+ (start...line.length).find { |i| (depth += steps.fetch(line[i], 0)).zero? }
84
+ end
85
+
86
+ def output(line, start)
87
+ match = line.match(OUTPUT, start)
88
+ [match[:body], match.begin(:body)] if match
31
89
  end
32
90
  end
33
91
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "strscan"
3
4
  require_relative "template_ruby_extractor"
4
5
 
5
6
  module Metz
@@ -7,28 +8,103 @@ module Metz
7
8
  # registered with `RuboCop::Runner.ruby_extractors` so view-aware Metz cops
8
9
  # (currently `Metz/ViewsDeepNavigation`) can run against Slim content.
9
10
  #
10
- # Recognises four Slim constructs that carry Ruby:
11
+ # Recognises the Slim constructs that carry Ruby:
11
12
  #
12
- # * `= ruby_expr` - output script (escaped)
13
- # * `== ruby_expr` - output script (raw / unescaped)
14
- # * `- ruby_stmt` - silent script
15
- # * `ruby:` filter - indented block of plain Ruby
13
+ # * `= expr`, `== expr` - output script, bare or after a tag
14
+ # (`p = expr`, `a.link[href=url] == expr`)
15
+ # * `- stmt` - control code, including control openers
16
+ # (`- if cond`, `- items.each do |item|`)
17
+ # * `title=expr` - unquoted Ruby attribute values, bare
18
+ # (`p title=expr`) or wrapped (`a[href=expr]`)
19
+ # * `ruby:` filter - indented block of plain Ruby
16
20
  #
17
- # Each tag's body is handed to RuboCop as its own `ProcessedSource` whose
18
- # offset points at the body's column in the original template. Tags whose
19
- # body is not valid Ruby on its own are silently skipped (we never want to
20
- # surface `Lint/Syntax` from a partial Slim fragment).
21
+ # Quoted attribute values, text, comments, and other filters' bodies
22
+ # (`javascript:`, `css:`, `markdown:`, ...) are not extracted, nor are
23
+ # inline nested tags (`li: a href=expr`) or splat attributes (`*hash`).
24
+ # Every `.slim` file is extracted; each cop's own scope decides which
25
+ # files it checks.
26
+ # Each fragment is handed to RuboCop as its own `ProcessedSource` whose
27
+ # offset points at the fragment's column in the original template;
28
+ # fragments that are not valid Ruby on their own are skipped.
21
29
  module SlimRubyExtractor
22
30
  extend TemplateRubyExtractor
23
31
 
24
- EXPR_LINE = /\A(?<lead>[ \t]*(?:[a-zA-Z][\w-]*|[.#][^\s=]*)?)==?\s(?<body>.*)$/
25
- STMT_LINE = /\A(?<lead>[ \t]*)-\s(?<body>.*)$/
26
- FILTER_LINE = /\A(?<indent>[ \t]*)ruby:[ \t]*$/
32
+ CONTROL_LINE = /\A[ \t]*-[ \t]*(?<body>.*)$/
33
+ TAG = /[ \t]*(?:[a-zA-Z][\w:-]*(?:[.#][\w-]+)*|(?:[.#][\w-]+)+)/
34
+ OUTPUT = /\G[ \t]*==?[<>']*[ \t]*(?<body>.*)$/
35
+ FILTER_LINE = /\A(?<indent>[ \t]*)(?<name>\w+):[ \t]*$/
27
36
 
28
37
  module_function
29
38
 
30
39
  def handles?(path)
31
- File.extname(path.to_s) == ".slim" && ::Metz::FileClassifier.view?(path)
40
+ File.extname(path.to_s) == ".slim"
41
+ end
42
+
43
+ def line_fragments(line, processed_source)
44
+ control = line.match(CONTROL_LINE)
45
+ return [[control[:body], control.begin(:body)]] if control
46
+
47
+ scanner = StringScanner.new(line.chomp)
48
+ attributes = scanner.skip(TAG) ? Attributes.new(scanner, processed_source).fragments : []
49
+ [*attributes, output(scanner)].compact
50
+ end
51
+
52
+ def output(scanner)
53
+ match = scanner.string.match(OUTPUT, scanner.pos)
54
+ [match[:body], match.begin(:body)] if match
55
+ end
56
+
57
+ # Scans the attributes after a Slim tag, leaving the scanner just past
58
+ # them. Like Slim itself, an unquoted value runs to the first space or
59
+ # closing bracket outside nested brackets; the shortest such prefix that
60
+ # parses as Ruby is taken as the value.
61
+ class Attributes
62
+ WRAPPERS = { "[" => "]", "(" => ")", "{" => "}" }.freeze
63
+ UNWRAPPED_NAME = /[ \t]+[\w:@-]+==?/
64
+ WRAPPED_NAME = /[ \t]*[\w:@-]+[ \t]*==?[ \t]*/
65
+ BOOLEANS = /(?:[ \t]*[\w:@-]+(?=[ \t\])}]))*/
66
+ QUOTED = /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/
67
+
68
+ def initialize(scanner, processed_source)
69
+ @scanner = scanner
70
+ @processed_source = processed_source
71
+ @close = WRAPPERS[scanner.peek(1)]
72
+ scanner.getch if @close
73
+ end
74
+
75
+ def fragments
76
+ found = []
77
+ found << value while attribute_name?
78
+ @scanner.skip(/[ \t]*#{Regexp.escape(@close)}/) if @close
79
+ found.compact
80
+ end
81
+
82
+ private
83
+
84
+ def attribute_name?
85
+ @scanner.skip(BOOLEANS) if @close
86
+ @scanner.skip(@close ? WRAPPED_NAME : UNWRAPPED_NAME)
87
+ end
88
+
89
+ def value
90
+ return if @scanner.skip(QUOTED)
91
+
92
+ start = @scanner.pos
93
+ stop = value_end(start)
94
+ @scanner.pos = stop || @scanner.string.length
95
+ [@scanner.string[start...stop], start] if stop
96
+ end
97
+
98
+ def value_end(start)
99
+ string = @scanner.string
100
+ ((start + 1)..string.length).find do |stop|
101
+ delimiter?(string[stop]) && TemplateRubyFragment.valid?(string[start...stop], @processed_source)
102
+ end
103
+ end
104
+
105
+ def delimiter?(char)
106
+ char.nil? || char.match?(@close ? /[ \t\])}]/ : /[ \t]/)
107
+ end
32
108
  end
33
109
  end
34
110
  end
@@ -1,23 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "file_classifier"
3
+ require_relative "template_ruby_fragment"
4
4
 
5
5
  module Metz
6
6
  # Shared iteration backbone for line-based Ruby extractors that target
7
7
  # indentation-driven template languages (HAML, Slim). Concrete extractors
8
- # define three patterns -- an expression line, a statement line, and a
9
- # filter-block start -- and this module walks the raw source line by
10
- # line, hands every matching body to RuboCop as its own ProcessedSource,
11
- # and tracks the byte offset of each body inside the original template
12
- # so offense locations refer back to the source file rather than the
13
- # synthetic snippet.
8
+ # define a filter-block start pattern (`FILTER_LINE`, capturing the filter
9
+ # `name`) and `line_fragments(line, processed_source)`, which returns the
10
+ # `[ruby_source, column]` pairs a single template line carries. Every
11
+ # filter's indented body is consumed, but only a `ruby` filter's body is
12
+ # Ruby; other filters (`javascript`, `css`, `markdown`, ...) yield nothing. This
13
+ # module walks the raw source line by line, hands every fragment to
14
+ # RuboCop as its own ProcessedSource, and tracks the offset of each
15
+ # fragment inside the original template so offense locations refer back
16
+ # to the source file rather than the synthetic snippet.
14
17
  module TemplateRubyExtractor
15
18
  def call(processed_source)
16
19
  path = processed_source.path
17
20
  return nil unless path && handles?(path)
18
21
 
19
22
  snippets = Walker.new(self, processed_source).snippets
20
- snippets << empty_snippet(processed_source) if snippets.empty?
23
+ snippets << TemplateRubyFragment.empty(processed_source) if snippets.empty?
21
24
  snippets
22
25
  end
23
26
 
@@ -27,25 +30,6 @@ module Metz
27
30
  extractors.unshift(entrypoint) unless extractors.include?(entrypoint)
28
31
  end
29
32
 
30
- def empty_snippet(processed_source)
31
- ps = build_processed_source("", processed_source)
32
- { offset: 0, processed_source: ps }
33
- end
34
-
35
- def build_snippet(body, body_offset, processed_source)
36
- return nil if body.strip.empty?
37
-
38
- ps = build_processed_source(body, processed_source)
39
- return nil unless ps.valid_syntax?
40
-
41
- { offset: body_offset, processed_source: ps }
42
- end
43
-
44
- def build_processed_source(body, processed_source)
45
- ruby_version = processed_source.ruby_version || RUBY_VERSION.to_f
46
- RuboCop::ProcessedSource.new(body, ruby_version, processed_source.path)
47
- end
48
-
49
33
  # Walks lines of a template, dispatching each line to the owner module's
50
34
  # match patterns. Holds the running byte offset, the line index, and the
51
35
  # accumulating snippet list so the owner module can stay stateless.
@@ -61,37 +45,33 @@ module Metz
61
45
 
62
46
  def walk
63
47
  @snippets = []
64
- @snippets << next_snippet until @cursor.done?
48
+ @snippets.concat(next_snippets) until @cursor.done?
65
49
  @snippets.compact!
66
50
  end
67
51
 
68
- def next_snippet
52
+ def next_snippets
69
53
  line = @cursor.line
70
54
  filter = line.match(@owner::FILTER_LINE)
71
- return consume_filter(filter) if filter
55
+ return [consume_filter(filter)] if filter
72
56
 
73
- consume_inline(line.match(@owner::EXPR_LINE) || line.match(@owner::STMT_LINE))
57
+ consume_inline(line)
74
58
  end
75
59
 
76
- def consume_inline(match)
77
- snippet = inline_snippet(match)
60
+ def consume_inline(line)
61
+ snippets = @owner.line_fragments(line, @processed_source).map { |body, column| inline_snippet(body, column) }
78
62
  @cursor.advance(1)
79
- snippet
63
+ snippets
80
64
  end
81
65
 
82
- def inline_snippet(match)
83
- return nil if match.nil?
84
-
85
- body_offset = @cursor.offset + match.begin(:body)
86
- @owner.build_snippet(match[:body], body_offset, @processed_source)
66
+ def inline_snippet(body, column)
67
+ TemplateRubyFragment.snippet(body, @cursor.offset + column, @processed_source)
87
68
  end
88
69
 
89
70
  def consume_filter(match)
90
71
  body_offset = @cursor.offset + @cursor.line.length
91
- body_lines = collect_filter_body(match[:indent].length)
92
- snippet = build_filter_snippet(body_lines, body_offset)
93
- @cursor.advance(1 + body_lines.size)
94
- snippet
72
+ body = collect_filter_body(match[:indent].length)
73
+ @cursor.advance(1 + body.size)
74
+ TemplateRubyFragment.snippet(body.join, body_offset, @processed_source) if match[:name] == "ruby"
95
75
  end
96
76
 
97
77
  def collect_filter_body(base_indent)
@@ -110,12 +90,6 @@ module Metz
110
90
  def leading_indent(line)
111
91
  line[/\A[ \t]*/].length
112
92
  end
113
-
114
- def build_filter_snippet(body_lines, body_offset)
115
- return nil if body_lines.empty?
116
-
117
- @owner.build_snippet(body_lines.join, body_offset, @processed_source)
118
- end
119
93
  end
120
94
 
121
95
  # Tracks the running byte offset and line index while walking a template.
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Metz
4
+ # Turns one Ruby fragment found in a view template into a RuboCop snippet
5
+ # whose offset points back at the fragment inside the template. A control
6
+ # opener (`if cond`, `form_with(...) do |f|`) is not valid Ruby on its own,
7
+ # so it is reduced to the expression it evaluates; any other invalid
8
+ # fragment is skipped so partial template code never surfaces `Lint/Syntax`.
9
+ module TemplateRubyFragment
10
+ CONTROL_CONDITION = /\A(?<prefix>\s*(?:if|unless|while|until|elsif|case)\b\s*)(?<expr>.*?)(?:\s+then)?\s*\z/m
11
+ TRAILING_DO_BLOCK = /\A(?<prefix>\s*)(?<expr>.*?)(?<suffix>\s+do\b(?:\s*\|[^|]*\|)?\s*)\z/m
12
+ MAGIC_COMMENT = "# frozen_string_literal: true\n\n"
13
+
14
+ module_function
15
+
16
+ def snippet(body, body_offset, processed_source)
17
+ return if body.strip.empty?
18
+
19
+ source = parse(body, processed_source)
20
+ return { offset: body_offset, processed_source: source } if source.valid_syntax?
21
+
22
+ reduced(body, body_offset, processed_source)
23
+ end
24
+
25
+ def valid?(body, processed_source)
26
+ parse(body, processed_source).valid_syntax?
27
+ end
28
+
29
+ def reduced(body, body_offset, processed_source)
30
+ match = body.match(CONTROL_CONDITION) || body.match(TRAILING_DO_BLOCK)
31
+ source = match && parse("#{MAGIC_COMMENT}#{match[:expr]}\n", processed_source)
32
+ return unless source&.valid_syntax?
33
+
34
+ { offset: body_offset + match.begin(:expr) - MAGIC_COMMENT.length, processed_source: source }
35
+ end
36
+
37
+ def empty(processed_source)
38
+ { offset: 0, processed_source: parse("", processed_source) }
39
+ end
40
+
41
+ # Cops and their correctors read the config and registry off the
42
+ # ProcessedSource, so each fragment carries the template's.
43
+ def parse(body, processed_source)
44
+ ruby_version = processed_source.ruby_version || RUBY_VERSION.to_f
45
+ RuboCop::ProcessedSource.new(body, ruby_version, processed_source.path).tap do |source|
46
+ source.config = processed_source.config
47
+ source.registry = processed_source.registry
48
+ end
49
+ end
50
+ end
51
+ end
@@ -98,6 +98,11 @@ module RuboCop
98
98
  Rails Arel Time Date DateTime File FileUtils Pathname Hash Array String Integer Float
99
99
  Symbol Set SecureRandom JSON YAML URI CGI ERB
100
100
  ].freeze
101
+ VALUE_CONSTANT = /\A[A-Z][A-Z0-9_]*\z/
102
+ DATA_READ_METHODS = %i[
103
+ include? each map fetch [] keys values first size any? empty? length count last key? to_a dig
104
+ sample each_with_index == != < <= > >= <=> + - * / % **
105
+ ].to_set.freeze
101
106
 
102
107
  def initialize(method_node)
103
108
  @method_node = method_node
@@ -115,12 +120,30 @@ module RuboCop
115
120
  attr_reader :method_node, :same_class_constants
116
121
 
117
122
  def record(ordered, const_node)
118
- name = const_node.const_name
123
+ name = collaborator_name(const_node)
119
124
  return if name.nil? || ignored?(const_node, name)
120
125
 
121
126
  ordered[name] ||= const_node
122
127
  end
123
128
 
129
+ # A value constant such as `User::STATUSES` read as data (bare, or the
130
+ # receiver of a `DATA_READ_METHODS` call or operator) is owned by `User`,
131
+ # so it counts toward `User` rather than as its own collaborator.
132
+ def collaborator_name(const_node)
133
+ name = const_node.const_name
134
+ owner, separator, last = name.to_s.rpartition("::")
135
+ return name if separator.empty? || owner.empty? || !last.match?(VALUE_CONSTANT)
136
+
137
+ read_as_data?(const_node) ? owner : name
138
+ end
139
+
140
+ def read_as_data?(const_node)
141
+ parent = const_node.parent
142
+ return true unless parent&.type?(:send, :csend) && parent.receiver.equal?(const_node)
143
+
144
+ DATA_READ_METHODS.include?(parent.method_name)
145
+ end
146
+
124
147
  def ignored?(const_node, name)
125
148
  nested_inside_const?(const_node) ||
126
149
  rescue_exception_class?(const_node) ||
@@ -175,9 +198,13 @@ module RuboCop
175
198
  # Exception classes at `rescue`/`raise`/`fail` sites, constants owned by
176
199
  # the controller class, and core framework/stdlib constants do not
177
200
  # count. Multiple references
178
- # to the same constant count once. The cop is path-classified through
179
- # `Metz::FileClassifier.controller?` and is silent on any file that is
180
- # not under `app/controllers/`.
201
+ # to the same constant count once, and a value constant read as data
202
+ # (`User::STATUSES`, `User::STATUSES.include?(x)`) counts toward its
203
+ # owner (`User`). By default the cop is path-classified
204
+ # through `Metz::FileClassifier.controller?` and is silent on any file
205
+ # that is not under an `app/controllers/` directory. An `Include`
206
+ # that still lists the default pattern keeps that scope and adds its other
207
+ # patterns; one that drops it replaces the scope. `Exclude` always applies.
181
208
  class ControllersTooManyDirectCollaborators < RuboCop::Cop::Base
182
209
  extend ::Metz::CopMetadata
183
210
 
@@ -202,14 +229,32 @@ module RuboCop
202
229
  end
203
230
 
204
231
  def relevant_file?(file)
205
- return super if file.nil? || file.empty? || file == "(string)"
232
+ return super if file.nil? || file.empty? || file == "(string)" || !default_scope_kept?
233
+
234
+ default_scope_file?(file) ||
235
+ (file_name_matches_any?(file, "Include", false) && !file_name_matches_any?(file, "Exclude", false))
236
+ end
206
237
 
207
- !file_name_matches_any?(file, "Exclude", false) &&
208
- ::Metz::FileClassifier.controller?(file)
238
+ # The classifier-based default scope minus Exclude, ignoring any
239
+ # configured Include.
240
+ def default_scope_file?(file)
241
+ !file_name_matches_any?(file, "Exclude", false) && ::Metz::FileClassifier.controller?(file)
209
242
  end
210
243
 
211
244
  private
212
245
 
246
+ # The default Include glob cannot match nested app roots (engines,
247
+ # monorepos), so the classifier stands in for it while the configured
248
+ # Include still lists every default pattern. An Include inherited from
249
+ # a .rubocop.yml in a parent directory is rewritten by RuboCop relative
250
+ # to that directory, so it never equals the default pattern and counts
251
+ # as a replacement, as it does for stock cops.
252
+ def default_scope_kept?
253
+ configured = cop_config["Include"]
254
+ default = RuboCop::ConfigLoader.default_configuration.for_cop(cop_name)["Include"]
255
+ configured.nil? || (default && (default - configured).empty?)
256
+ end
257
+
213
258
  def collect_collaborators(method_node)
214
259
  ControllerCollaboratorCollector.new(method_node).call
215
260
  end
@@ -59,7 +59,7 @@ module RuboCop
59
59
 
60
60
  def collect_chain(links, start)
61
61
  current = start
62
- while current
62
+ until current.nil? || operator_send?(current)
63
63
  links.unshift(current) if current.type?(:send, :csend)
64
64
  current = inner_node(current)
65
65
  end
@@ -72,7 +72,7 @@ module RuboCop
72
72
  end
73
73
 
74
74
  def skip_link?(send_node)
75
- operator_send?(send_node) || send_node.setter_method?
75
+ send_node.setter_method?
76
76
  end
77
77
 
78
78
  def outermost_skippable?(node)
@@ -80,13 +80,16 @@ module RuboCop
80
80
  end
81
81
 
82
82
  def operator_send?(node)
83
- node.type?(:send, :csend) && TypeInference.operator?(node.method_name)
83
+ return false unless node.type?(:send, :csend)
84
+
85
+ TypeInference.operator?(node.method_name) || OperatorMethods.unary_operator?(node.method_name)
84
86
  end
85
87
 
88
+ # An operator ends a chain: the chain beneath it is measured on its own.
86
89
  def part_of_outer_chain?(node)
87
90
  unit = wrapping_block(node) || node
88
91
  parent = unit.parent
89
- parent&.type?(:send, :csend) && parent.receiver.equal?(unit)
92
+ parent&.type?(:send, :csend) && parent.receiver.equal?(unit) && !operator_send?(parent)
90
93
  end
91
94
 
92
95
  def wrapping_block(node)
@@ -30,20 +30,20 @@ module RuboCop
30
30
  "keep a single public entry (max %<max>d, excluding %<allowed>s)."
31
31
 
32
32
  def on_class(node)
33
- return unless operation_file?
34
-
35
33
  public_names = api_names(node)
36
34
  return if public_names.size <= max_public_methods
37
35
 
38
36
  add_offense(node.identifier, message: offense_message(public_names))
39
37
  end
40
38
 
41
- private
39
+ def relevant_file?(file)
40
+ return super if file.nil? || file.empty? || file == "(string)" || cop_config["Include"]
42
41
 
43
- def operation_file?
44
- ::Metz::FileClassifier.operation?(processed_source.file_path)
42
+ !file_name_matches_any?(file, "Exclude", false) && ::Metz::FileClassifier.operation?(file)
45
43
  end
46
44
 
45
+ private
46
+
47
47
  def api_names(node)
48
48
  PublicApiMethods.new(node, allowed_methods: allowed_methods).names
49
49
  end
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Metz
6
- # Provides a canonical predicate for operator method symbols.
6
+ # Provides the canonical predicates for binary and unary operator method symbols.
7
7
  # Extracted from Metz/DemeterTrainWreck's TypeInference module
8
8
  # so testing cops can use it without coupling to DemeterTrainWreck.
9
9
  module OperatorMethods
@@ -12,12 +12,17 @@ module RuboCop
12
12
  %i[== != < > <= >= <=> === =~ !~] +
13
13
  %i[& | ^ << >>]
14
14
  ).to_set.freeze
15
+ UNARY_OPERATOR_METHODS = %i[! -@ +@ ~].to_set.freeze
15
16
 
16
17
  module_function
17
18
 
18
19
  def operator?(method)
19
20
  OPERATOR_METHODS.include?(method)
20
21
  end
22
+
23
+ def unary_operator?(method)
24
+ UNARY_OPERATOR_METHODS.include?(method)
25
+ end
21
26
  end
22
27
  end
23
28
  end
@@ -10,9 +10,11 @@ module RuboCop
10
10
  # traverse the object graph deeper than `MaxChainLength`. Reuses
11
11
  # `Metz/DemeterTrainWreck`'s chain walker and value-object skip logic,
12
12
  # so a chain like `name.upcase.strip.split(' ').first` (every link a
13
- # recognised value-object call) stays silent. Path-classified through
14
- # `Metz::FileClassifier.view?`: a deep chain inside an `.erb` file
15
- # outside `app/views/` will not fire.
13
+ # recognised value-object call) stays silent. By default path-classified
14
+ # through `Metz::FileClassifier.view?`: a deep chain inside an `.erb` file
15
+ # outside an `app/views/` directory will not fire. An `Include` that
16
+ # still lists the default pattern keeps that scope and adds its other
17
+ # patterns; one that drops it replaces the scope. `Exclude` always applies.
16
18
  # DDR: docs/ddrs/2026-06-24-views-deep-navigation-inherits-demeter.md
17
19
  # explains why this specialization uses inheritance instead of composition.
18
20
  class ViewsDeepNavigation < DemeterTrainWreck
@@ -39,14 +41,32 @@ module RuboCop
39
41
  end
40
42
 
41
43
  def relevant_file?(file)
42
- return super if file.nil? || file.empty? || file == "(string)"
44
+ return super if file.nil? || file.empty? || file == "(string)" || !default_scope_kept?
43
45
 
44
- !file_name_matches_any?(file, "Exclude", false) &&
45
- ::Metz::FileClassifier.view?(file)
46
+ default_scope_file?(file) ||
47
+ (file_name_matches_any?(file, "Include", false) && !file_name_matches_any?(file, "Exclude", false))
48
+ end
49
+
50
+ # The classifier-based default scope minus Exclude, ignoring any
51
+ # configured Include.
52
+ def default_scope_file?(file)
53
+ !file_name_matches_any?(file, "Exclude", false) && ::Metz::FileClassifier.view?(file)
46
54
  end
47
55
 
48
56
  private
49
57
 
58
+ # The default Include glob cannot match nested app roots (engines,
59
+ # monorepos), so the classifier stands in for it while the configured
60
+ # Include still lists every default pattern. An Include inherited from
61
+ # a .rubocop.yml in a parent directory is rewritten by RuboCop relative
62
+ # to that directory, so it never equals the default pattern and counts
63
+ # as a replacement, as it does for stock cops.
64
+ def default_scope_kept?
65
+ configured = cop_config["Include"]
66
+ default = RuboCop::ConfigLoader.default_configuration.for_cop(cop_name)["Include"]
67
+ configured.nil? || (default && (default - configured).empty?)
68
+ end
69
+
50
70
  def max
51
71
  cop_config["MaxChainLength"] || 3
52
72
  end
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "lint_roller"
4
- require "pathname"
5
4
 
6
5
  require_relative "version"
7
6
 
@@ -2,6 +2,6 @@
2
2
 
3
3
  module RuboCop
4
4
  module Metz
5
- VERSION = "0.6.0"
5
+ VERSION = "0.7.0"
6
6
  end
7
7
  end
data/rubocop-metz.gemspec CHANGED
@@ -14,7 +14,7 @@ Gem::Specification.new do |spec|
14
14
  spec.homepage = "https://github.com/fuentesjr/metz-scan"
15
15
  spec.license = "MIT"
16
16
 
17
- spec.required_ruby_version = ">= 3.3"
17
+ spec.required_ruby_version = ">= 4.0"
18
18
 
19
19
  spec.metadata["source_code_uri"] = spec.homepage
20
20
  spec.metadata["documentation_uri"] = "#{spec.homepage}/blob/main/README.md"
@@ -23,6 +23,7 @@ Gem::Specification.new do |spec|
23
23
  spec.metadata["github_repo"] = "ssh://github.com/fuentesjr/metz-scan"
24
24
  spec.metadata["github_package_uri"] = "https://github.com/users/fuentesjr/packages/rubygems/package/rubocop-metz"
25
25
  spec.metadata["default_lint_roller_plugin"] = "RuboCop::Metz::Plugin"
26
+ spec.metadata["rubygems_mfa_required"] = "true"
26
27
 
27
28
  # Resolve files from the gemspec directory so evaluation is CWD-independent.
28
29
  # Do not raise when the entrypoint is absent: Dependabot evaluates gemspecs in
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubocop-metz
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Salvador Fuentes Jr
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-10-04 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: lint_roller
@@ -67,6 +67,7 @@ files:
67
67
  - lib/metz/haml_ruby_extractor.rb
68
68
  - lib/metz/slim_ruby_extractor.rb
69
69
  - lib/metz/template_ruby_extractor.rb
70
+ - lib/metz/template_ruby_fragment.rb
70
71
  - lib/rubocop-metz.rb
71
72
  - lib/rubocop/cop/metz/classes_too_long.rb
72
73
  - lib/rubocop/cop/metz/controllers_too_many_direct_collaborators.rb
@@ -99,6 +100,7 @@ metadata:
99
100
  github_repo: ssh://github.com/fuentesjr/metz-scan
100
101
  github_package_uri: https://github.com/users/fuentesjr/packages/rubygems/package/rubocop-metz
101
102
  default_lint_roller_plugin: RuboCop::Metz::Plugin
103
+ rubygems_mfa_required: 'true'
102
104
  rdoc_options: []
103
105
  require_paths:
104
106
  - lib
@@ -106,14 +108,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
106
108
  requirements:
107
109
  - - ">="
108
110
  - !ruby/object:Gem::Version
109
- version: '3.3'
111
+ version: '4.0'
110
112
  required_rubygems_version: !ruby/object:Gem::Requirement
111
113
  requirements:
112
114
  - - ">="
113
115
  - !ruby/object:Gem::Version
114
116
  version: '0'
115
117
  requirements: []
116
- rubygems_version: 3.6.2
118
+ rubygems_version: 4.0.20
117
119
  specification_version: 4
118
120
  summary: Sandi-Metz-inspired RuboCop cops.
119
121
  test_files: []