rubocop-metz 0.5.3 → 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: 38eb7e859b0bf45c9f80e8838678713d2aaedb5f18409eb802f53c0489fec544
4
- data.tar.gz: 2972b51623d4c6027735b8a3cd9a1b85bb575a1778dd444f661e7f1bc7c37bf1
3
+ metadata.gz: 254fcc6071ff08ba5fac392e60bdfe75531f6e41b7d180a6fb833d2e11825c55
4
+ data.tar.gz: 4dc301e32f9805313fd68cfc8c7d415d946bf8ebc03d0067837f3994323cd827
5
5
  SHA512:
6
- metadata.gz: 68746f49ee4469e0f23e22eb8020ac3a6cdfbc5e117d6f524fcb6f1c88c95e6f6362bed07d6bf2e5f8896c4e3ea6f6b0ad8f02461366bd045b83348aadb54140
7
- data.tar.gz: 7a242eacde2feca2b19fb116391f42923b59e64b0273432cfc7022eb33e94c5164cb8e1a3e0a122faca561c086d94aabc10cd3f2e12bd7848fa9e47252d2e302
6
+ metadata.gz: 0b8cbca1694e4e1b5f7f4cdf631c0a99bd0fb054242dd5e5e96feab03c867bee3f2bfaac34038c58caa18f318489887680210b5f27b6e8dbdbe47f5e807ef218
7
+ data.tar.gz: 7865e226ade783613d45f16ae841ce34665a1b9f130330abc9e27df885541cfd52268cae2bb88a472fc63aba7103bd25476c7fe32e4fc2b62be1bb52a3946561
data/config/default.yml CHANGED
@@ -57,6 +57,43 @@ Metz/DemeterTrainWreck:
57
57
  - 'db/migrate/**/*'
58
58
  VersionAdded: '0.1'
59
59
 
60
+ Metz/TestReachesPrivate:
61
+ Description: 'Flags tests that reach past the public interface with send/__send__ and a literal method name.'
62
+ Enabled: false
63
+ Severity: refactor
64
+ Include:
65
+ - '**/*_test.rb'
66
+ - '**/test_*.rb'
67
+ - '**/*_spec.rb'
68
+ AllowedMethods:
69
+ - define_method
70
+ - remove_const
71
+ - include
72
+ - extend
73
+ - prepend
74
+ - alias_method
75
+ AllowedReceivers: []
76
+ VersionAdded: '0.6'
77
+
78
+ Metz/TestAssertsOnInternals:
79
+ Description: 'Flags tests that assert on internal state via instance_variable_get/_set or Rails controller-test assigns.'
80
+ Enabled: false
81
+ Severity: refactor
82
+ Include:
83
+ - '**/*_test.rb'
84
+ - '**/test_*.rb'
85
+ - '**/*_spec.rb'
86
+ AllowedReceivers: []
87
+ VersionAdded: '0.6'
88
+
89
+ Metz/TestStubsSubject:
90
+ Description: 'Flags RSpec tests that stub or mock the subject under test instead of its collaborators.'
91
+ Enabled: false
92
+ Severity: refactor
93
+ Include:
94
+ - '**/*_spec.rb'
95
+ VersionAdded: '0.6'
96
+
60
97
  Metz/ControllersTooManyDirectCollaborators:
61
98
  Description: 'Flags Rails controller actions that reach into more than MaxCollaborators distinct collaborator constants.'
62
99
  Enabled: true
@@ -66,11 +103,86 @@ Metz/ControllersTooManyDirectCollaborators:
66
103
  - 'app/controllers/**/*.rb'
67
104
  VersionAdded: '0.1'
68
105
 
106
+ Metz/OperationsTooManyPublicMethods:
107
+ Description: >-
108
+ Flags classes under app/services or app/operations that expose more than
109
+ MaxPublicMethods public methods (excluding AllowedMethods such as initialize).
110
+ Enabled: true
111
+ Severity: refactor
112
+ MaxPublicMethods: 1
113
+ AllowedMethods:
114
+ - initialize
115
+ Include:
116
+ - 'app/services/**/*.rb'
117
+ - 'app/operations/**/*.rb'
118
+ VersionAdded: '0.6'
119
+
120
+ Metz/GodServiceClass:
121
+ Description: >-
122
+ Flags *Service classes that expose more than MaxPublicMethods public methods
123
+ (excluding AllowedMethods such as initialize) — god-service / multi-use bags.
124
+ Enabled: true
125
+ Severity: refactor
126
+ MaxPublicMethods: 1
127
+ AllowedMethods:
128
+ - initialize
129
+ VersionAdded: '0.6'
130
+
69
131
  Metz/ViewsDeepNavigation:
70
132
  Description: 'Flags Rails view templates whose ERB/HAML/SLIM expressions traverse the object graph deeper than MaxChainLength.'
71
133
  Enabled: true
72
134
  Severity: refactor
73
135
  MaxChainLength: 3
136
+ AllowedReceivers: []
74
137
  Include:
75
138
  - 'app/views/**/*.{erb,haml,slim}'
76
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,7 +20,9 @@ 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}
25
+ OPERATION_PATTERN = %r{(?:\A|/)app/(?:services|operations)/[^\0]+\.rb\z}
24
26
 
25
27
  module_function
26
28
 
@@ -32,10 +34,21 @@ module Metz
32
34
  normalize(path).match?(VIEW_PATTERN)
33
35
  end
34
36
 
37
+ def template?(path)
38
+ normalize(path).match?(TEMPLATE_PATTERN)
39
+ end
40
+
35
41
  def model?(path)
36
42
  normalize(path).match?(MODEL_PATTERN)
37
43
  end
38
44
 
45
+ # Application-operation homes (legacy `app/services` and preferred
46
+ # `app/operations`). Path alone does not legitimize a class; it only
47
+ # scopes shape cops such as OperationsTooManyPublicMethods.
48
+ def operation?(path)
49
+ normalize(path).match?(OPERATION_PATTERN)
50
+ end
51
+
39
52
  # Windows-style paths arrive with backslash separators when the caller is
40
53
  # an editor running on Windows or a CI step that shells out via `cmd.exe`.
41
54
  # Normalize to forward slashes so the regexes below stay POSIX-shaped.
@@ -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.