metz-scan 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.
Files changed (61) hide show
  1. checksums.yaml +4 -4
  2. data/lib/metz_scan/analyzers/inheritance_descendants.rb +1 -1
  3. data/lib/metz_scan/analyzers/namespace_leak_pressure.rb +1 -1
  4. data/lib/metz_scan/analyzers/package_dependency_pressure.rb +1 -1
  5. data/lib/metz_scan/analyzers/package_map.rb +2 -2
  6. data/lib/metz_scan/analyzers/test_calls_private_method/call_site_collector.rb +79 -0
  7. data/lib/metz_scan/analyzers/test_calls_private_method/finding.rb +23 -0
  8. data/lib/metz_scan/analyzers/test_calls_private_method/metadata.rb +27 -0
  9. data/lib/metz_scan/analyzers/test_calls_private_method/node_predicates.rb +57 -0
  10. data/lib/metz_scan/analyzers/test_calls_private_method/receiver_resolution.rb +80 -0
  11. data/lib/metz_scan/analyzers/test_calls_private_method/scope_facts.rb +76 -0
  12. data/lib/metz_scan/analyzers/test_calls_private_method/scope_resolution.rb +56 -0
  13. data/lib/metz_scan/analyzers/test_calls_private_method/triage.rb +23 -0
  14. data/lib/metz_scan/analyzers/test_calls_private_method.rb +125 -0
  15. data/lib/metz_scan/cli.rb +7 -13
  16. data/lib/metz_scan/commands/explain.rb +11 -2
  17. data/lib/metz_scan/commands/project_analyzers.rb +3 -2
  18. data/lib/metz_scan/commands/report.rb +22 -8
  19. data/lib/metz_scan/commands/rules.rb +16 -4
  20. data/lib/metz_scan/commands/scan/auto_fix.rb +54 -54
  21. data/lib/metz_scan/commands/scan/check_failure.rb +42 -0
  22. data/lib/metz_scan/commands/scan/config_disables.rb +83 -0
  23. data/lib/metz_scan/commands/scan/config_exclusions.rb +112 -0
  24. data/lib/metz_scan/commands/scan/exclude_entries.rb +64 -0
  25. data/lib/metz_scan/commands/scan/exclude_entry_locator.rb +84 -0
  26. data/lib/metz_scan/commands/scan/exclude_provenance.rb +53 -0
  27. data/lib/metz_scan/commands/scan/execution_config_store.rb +142 -0
  28. data/lib/metz_scan/commands/scan/ignored_cli_options_note.rb +35 -0
  29. data/lib/metz_scan/commands/scan/inherited_include_rewriter.rb +43 -0
  30. data/lib/metz_scan/commands/scan/inline_directive_locator.rb +80 -0
  31. data/lib/metz_scan/commands/scan/json_guidance.rb +81 -0
  32. data/lib/metz_scan/commands/scan/offense_extractor.rb +29 -7
  33. data/lib/metz_scan/commands/scan/path_scoped_include_note.rb +73 -0
  34. data/lib/metz_scan/commands/scan/project_analyzer_offenses.rb +21 -5
  35. data/lib/metz_scan/commands/scan/project_analyzer_runner.rb +25 -24
  36. data/lib/metz_scan/commands/scan/project_config_scope.rb +105 -26
  37. data/lib/metz_scan/commands/scan/rubocop_failure.rb +38 -0
  38. data/lib/metz_scan/commands/scan/rubocop_invocation.rb +141 -0
  39. data/lib/metz_scan/commands/scan/runner.rb +94 -75
  40. data/lib/metz_scan/commands/scan/sarif_rule_descriptors.rb +6 -24
  41. data/lib/metz_scan/commands/scan/suppression_ledger.rb +113 -0
  42. data/lib/metz_scan/commands/scan/suppression_ledger_formatter.rb +54 -0
  43. data/lib/metz_scan/commands/scan/target_ruby_version.rb +3 -2
  44. data/lib/metz_scan/commands/scan/text_renderer.rb +5 -4
  45. data/lib/metz_scan/commands/scan.rb +48 -26
  46. data/lib/metz_scan/project_index/rubydex_backend/method_declarations.rb +33 -12
  47. data/lib/metz_scan/project_index/rubydex_backend/method_visibility.rb +155 -0
  48. data/lib/metz_scan/project_index/rubydex_backend.rb +2 -1
  49. data/lib/metz_scan/project_index.rb +1 -1
  50. data/lib/metz_scan/version.rb +1 -1
  51. data/metz-scan.gemspec +20 -12
  52. metadata +33 -14
  53. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/artifact_writer.rb +0 -51
  54. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/baseline_delta.rb +0 -231
  55. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/collaborators.rb +0 -76
  56. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/markdown_renderer.rb +0 -353
  57. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/readiness_catalog.rb +0 -123
  58. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/summary.rb +0 -333
  59. data/lib/metz_scan/calibration/project_analyzer_evidence_runner/target_set.rb +0 -139
  60. data/lib/metz_scan/calibration/project_analyzer_evidence_runner.rb +0 -64
  61. data/lib/metz_scan/calibration/rubydex_drift_formatter.rb +0 -91
