metz-scan 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.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/lib/metz_scan/analyzers/package_map.rb +1 -1
  3. data/lib/metz_scan/analyzers/test_calls_private_method/receiver_resolution.rb +3 -3
  4. data/lib/metz_scan/analyzers/test_calls_private_method/scope_resolution.rb +1 -1
  5. data/lib/metz_scan/commands/report.rb +16 -3
  6. data/lib/metz_scan/commands/scan/auto_fix.rb +49 -51
  7. data/lib/metz_scan/commands/scan/check_failure.rb +42 -0
  8. data/lib/metz_scan/commands/scan/config_disables.rb +83 -0
  9. data/lib/metz_scan/commands/scan/config_exclusions.rb +66 -30
  10. data/lib/metz_scan/commands/scan/exclude_entries.rb +5 -0
  11. data/lib/metz_scan/commands/scan/exclude_entry_locator.rb +15 -5
  12. data/lib/metz_scan/commands/scan/exclude_provenance.rb +7 -2
  13. data/lib/metz_scan/commands/scan/execution_config_store.rb +142 -0
  14. data/lib/metz_scan/commands/scan/ignored_cli_options_note.rb +35 -0
  15. data/lib/metz_scan/commands/scan/inherited_include_rewriter.rb +43 -0
  16. data/lib/metz_scan/commands/scan/inline_directive_locator.rb +38 -11
  17. data/lib/metz_scan/commands/scan/json_guidance.rb +81 -0
  18. data/lib/metz_scan/commands/scan/offense_extractor.rb +29 -7
  19. data/lib/metz_scan/commands/scan/path_scoped_include_note.rb +73 -0
  20. data/lib/metz_scan/commands/scan/project_analyzer_offenses.rb +21 -5
  21. data/lib/metz_scan/commands/scan/project_analyzer_runner.rb +21 -23
  22. data/lib/metz_scan/commands/scan/project_config_scope.rb +85 -28
  23. data/lib/metz_scan/commands/scan/rubocop_failure.rb +38 -0
  24. data/lib/metz_scan/commands/scan/rubocop_invocation.rb +141 -0
  25. data/lib/metz_scan/commands/scan/runner.rb +103 -49
  26. data/lib/metz_scan/commands/scan/sarif_rule_descriptors.rb +6 -24
  27. data/lib/metz_scan/commands/scan/suppression_ledger.rb +51 -14
  28. data/lib/metz_scan/commands/scan/suppression_ledger_formatter.rb +7 -1
  29. data/lib/metz_scan/commands/scan/target_ruby_version.rb +3 -2
  30. data/lib/metz_scan/commands/scan.rb +43 -21
  31. data/lib/metz_scan/project_index/rubydex_backend/method_visibility.rb +3 -0
  32. data/lib/metz_scan/version.rb +1 -1
  33. data/metz-scan.gemspec +9 -2
  34. metadata +16 -15
  35. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/artifact_writer.rb +0 -51
  36. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/baseline_delta.rb +0 -231
  37. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/collaborators.rb +0 -76
  38. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/markdown_renderer.rb +0 -353
  39. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/readiness_catalog.rb +0 -127
  40. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/summary.rb +0 -333
  41. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/target_set.rb +0 -139
  42. data/lib/metz_scan/calibration/project_analyzer_evidence_runner.rb +0 -64
  43. data/lib/metz_scan/calibration/rubydex_drift_formatter.rb +0 -91
@@ -1,17 +1,30 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "pathname"
4
3
  require "rubocop"
5
4
 
6
5
  require "metz_scan/commands/scan/exclude_provenance"
6
+ require "metz_scan/commands/scan/inherited_include_rewriter"
7
+ require "metz_scan/commands/scan/path_scoped_include_note"
7
8
 
8
9
  module MetzScan
9
10
  module Commands
10
11
  class Scan
11
12
  # DDR: docs/ddrs/2026-07-08-rubocop-scope-only-config.md explains why default mode bypasses ConfigStore here.
12
13
  module ProjectConfigScope