@@ -1,18 +1,34 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "project_analyzer_metadata"
4
+ require_relative "suppression_ledger"
4
5
 
5
6
  module MetzScan
6
7
  module Commands
7
8
  class Scan
8
9
  module ProjectAnalyzerOffenses
9
- OffenseSet = Struct.new(:by_path, :offenses, keyword_init: true)
10
+ OffenseSet = Struct.new(:findings, :by_path, :offenses, keyword_init: true)
11
+ FIX_SAFETY = "manual"
10
12
 
11
13
  module_function
12
14
 
13
- def build(findings)
15
+ # With a `ledger_report` (scan), the project's MetzProject/* config
16
+ # and inline directives hide offenses, crediting them in that report's
17
+ # suppression ledger; findings left with no live offense drop out.
18
+ def build(findings, ledger_report: nil, **scope)
14
19
  entries = entries_for(findings)
15
- OffenseSet.new(by_path: offenses_by_path(entries), offenses: entries.map { |entry| entry.fetch(:offense) })
20
+ return live_set(entries, ledger_report, **scope) if ledger_report
21
+
22
+ OffenseSet.new(findings: findings, by_path: offenses_by_path(entries),
23
+ offenses: entries.map { |entry| entry.fetch(:offense) })
24
+ end
25
+
26
+ def live_set(entries, ledger_report, **scope)
27
+ by_path = SuppressionLedger.partition!(ledger_report, offenses_by_path(entries), **scope)
28
+ live = by_path.values.flatten
29
+ kept = Set.new.compare_by_identity.merge(live)
30
+ findings = entries.select { |entry| kept.include?(entry.fetch(:offense)) }.map { |entry| entry[:finding] }
31
+ OffenseSet.new(findings: findings.uniq(&:object_id), by_path: by_path, offenses: live)
16
32
  end
17
33
 
18
34
  def entries_for(findings)
@@ -21,7 +37,7 @@ module MetzScan
21
37
 
22
38
  def offenses_for(finding)
23
39
  locations_for(finding).map do |location|
24
- { path: location.path, offense: offense_for(finding, location) }
40
+ { path: location.path, finding: finding, offense: offense_for(finding, location) }
25
41
  end
26
42
  end
27
43
 
@@ -47,7 +63,7 @@ module MetzScan
47
63
  end
48
64
 
49
65
  def explanation_metadata(finding)
50
- { "why_it_matters" => finding.why_it_matters, "fix_safety" => "manual",
66
+ { "why_it_matters" => finding.why_it_matters, "fix_safety" => FIX_SAFETY,
51
67
  "suggested_next_moves" => suggested_next_moves_for(finding) }
52
68
  end
53
69
 
@@ -8,6 +8,7 @@ require_relative "../../analyzers/namespace_leak_pressure"
8
8
  require_relative "../../analyzers/implicit_context_pressure"
9
9
  require_relative "../../analyzers/repeated_query_criteria"
10
10
  require_relative "../../analyzers/subclass_override_pressure"
11
+ require_relative "../../analyzers/test_calls_private_method"
11
12
  require_relative "../../project_index"
12
13
  require_relative "runner"
13
14
  require_relative "project_analyzer_metadata"
@@ -20,43 +21,44 @@ module MetzScan
20
21
  # same report shape produced by RuboCop's JSON formatter.
21
22
  module ProjectAnalyzerRunner
22
23
  ANALYZERS = [
23
- Analyzers::RepeatedBranching,
24
- Analyzers::ServiceSoup,
25
- Analyzers::InheritanceDescendants,
26
- Analyzers::PackageDependencyPressure,
27
- Analyzers::NamespaceLeakPressure,
28
- Analyzers::ImplicitContextPressure,
29
- Analyzers::RepeatedQueryCriteria,
30
- Analyzers::SubclassOverridePressure
24
+ Analyzers::RepeatedBranching, Analyzers::ServiceSoup, Analyzers::InheritanceDescendants,
25
+ Analyzers::PackageDependencyPressure, Analyzers::NamespaceLeakPressure, Analyzers::ImplicitContextPressure,
26
+ Analyzers::RepeatedQueryCriteria, Analyzers::SubclassOverridePressure, Analyzers::TestCallsPrivateMethod
31
27
  ].freeze
32
28
  INDEX_BACKED_ANALYZERS = [Analyzers::InheritanceDescendants, Analyzers::PackageDependencyPressure,
33
- Analyzers::NamespaceLeakPressure, Analyzers::SubclassOverridePressure].freeze
29
+ Analyzers::NamespaceLeakPressure, Analyzers::SubclassOverridePressure,
30
+ Analyzers::TestCallsPrivateMethod].freeze
34
31
  DEFAULT_OUTPUT_STATUS = "validated"
35
32
  DEFAULT_OUTPUT_CONFIDENCE = "medium"
36
33
  DEFAULT_OUTPUT_TRIAGE_SEVERITY = "design pressure"
37
34
 
38
35
  module_function
39
36
 
40
- def merge!(parsed, paths, **)
41
- findings = project_findings_for(paths, **)
37
+ def merge!(parsed, paths, **options)
38
+ scope = TargetFileDiscovery.analyzer_scope(options)
39
+ findings = project_findings_for(paths, **options, **scope)
42
40
  return parsed if findings.empty?
43
41
 
44
- merge_findings(parsed, findings)
42
+ merge_live_offenses(parsed, findings, scope)
43
+ end
44
+
45
+ def merge_live_offenses(parsed, findings, scope)
46
+ offense_set = Runner.with_errors { ProjectAnalyzerOffenses.build(findings, ledger_report: parsed, **scope) }
47
+ merge_offense_set(parsed, offense_set) unless offense_set.findings.empty?
45
48
  parsed
46
49
  end
47
50
 
48
- def project_findings_for(paths, index: nil, default_output: false, force_default_config: false)
49
- paths = analyzer_paths(paths, index: index, force_default_config: force_default_config)
51
+ def project_findings_for(paths, index: nil, default_output: false, **)
52
+ paths = analyzer_paths(paths, index: index, **)
50
53
  return [] if paths.empty? && !index
51
54
 
52
55
  findings = project_findings(paths, index: index, default_output: default_output)
53
56
  default_output ? findings.select { |finding| default_output_finding?(finding) } : findings
54
57
  end
55
58
 
56
- def merge_findings(parsed, findings)
57
- offense_set = ProjectAnalyzerOffenses.build(findings)
59
+ def merge_offense_set(parsed, offense_set)
58
60
  merge_offenses(parsed, offense_set.by_path)