13
- SCOPE_KEYS = %w[Include Exclude Includes Excludes].freeze
14
+ SCOPE_KEYS = %w[Include Exclude Includes Excludes inherit_mode].freeze
15
+ # ExcludeProvenance stamps ENABLED_SOURCE beside each project-written
16
+ # `Enabled`, so inheritance resolves the file that wrote the winning
17
+ # value along with the value itself.
18
+ ENABLED_SOURCE = "MetzScanEnabledSource"
19
+ COP_KEYS = (SCOPE_KEYS + ["Enabled", ENABLED_SOURCE]).freeze
14
20
  ALL_COPS_PROJECT_KEYS = (SCOPE_KEYS + %w[RubyInterpreters TargetRubyVersion]).freeze
21
+
22
+ # RuboCop evaluates ERB in `.rubocop.yml`, which can raise anything, even a SyntaxError.
23
+ class LoadFailure < RuboCop::Error; end
24
+
25
+ # Not a RuboCop department: plain rubocop rejects the bare key, so only
26
+ # an analyzer's own `MetzProject/<Rule>` key scopes or disables it.
27
+ ANALYZER_DEPARTMENT = "MetzProject"
15
28
  DEFAULT_FILE = RuboCop::ConfigLoader::DEFAULT_FILE
16
29
 
17
30
  module_function
@@ -35,6 +48,14 @@ module MetzScan
35
48
  @unresolved_inherit_gems = []
36
49
  end
37
50
 
51
+ # The default-mode stderr notes printed after a successful scan of
52
+ # `files`. Lives here, not in Runner, because Runner is at its
53
+ # Metrics/ModuleLength limit.
54
+ def warn_scope_notes(files, stderr, exec_store: nil)
55
+ PathScopedIncludeNote.print_note(files, stderr, exec_store: exec_store)
56
+ warn_unresolved_inherit_gems(stderr)
57
+ end
58
+
38
59
  # Default mode drops file-scope Exclude from an inherit_gem whose gem
39
60
  # isn't installed (docs/ddrs/2026-07-08-rubocop-scope-only-config.md);
40
61
  # this turns that silent degrade into a one-line stderr note per gem.
@@ -49,6 +70,15 @@ module MetzScan
49
70
  "its file-scope Exclude is not applied — install the gem or use --all-cops"
50
71
  end
51
72
 
73
+ def ensure_metz_defaults_loaded
74
+ defaults = RuboCop::ConfigLoader.default_configuration
75
+ return defaults if defaults.key?("Metz/ClassesTooLong")
76
+
77
+ require "rubocop-metz"
78
+ RuboCop::Plugin.integrate_plugins(RuboCop::Config.new, [RuboCop::Metz::Plugin])
79
+ defaults
80
+ end
81
+
52
82
  class TargetRubyVersion
53
83
  def initialize(paths, store: ConfigStore.new, loader: ConfigLoader.new)
54
84
  @paths = paths
@@ -57,9 +87,10 @@ module MetzScan
57
87
  end
58
88
 
59
89
  def version
60
- config.target_ruby_version
61
- rescue RuboCop::Error, Psych::Exception
62
- nil
90
+ target = RuboCop::TargetRuby.new(config)
91
+ return target.version if target.supported?
92
+
93
+ raise RuboCop::ValidationError, "unsupported Ruby version #{target.version} in #{target.source}"
63
94
  end
64
95
 
65
96
  private
@@ -104,14 +135,44 @@ module MetzScan
104
135
 
105
136
  def for_dir(dir)
106
137
  path = @path_cache[dir] ||= RuboCop::ConfigLoader.configuration_file_for(dir)
107
- @object_cache[path] ||= @loader.load(path)
138
+ @object_cache[path] ||= load_config(path)
108
139
  end
109
140
 
110
141
  # The project Exclude entry (with its source config file) that scopes
111
142
  # the cop off `file`, or nil when only a stock default does.
112
143
  def applied_exclude(badge, file)
113
144
  config = for_file(file)
114
- @loader.provenance.entries_for(config).applied(config, badge, file)
145
+ entry = @loader.provenance.entries_for(config).applied(config, badge, file)
146
+ entry unless entry&.key == ANALYZER_DEPARTMENT
147
+ end
148
+
149
+ def project_exclude?(config, key)
150
+ @loader.provenance.entries_for(config).any_for?(key)
151
+ end
152
+
153
+ # The project config file and key (the cop or its department) whose
154
+ # `Enabled: false` turns `cop_name` off for `file`, or nil when the
155
+ # project leaves it enabled.
156
+ def disabling_config(cop_name, file)
157
+ config = for_file(file)
158
+ return unless config.for_cop(cop_name)["Enabled"] == false
159
+
160
+ key = enabling_keys(cop_name).find { |name| config.to_h.dig(name, ENABLED_SOURCE) }
161
+ [config.to_h.dig(key, ENABLED_SOURCE), key] if key
162
+ end
163
+
164
+ def enabling_keys(cop_name)
165
+ department = cop_name.rpartition("/").first
166
+ department == ANALYZER_DEPARTMENT ? [cop_name] : [cop_name, department]
167
+ end
168
+
169
+ private
170
+
171
+ # Everything raised while loading a project config is a configuration failure.
172
+ def load_config(path)
173
+ @loader.load(path)
174
+ rescue StandardError, ScriptError => e
175
+ raise LoadFailure, e.message
115
176
  end
116
177
  end
117
178
 
@@ -120,33 +181,39 @@ module MetzScan
120
181
 
121
182
  def default_for(dir)
122
183
  path = File.join(File.expand_path(dir), ".rubocop.yml")
123
- config = RuboCop::Config.new({}, path)
124
- RuboCop::ConfigLoader.merge_with_default(config, path)
184
+ merge_with_default(RuboCop::Config.new({}, path), path)
125
185
  end
126
186
 
127
187
  def load(path)
128
- return RuboCop::ConfigLoader.default_configuration if path == DEFAULT_FILE
188
+ return ProjectConfigScope.ensure_metz_defaults_loaded if path == DEFAULT_FILE
129
189
 
130
190
  config = RuboCop::Config.new(scope_hash(path), path)
131
191
  config.deprecation_check { |_message| nil }
132
192
  provenance.make_excludes_absolute(config)
133
- RuboCop::ConfigLoader.merge_with_default(config, path)
193
+ merge_with_default(config, path)
134
194
  end
135
195
 
136
196
  private
137
197
 
198
+ def merge_with_default(config, path)
199
+ ProjectConfigScope.ensure_metz_defaults_loaded
200
+ RuboCop::ConfigLoader.merge_with_default(config, path)
201
+ end
202
+
138
203
  def scope_hash(path, seen = [])
139
204
  absolute_path = File.expand_path(path)
140
205
  return {} if seen.include?(absolute_path)
141
206
 
142
207
  raw_hash = provenance.load_yaml_configuration(absolute_path)
143
208
  inherited = inherited_scope_hash(raw_hash, absolute_path, [*seen, absolute_path])
144
- merge(inherited, local_scope_hash(raw_hash), raw_hash["inherit_mode"])
209
+ merge(inherited, local_scope_hash(raw_hash), raw_hash["inherit_mode"] || inherited["inherit_mode"])
145
210
  end
146
211
 
147
212
  def inherited_scope_hash(raw_hash, path, seen)
148
213
  inherited_paths(raw_hash, path).each_with_object({}) do |inherited_path, merged|
149
- merged.replace(merge(merged, scope_hash(inherited_path, seen), raw_hash["inherit_mode"]))
214
+ child = InheritedIncludeRewriter.rewrite(scope_hash(inherited_path, seen), inherited_path, path)
215
+ mode = raw_hash["inherit_mode"] || child["inherit_mode"] || merged["inherit_mode"]
216
+ merged.replace(merge(merged, child, mode))
150
217
  end
151
218
  end
152
219
 
@@ -157,9 +224,7 @@ module MetzScan
157
224
  resolver.merge(base_hash, derived_hash, inherit_mode: inherit_mode || {})
158
225
  end
159
226
 
160
- def resolver
161
- @resolver ||= RuboCop::ConfigLoaderResolver.new
162
- end
227
+ def resolver = @resolver ||= RuboCop::ConfigLoaderResolver.new
163
228
 
164
229
  def inherited_paths(raw_hash, path)
165
230
  gem_inherited_paths(raw_hash["inherit_gem"], path) + local_inherited_paths(raw_hash["inherit_from"], path)
@@ -222,7 +287,7 @@ module MetzScan
222
287
  end
223
288
 
224
289
  def scoped_settings(key, value)