59
- update_summary(parsed, findings, offense_set.offenses)
61
+ update_summary(parsed, offense_set.findings, offense_set.offenses)
60
62
  end
61
63
 
62
64
  def project_findings(paths, index: nil, default_output: false)
@@ -80,7 +82,7 @@ module MetzScan
80
82
 
81
83
  def project_index_for(paths, index, analyzers)
82
84
  return index if index
83
- return nil unless analyzers.any? { |analyzer| INDEX_BACKED_ANALYZERS.include?(analyzer) }
85
+ return nil unless analyzers.intersect?(INDEX_BACKED_ANALYZERS)
84
86
 
85
87
  ProjectIndex.build(paths)
86
88
  end
@@ -91,16 +93,15 @@ module MetzScan
91
93
  finding.triage_severity == DEFAULT_OUTPUT_TRIAGE_SEVERITY
92
94
  end
93
95
 
94
- def analyzer_paths(paths, index: nil, force_default_config: false)
96
+ def analyzer_paths(paths, index: nil, target_files: nil, **)
95
97
  return Array(paths) if index
98
+ return target_files if target_files
96
99
 
97
- rubocop_target_files(paths, force_default_config: force_default_config)
100
+ rubocop_target_files(paths, **)
98
101
  end
99
102
 
100
- def rubocop_target_files(paths, force_default_config: false)
101
- return TargetFileDiscovery.with_forced_defaults(paths) if force_default_config
102
-
103
- TargetFileDiscovery.for_project_config(paths)
103
+ def rubocop_target_files(paths, **)
104
+ Runner.with_errors { TargetFileDiscovery.for_analyzer(paths, **) }
104
105
  end
105
106
 
106
107
  def merge_offenses(parsed, grouped_offenses)
@@ -1,15 +1,30 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "pathname"
4
3
  require "rubocop"
5
4
 
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"
8
+
6
9
  module MetzScan
7
10
  module Commands
8
11
  class Scan
9
12
  # DDR: docs/ddrs/2026-07-08-rubocop-scope-only-config.md explains why default mode bypasses ConfigStore here.
10
13
  module ProjectConfigScope
11
- 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
12
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"
13
28
  DEFAULT_FILE = RuboCop::ConfigLoader::DEFAULT_FILE
14
29
 
15
30
  module_function
@@ -33,6 +48,14 @@ module MetzScan
33
48
  @unresolved_inherit_gems = []
34
49
  end
35
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
+
36
59
  # Default mode drops file-scope Exclude from an inherit_gem whose gem
37
60
  # isn't installed (docs/ddrs/2026-07-08-rubocop-scope-only-config.md);
38
61
  # this turns that silent degrade into a one-line stderr note per gem.
@@ -47,6 +70,15 @@ module MetzScan
47
70
  "its file-scope Exclude is not applied — install the gem or use --all-cops"
48
71
  end
49
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
+
50
82
  class TargetRubyVersion
51
83
  def initialize(paths, store: ConfigStore.new, loader: ConfigLoader.new)
52
84
  @paths = paths
@@ -55,9 +87,10 @@ module MetzScan
55
87
  end
56
88
 
57
89
  def version
58
- config.target_ruby_version
59
- rescue RuboCop::Error, Psych::Exception
60
- 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}"
61
94
  end
62
95
 
63
96
  private
@@ -102,43 +135,97 @@ module MetzScan
102
135
 
103
136
  def for_dir(dir)
104
137
  path = @path_cache[dir] ||= RuboCop::ConfigLoader.configuration_file_for(dir)
105
- @object_cache[path] ||= @loader.load(path)
138
+ @object_cache[path] ||= load_config(path)
139
+ end
140
+
141
+ # The project Exclude entry (with its source config file) that scopes
142
+ # the cop off `file`, or nil when only a stock default does.
143
+ def applied_exclude(badge, file)
144
+ config = for_file(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
106
176
  end
107
177
  end
108
178
 
109
179
  class ConfigLoader
180
+ def provenance = @provenance ||= ExcludeProvenance.new
181
+
110
182
  def default_for(dir)
111
183
  path = File.join(File.expand_path(dir), ".rubocop.yml")
112
- config = RuboCop::Config.new({}, path)
113
- RuboCop::ConfigLoader.merge_with_default(config, path)
184
+ merge_with_default(RuboCop::Config.new({}, path), path)
114
185
  end
115
186
 
116
187
  def load(path)
117
- return RuboCop::ConfigLoader.default_configuration if path == DEFAULT_FILE
188
+ return ProjectConfigScope.ensure_metz_defaults_loaded if path == DEFAULT_FILE
118
189
 
119
190
  config = RuboCop::Config.new(scope_hash(path), path)
120
191
  config.deprecation_check { |_message| nil }
121
- config.make_excludes_absolute
122
- RuboCop::ConfigLoader.merge_with_default(config, path)
192
+ provenance.make_excludes_absolute(config)
193
+ merge_with_default(config, path)
123
194
  end
124
195
 
125
196
  private
126
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
+
127
203
  def scope_hash(path, seen = [])
128
204
  absolute_path = File.expand_path(path)
129
205
  return {} if seen.include?(absolute_path)
130
206
 
131
- raw_hash = RuboCop::ConfigLoader.load_yaml_configuration(absolute_path)
207
+ raw_hash = provenance.load_yaml_configuration(absolute_path)
132
208
  inherited = inherited_scope_hash(raw_hash, absolute_path, [*seen, absolute_path])
133
- RuboCop::ConfigLoader.merge(inherited, local_scope_hash(raw_hash))
209
+ merge(inherited, local_scope_hash(raw_hash), raw_hash["inherit_mode"] || inherited["inherit_mode"])
134
210
  end
135
211
 
136
212
  def inherited_scope_hash(raw_hash, path, seen)
137
213
  inherited_paths(raw_hash, path).each_with_object({}) do |inherited_path, merged|
138
- merged.replace(RuboCop::ConfigLoader.merge(merged, scope_hash(inherited_path, seen)))
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))
139
217
  end
140
218
  end
141
219
 
220
+ # RuboCop's resolve_inheritance merges every inherited file with the
221
+ # inheriting file's top-level inherit_mode, so sibling inherit_from
222
+ # files union under `merge: [Exclude]` too.
223
+ def merge(base_hash, derived_hash, inherit_mode)
224
+ resolver.merge(base_hash, derived_hash, inherit_mode: inherit_mode || {})
225
+ end
226
+
227
+ def resolver = @resolver ||= RuboCop::ConfigLoaderResolver.new
228
+
142
229
  def inherited_paths(raw_hash, path)
143
230
  gem_inherited_paths(raw_hash["inherit_gem"], path) + local_inherited_paths(raw_hash["inherit_from"], path)
144
231
  end
@@ -200,7 +287,7 @@ module MetzScan
200
287
  end
201
288
 
202
289
  def scoped_settings(key, value)
203
- keys = key == "AllCops" ? ALL_COPS_PROJECT_KEYS : SCOPE_KEYS
290
+ keys = key == "AllCops" ? ALL_COPS_PROJECT_KEYS : COP_KEYS
204
291
  value.each_with_object({}) do |(setting, setting_value), scope|
205
292
  scope[setting] = copy_value(setting_value) if keys.include?(setting)
206
293
  end
@@ -213,17 +300,9 @@ module MetzScan
213
300
  value
214
301
  end
215
302
 
216
- def remote_config?(path)
217
- path.to_s.start_with?("http://", "https://")
218
- end
219
-
220
- def absolute_path?(path)
221
- Pathname.new(path.to_s).absolute?
222
- end
223
-
224
- def glob_path?(path)
225
- path.match?(/[*?{}\[\]]/)
226
- 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?(/[*?{}\[\]]/)
227
306
  end
228
307
  end
229
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