225
- keys = key == "AllCops" ? ALL_COPS_PROJECT_KEYS : SCOPE_KEYS
290
+ keys = key == "AllCops" ? ALL_COPS_PROJECT_KEYS : COP_KEYS
226
291
  value.each_with_object({}) do |(setting, setting_value), scope|
227
292
  scope[setting] = copy_value(setting_value) if keys.include?(setting)
228
293
  end
@@ -235,17 +300,9 @@ module MetzScan
235
300
  value
236
301
  end
237
302
 
238
- def remote_config?(path)
239
- path.to_s.start_with?("http://", "https://")
240
- end
241
-
242
- def absolute_path?(path)
243
- Pathname.new(path.to_s).absolute?
244
- end
245
-
246
- def glob_path?(path)
247
- path.match?(/[*?{}\[\]]/)
248
- end
303
+ def remote_config?(path) = path.to_s.start_with?("http://", "https://")
304
+ def absolute_path?(path) = Pathname.new(path.to_s).absolute?
305
+ def glob_path?(path) = path.match?(/[*?{}\[\]]/)
249
306
  end
250
307
  end
251
308
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MetzScan
4
+ module Commands
5
+ class Scan
6
+ # Decides whether an in-process RuboCop run failed and describes why. RuboCop exits 1
7
+ # for offenses and for recorded errors alike, so the error lines it warns tell them apart:
8
+ # a cop crash or an autocorrect that never converges. Other stderr output, such as the
9
+ # pending-cops notice, is not an error. Matching stops at an ANSI escape, so color is harmless.
10
+ module RubocopFailure
11
+ RECORDED_ERROR = /(?:An error occurred while|Infinite loop detected in) [^\e\n]+/
12
+ # RuboCop prints this notice before any error raised while loading nested configs or files.
13
+ PENDING_COPS_NOTICE = %r{\A.*?docs\.rubocop\.org/rubocop/versioning\.html[^\n]*\n}m
14
+
15
+ module_function
16
+
17
+ def failed?(result)
18
+ ![0, 1].include?(result.status) || recorded_errors(result).any?
19
+ end
20
+
21
+ def message(result)
22
+ errors = recorded_errors(result)
23
+ errors.empty? ? output_message(result) : errors.join("; ")
24
+ end
25
+
26
+ def recorded_errors(result)
27
+ result.stderr.scan(RECORDED_ERROR).uniq
28
+ end
29
+
30
+ def output_message(result)
31
+ detail = Runner.concise_message(result.stderr.sub(PENDING_COPS_NOTICE, ""))
32
+ detail = Runner.concise_message(result.stdout) if detail.empty?
33
+ detail.empty? ? "RuboCop exited with status #{result.status} without JSON output" : detail
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubocop"
4
+ require "stringio"
5
+
6
+ require "metz_scan/commands/scan/execution_config_store"
7
+ require "metz_scan/commands/scan/project_config_scope"
8
+
9
+ module MetzScan
10
+ module Commands
11
+ class Scan
12
+ # Invokes RuboCop::Runner directly so RuboCop::Options#parse, `.rubocop`,
13
+ # and `RUBOCOP_OPTS` are never consulted in any scan mode.
14
+ module RuboCopInvocation
15
+ RUBOCOP_STATE_TARGETS = {
16
+ RuboCop::ConfigLoader => %i[
17
+ debug ignore_parent_exclusion ignore_unrecognized_cops disable_pending_cops
18
+ enable_pending_cops enabled_by_default disabled_by_default preview
19
+ ].freeze,
20
+ RuboCop::PendingCopsReporter => %i[disable_pending_cops enable_pending_cops].freeze
21
+ }.freeze
22
+
23
+ module_function
24
+
25
+ def scan(paths, all_cops:, store: nil)
26
+ run(paths, options: scan_options(all_cops), config_store: config_store(all_cops, store), all_cops: all_cops)
27
+ end
28
+
29
+ def auto_fix(paths, options:, report_path:, store: nil)
30
+ all_cops = options.all_cops
31
+ store_arg = config_store(all_cops, store, honor_suppressions: !all_cops)
32
+ run(paths, options: auto_fix_options(options, report_path), config_store: store_arg, all_cops: all_cops)
33
+ end
34
+
35
+ def run(paths, options:, config_store:, all_cops: false)
36
+ Runner.require_metz_plugin
37
+ ProjectConfigScope.ensure_metz_defaults_loaded
38
+ capture_runner { run_in_process(paths, options, config_store, all_cops) }
39
+ end
40
+
41
+ def capture_runner(&)
42
+ out = StringIO.new
43
+ err = StringIO.new
44
+ status = Runner.with_redirected_io(out, err, &)
45
+ Runner::Result.new(stdout: out.string, stderr: err.string, status: status)
46
+ end
47
+
48
+ def run_in_process(paths, options, config_store, all_cops)
49
+ rescue_runner_errors do
50
+ with_isolated_rubocop_state(options[:disable_pending_cops]) do
51
+ run_configured(paths, options, config_store, all_cops)
52
+ end
53
+ end
54
+ end
55
+
56
+ def rescue_runner_errors
57
+ yield
58
+ rescue StandardError, SyntaxError, LoadError => e
59
+ warn(e.message)
60
+ RuboCop::CLI::STATUS_ERROR
61
+ end
62
+
63
+ def run_configured(paths, options, config_store, all_cops)
64
+ configure_cache_root(config_store)
65
+ warn_pending_cops(config_store) if all_cops && !options[:disable_pending_cops]
66
+ execute_runner(paths, options, config_store)
67
+ end
68
+
69
+ def execute_runner(paths, options, config_store)
70
+ runner = RuboCop::Runner.new(options, config_store)
71
+ all_passed = runner.run(paths)
72
+ report_problems(runner)
73
+ runner_status(runner, all_passed)
74
+ end
75
+
76
+ def report_problems(runner)
77
+ runner.warnings.each { |warning| warn(warning) }
78
+ runner.errors.each { |error| warn(error) }
79
+ end
80
+
81
+ def runner_status(runner, all_passed)
82
+ return RuboCop::CLI::STATUS_INTERRUPTED if runner.aborting?
83
+
84
+ all_passed && runner.errors.empty? ? RuboCop::CLI::STATUS_SUCCESS : RuboCop::CLI::STATUS_OFFENSES
85
+ end
86
+
87
+ def configure_cache_root(config_store)
88
+ RuboCop::ResultCache.reset_config_cache
89
+ RuboCop::ConfigLoader.cache_root = RuboCop::ResultCache.cache_root(config_store, nil)
90
+ end
91
+
92
+ def warn_pending_cops(config_store) = RuboCop::PendingCopsReporter.warn_if_needed(config_store.for_pwd)
93
+
94
+ def with_isolated_rubocop_state(disable_pending)
95
+ snapshot = snapshot_rubocop_state
96
+ reset_rubocop_state(disable_pending)
97
+ yield
98
+ ensure
99
+ restore_rubocop_state(snapshot) if snapshot
100
+ end
101
+
102
+ def snapshot_rubocop_state
103
+ RUBOCOP_STATE_TARGETS.to_h { |target, attrs| [target, attrs.to_h { |a| [a, target.public_send(a)] }] }
104
+ end
105
+
106
+ def reset_rubocop_state(disable_pending)
107
+ RUBOCOP_STATE_TARGETS.each { |target, attrs| attrs.each { |attr| target.public_send(:"#{attr}=", nil) } }
108
+ RUBOCOP_STATE_TARGETS.each_key { |target| target.disable_pending_cops = disable_pending }
109
+ end
110
+
111
+ def restore_rubocop_state(snapshot)
112
+ snapshot.each { |target, values| values.each { |attr, val| target.public_send(:"#{attr}=", val) } }
113
+ end
114
+
115
+ def config_store(all_cops, store, honor_suppressions: false)
116
+ return RuboCop::ConfigStore.new if all_cops
117
+
118
+ ExecutionConfigStore.new(store || ProjectConfigScope.store, honor_suppressions: honor_suppressions)
119
+ end
120
+
121
+ def scan_options(all_cops)
122
+ base = { format: Runner::FORMATTER, formatters: [[Runner::FORMATTER]] }
123
+ return base if all_cops
124
+
125
+ base.merge(only: ["Lint/Syntax", "Metz"], display_suppressed: true)
126
+ end
127
+
128
+ def auto_fix_options(options, report_path)
129
+ base = autocorrect_options(options.unsafe).merge(
130
+ format: "progress", formatters: [["json", report_path], ["progress"]], out: report_path
131
+ )
132
+ return base if options.all_cops
133
+
134
+ base.merge(only: ["Lint/Syntax", "Metz"], disable_pending_cops: true)
135
+ end
136
+
137
+ def autocorrect_options(unsafe) = { autocorrect: true, (unsafe ? :autocorrect_all : :safe_autocorrect) => true }
138
+ end
139
+ end
140
+ end
141
+ end
@@ -5,7 +5,11 @@ require "psych"
5
5
  require "rubocop"
6
6
  require "stringio"
7
7
 
8
+ require "metz/file_classifier"
9
+ require "metz_scan/commands/scan/execution_config_store"
8
10
  require "metz_scan/commands/scan/project_config_scope"
11
+ require "metz_scan/commands/scan/rubocop_failure"
12
+ require "metz_scan/commands/scan/rubocop_invocation"
9
13
  require "metz_scan/commands/scan/suppression_ledger"
10
14
  require "metz_scan/commands/scan/target_ruby_version"
11
15
 
@@ -19,58 +23,44 @@ module MetzScan
19
23
 
20
24
  Result = Struct.new(:stdout, :stderr, :status, keyword_init: true)
21
25
 
22
- def self.invoke(paths, all_cops: false, stderr: $stderr)
23
- with_errors { perform(paths, all_cops: all_cops, stderr: stderr) }
26
+ def self.invoke(paths, all_cops: false, stderr: $stderr, **scope)
27
+ with_errors { perform(paths, all_cops: all_cops, stderr: stderr, scope: scope) }
24
28
  end
25
29
 
26
- def self.perform(paths, all_cops:, stderr:)
27
- ProjectConfigScope.reset_unresolved_inherit_gems! unless all_cops
28
- paths = inspection_paths(paths, all_cops: all_cops)
29
- report = paths.empty? ? empty_report : scan(paths, all_cops: all_cops)
30
- report.tap { ProjectConfigScope.warn_unresolved_inherit_gems(stderr) unless all_cops }
30
+ def self.perform(paths, all_cops:, stderr:, scope: {})
31
+ store = scope[:store] || (ProjectConfigScope.store unless all_cops)
32
+ exec_store = ExecutionConfigStore.new(store) unless all_cops
33
+ files = inspection_paths(paths, all_cops: all_cops, store: store, target_files: scope[:target_files])
34
+ report = files.empty? ? empty_report : scan(files, all_cops: all_cops, store: store)
35
+ report.tap { ProjectConfigScope.warn_scope_notes(files, stderr, exec_store: exec_store) unless all_cops }
31
36
  end
32
37
 
33
- def self.scan(paths, all_cops:)
34
- report = TargetRubyVersion.with_project_config(paths, all_cops: all_cops) do
35
- parse_output(capture_output(rubocop_argv(paths, all_cops: all_cops)))
38
+ def self.scan(paths, all_cops:, store: nil)
39
+ report = TargetRubyVersion.with_project_config(paths, all_cops: all_cops, store: store) do
40
+ parse_output(RuboCopInvocation.scan(paths, all_cops: all_cops, store: store))
36
41
  end
37
- all_cops ? report : SuppressionLedger.apply(report)
42
+ return report if all_cops
43
+
44
+ SuppressionLedger.with_store(store) { SuppressionLedger.apply(report) }
38
45
  end
39
46
 
47
+ # Only what RuboCop and config loading raise; a metz-scan bug keeps its class and backtrace.
40
48
  def self.with_errors
41
49
  yield
42
- rescue LoadError, StandardError => e
50
+ rescue LoadError, RuboCop::Error, Psych::Exception, SystemCallError => e
43
51
  raise Error, concise_message(e.message)
44
52
  end
45
53
 
46
- def self.rubocop_argv(paths, all_cops:)
47
- require_metz_plugin
48
- ["--plugin", "rubocop-metz", *cop_selection_argv(all_cops), *ledger_argv(all_cops), "--format", FORMATTER,
49
- *paths]
50
- end
51
-
52
54
  def self.require_metz_plugin
53
55
  require "rubocop-metz"
54
56
  rescue LoadError => e
55
57
  raise Error, "could not load rubocop-metz: #{e.message}"
56
58
  end
57
59
 
58
- def self.inspection_paths(paths, all_cops:)
60
+ def self.inspection_paths(paths, all_cops:, store: nil, target_files: nil)
59
61
  return paths if all_cops
60
62
 
61
- TargetFileDiscovery.for_project_config(paths).map { |path| display_path(path) }
62
- end
63
-
64
- def self.cop_selection_argv(all_cops) = all_cops ? [] : ["--force-default-config", "--only", "Metz"]
65
-
66
- # The suppression ledger needs inline-suppressed offenses; AutoFix reuses cop_selection_argv without it.
67
- def self.ledger_argv(all_cops) = all_cops ? [] : ["--display-suppressed"]
68
-
69
- def self.capture_output(argv)
70
- out = StringIO.new
71
- err = StringIO.new
72
- status = with_redirected_io(out, err) { RuboCop::CLI.new.run(argv) }
73
- Result.new(stdout: out.string, stderr: err.string, status: status)
63
+ (target_files || TargetFileDiscovery.discover(paths, store: store)).map { |path| display_path(path) }
74
64
  end
75
65
 
76
66
  def self.with_redirected_io(out, err)
@@ -93,17 +83,11 @@ module MetzScan
93
83
  end
94
84
 
95
85
  def self.parse_output(result)
86
+ raise Error, RubocopFailure.message(result) if RubocopFailure.failed?(result)
87
+
96
88
  JSON.parse(result.stdout)
97
89
  rescue JSON::ParserError
98
- raise Error, failure_message(result)
99
- end
100
-
101
- def self.failure_message(result)
102
- detail = concise_message(result.stderr)
103
- detail = concise_message(result.stdout) if detail.empty?
104
- return detail unless detail.empty?
105
-
106
- "RuboCop exited with status #{result.status} without JSON output"
90
+ raise Error, RubocopFailure.message(result)
107
91
  end
108
92
 
109
93
  def self.concise_message(text)
@@ -143,20 +127,90 @@ module MetzScan
143
127
  end
144
128
 
145
129
  module TargetFileDiscovery
130
+ STORE_KEY = :metz_scan_target_file_discovery_store
131
+
146
132
  module_function
147
133
 
148
- def for_project_config(paths)
149
- find(paths, ProjectConfigScope.store)
150
- rescue RuboCop::Error, Psych::Exception
151
- with_forced_defaults(paths)
134
+ def scan_scope(paths)
135
+ store = ProjectConfigScope.store
136
+ { store: store, target_files: Runner.with_errors { discover(paths, store: store) } }
137
+ end
138
+
139
+ def analyzer_scope(options)
140
+ if options[:all_cops]
141
+ return { rubocop_store: options[:rubocop_store] || Runner.with_errors { all_cops_store } }
142
+ end
143
+
144
+ { store: options[:store] || ProjectConfigScope.store }
152
145
  end
153
146
 
154
- def with_forced_defaults(paths)
155
- find(paths, RuboCop::ConfigStore.new.tap(&:force_default_config!))
147
+ def for_analyzer(paths, all_cops: false, store: nil, rubocop_store: nil)
148
+ return for_all_cops(paths, rubocop_store: rubocop_store || all_cops_store) if all_cops
149
+
150
+ discover(paths, store: store)
151
+ end
152
+
153
+ def discover(paths, store: nil)
154
+ Runner.require_metz_plugin
155
+ ProjectConfigScope.reset_unresolved_inherit_gems!
156
+ with_store(store || ProjectConfigScope.store) { for_project_config(paths) }
157
+ end
158
+
159
+ def for_project_config(paths, store: active_store)
160
+ finder = RuboCop::TargetFinder.new(store, {})
161
+ files = (finder.find(paths, :all_file_types) + view_templates(paths, finder, store)).uniq
162
+ load_governing_configs(files, store)
163
+ end
164
+
165
+ def for_all_cops(paths, rubocop_store: all_cops_store)
166
+ ProjectConfigScope.ensure_metz_defaults_loaded
167
+ RuboCop::TargetFinder.new(rubocop_store, {}).find(paths, :all_file_types)
168
+ end
169
+
170
+ def all_cops_store
171
+ ProjectConfigScope.ensure_metz_defaults_loaded
172
+ RuboCop::ConfigStore.new
173
+ end
174
+
175
+ def with_store(store)
176
+ previous = Thread.current[STORE_KEY]
177
+ Thread.current[STORE_KEY] = store
178
+ yield
179
+ ensure
180
+ Thread.current[STORE_KEY] = previous
181
+ end
182
+
183
+ def active_store
184
+ Thread.current[STORE_KEY] || ProjectConfigScope.store
185
+ end
186
+
187
+ # RuboCop's directory discovery finds only Ruby files; the Metz view cop also
188
+ # checks template files in its effective Include scope. Hidden directories and
189
+ # the project's AllCops: Exclude apply as they do to Ruby.
190
+ def view_templates(paths, finder, store)
191
+ exec_store = ExecutionConfigStore.new(store)
192
+ cops = {}.compare_by_identity
193
+ paths.select { |path| File.directory?(path) }.flat_map do |dir|
194
+ templates_in_dir(File.expand_path(dir), finder, exec_store, cops)
195
+ end
196
+ end
197
+
198
+ def templates_in_dir(base_dir, finder, exec_store, cops)
199
+ finder.find_files(base_dir, 0).select { |file| included_template?(file, exec_store, cops) }
200
+ end
201
+
202
+ def included_template?(file, exec_store, cops)
203
+ return false unless Metz::FileClassifier.template?(file)
204
+
205
+ exec_config = exec_store.for_file(file)
206
+ views_cop = cops[exec_config] ||= RuboCop::Cop::Metz::ViewsDeepNavigation.new(exec_config)
207
+ !exec_config.file_to_exclude?(file) && views_cop.relevant_file?(file)
156
208
  end
157
209
 
158
- def find(paths, store)
159
- RuboCop::TargetFinder.new(store, {}).find(paths, :all_file_types)
210
+ # ExecutionConfigStore builds execution configs per unique loaded_path only, so
211
+ # loading every file's governing config here makes a broken nested config fail the scan.
212
+ def load_governing_configs(files, store)
213
+ files.each { |file| store.for_file(file) }
160
214
  end
161
215
  end
162
216
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "offense_extractor"
3
4
  require_relative "sarif_severity"
4
5
 
5
6
  module MetzScan
@@ -31,8 +32,8 @@ module MetzScan
31
32
  end
32
33
 
33
34
  def add_optional_texts(descriptor, cop_name)
34
- descriptor = add_text(descriptor, "help", help_text(cop_name))
35
- add_text(descriptor, "fullDescription", full_description_for(cop_name))
35
+ text = rule_why_text(cop_name)
36
+ add_text(add_text(descriptor, "help", text), "fullDescription", text)
36
37
  end
37
38
 
38
39
  def add_text(descriptor, key, text)
@@ -45,28 +46,9 @@ module MetzScan
45
46
  SarifSeverity.highest_level(offenses.map { |offense| offense[:severity] })
46
47
  end
47
48
 
48
- def help_text(cop_name)
49
- offense_for(cop_name)&.dig(:why_it_matters) || registry_metadata(cop_name).fetch("why_it_matters", nil)
50
- end
51
-
52
- def full_description_for(cop_name)
53
- offense_for(cop_name)&.dig(:why_it_matters) || registry_metadata(cop_name).fetch("why_it_matters", nil)
54
- end
55
-
56
- def registry_metadata(cop_name)
57
- return {} unless defined?(RuboCop::Cop::Registry)
58
-
59
- metadata_for(cop_for(cop_name))
60
- end
61
-
62
- def metadata_for(cop)
63
- return {} unless cop.respond_to?(:why_it_matters)
64
-
65
- { "why_it_matters" => cop.why_it_matters }
66
- end
67
-
68
- def cop_for(cop_name)
69
- RuboCop::Cop::Registry.global.cops.find { |candidate| candidate.cop_name == cop_name }
49
+ def rule_why_text(cop_name)
50
+ first = offense_for(cop_name)
51
+ first&.fetch(:why_it_matters) { OffenseExtractor.registry_why_it_matters(cop_name) }
70
52
  end
71
53
 
72
54
  def offense_for(cop_name)