rails_tia 0.1.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 (41) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +180 -0
  4. data/docs/configuration.md +109 -0
  5. data/docs/github-actions.md +147 -0
  6. data/exe/rails-tia +5 -0
  7. data/ext/rails_tia/allocated_classes.c +111 -0
  8. data/ext/rails_tia/extconf.rb +7 -0
  9. data/lib/rails_tia/action_view_support.rb +67 -0
  10. data/lib/rails_tia/audit.rb +42 -0
  11. data/lib/rails_tia/boot.rb +12 -0
  12. data/lib/rails_tia/ci/base.rb +38 -0
  13. data/lib/rails_tia/ci/git.rb +49 -0
  14. data/lib/rails_tia/ci/github_actions.rb +237 -0
  15. data/lib/rails_tia/ci/gitlab.rb +199 -0
  16. data/lib/rails_tia/ci.rb +36 -0
  17. data/lib/rails_tia/cli.rb +328 -0
  18. data/lib/rails_tia/configuration.rb +169 -0
  19. data/lib/rails_tia/constant_reads.rb +84 -0
  20. data/lib/rails_tia/context.rb +17 -0
  21. data/lib/rails_tia/coverage_collector.rb +198 -0
  22. data/lib/rails_tia/described_class_support.rb +75 -0
  23. data/lib/rails_tia/fallback.rb +79 -0
  24. data/lib/rails_tia/formatter.rb +88 -0
  25. data/lib/rails_tia/http.rb +89 -0
  26. data/lib/rails_tia/junit_report.rb +116 -0
  27. data/lib/rails_tia/map.rb +178 -0
  28. data/lib/rails_tia/metrics.rb +71 -0
  29. data/lib/rails_tia/minitest.rb +243 -0
  30. data/lib/rails_tia/native_extension.rb +6 -0
  31. data/lib/rails_tia/object_allocations.rb +23 -0
  32. data/lib/rails_tia/predictor.rb +61 -0
  33. data/lib/rails_tia/rails_support.rb +86 -0
  34. data/lib/rails_tia/run_report.rb +116 -0
  35. data/lib/rails_tia/static_mapping.rb +85 -0
  36. data/lib/rails_tia/templates/minitest.yml +39 -0
  37. data/lib/rails_tia/templates/rspec.yml +45 -0
  38. data/lib/rails_tia/version.rb +3 -0
  39. data/lib/rails_tia.rb +27 -0
  40. data/skills/rails-tia/SKILL.md +49 -0
  41. metadata +145 -0
@@ -0,0 +1,178 @@
1
+ require 'fileutils'
2
+ require 'json'
3
+ require 'set'
4
+ require 'stringio'
5
+ require 'time'
6
+ require 'zlib'
7
+
8
+ module RailsTia
9
+ # Map spec files to the source files they execute.
10
+ #
11
+ # Queries always go from changed sources to affected specs,
12
+ # so store dependencies as a reverse index: source -> Set(spec).
13
+ class Map
14
+ FORMAT_VERSION = 1
15
+
16
+ class FormatError < StandardError; end
17
+
18
+ attr_reader :generated_at, :commit_sha
19
+
20
+ class << self
21
+ # Report corrupted files, such as truncated gzip or JSON, as FormatError with the path
22
+ # so that the CLI can fail with a diagnostic instead of a backtrace.
23
+ def load(path)
24
+ json = read_json(path)
25
+ map = new
26
+ map.load_hash(JSON.parse(json))
27
+ yield json if block_given?
28
+ map
29
+ rescue FormatError, JSON::ParserError, Zlib::Error => e
30
+ raise FormatError, "Invalid map file: #{path}: #{e.message}"
31
+ end
32
+
33
+ # Merge fragments produced by parallel_tests processes and CI nodes.
34
+ def merge_files(paths, &on_fragment)
35
+ paths.reduce(new) { |merged, path| merged.merge!(load(path, &on_fragment)) }
36
+ end
37
+
38
+ private
39
+
40
+ def read_json(path)
41
+ raw = File.binread(path)
42
+ gzipped?(raw) ? Zlib::GzipReader.new(StringIO.new(raw)).read : raw
43
+ end
44
+
45
+ # Detect gzip using its magic bytes rather than the filename extension.
46
+ # CI artifact transfer paths may not preserve extensions.
47
+ def gzipped?(raw)
48
+ raw.getbyte(0) == 0x1f && raw.getbyte(1) == 0x8b
49
+ end
50
+ end
51
+
52
+ def initialize(generated_at: nil, commit_sha: nil)
53
+ @specs = Set.new
54
+ @edges = {}
55
+ @generated_at = generated_at
56
+ @commit_sha = commit_sha
57
+ end
58
+
59
+ def add(spec, sources)
60
+ @specs << spec
61
+ sources.each do |source|
62
+ (@edges[source] ||= Set.new) << spec
63
+ end
64
+ self
65
+ end
66
+
67
+ def specs_for(source)
68
+ @edges[source] || Set.new
69
+ end
70
+
71
+ def known_source?(source)
72
+ @edges.key?(source)
73
+ end
74
+
75
+ def specs
76
+ @specs
77
+ end
78
+
79
+ def sources
80
+ @edges.keys
81
+ end
82
+
83
+ def empty?
84
+ @specs.empty?
85
+ end
86
+
87
+ def merge!(other)
88
+ @specs.merge(other.specs)
89
+ other.sources.each do |source|
90
+ (@edges[source] ||= Set.new).merge(other.specs_for(source))
91
+ end
92
+ # Use the oldest fragment timestamp to keep freshness checks conservative.
93
+ @generated_at = [@generated_at, other.generated_at].compact.min
94
+ @commit_sha ||= other.commit_sha
95
+ self
96
+ end
97
+
98
+ def mark_stale!
99
+ @generated_at = Time.at(0)
100
+ end
101
+
102
+ # Treat an unknown generation timestamp as stale to stay conservative.
103
+ def stale?(max_age_days:, now: Time.now)
104
+ return true if @generated_at.nil?
105
+
106
+ now - @generated_at > max_age_days * 24 * 60 * 60
107
+ end
108
+
109
+ def dump(path)
110
+ json = JSON.generate(to_h)
111
+ FileUtils.mkdir_p(File.dirname(path))
112
+ if path.end_with?('.gz')
113
+ File.open(path, 'wb') { |f| Zlib::GzipWriter.wrap(f) { |gz| gz.write(json) } }
114
+ else
115
+ File.write(path, json)
116
+ end
117
+ yield json if block_given?
118
+ path
119
+ end
120
+
121
+ def to_h
122
+ spec_list = @specs.to_a.sort
123
+ spec_index = spec_list.each_with_index.to_h
124
+ source_list = @edges.keys.sort
125
+
126
+ {
127
+ 'format_version' => FORMAT_VERSION,
128
+ 'generated_at' => @generated_at&.utc&.iso8601,
129
+ 'commit_sha' => @commit_sha,
130
+ 'specs' => spec_list,
131
+ 'sources' => source_list,
132
+ 'edges' => source_list.map { |source| @edges[source].map { |spec| spec_index[spec] }.sort },
133
+ }
134
+ end
135
+
136
+ def load_hash(hash)
137
+ raise FormatError, 'map must be an object' unless hash.is_a?(Hash)
138
+
139
+ version = hash['format_version']
140
+ raise FormatError, "unsupported format_version: #{version.inspect}" unless version == FORMAT_VERSION
141
+
142
+ spec_list = hash['specs']
143
+ source_list = hash['sources']
144
+ edges = hash['edges']
145
+ valid_paths = [spec_list, source_list].all? do |paths|
146
+ paths.is_a?(Array) && paths.all? { |path| path.is_a?(String) } && paths.uniq.size == paths.size
147
+ end
148
+ unless valid_paths
149
+ raise FormatError, 'specs and sources must be arrays of unique strings'
150
+ end
151
+ valid_edges = edges.is_a?(Array) && edges.size == source_list.size && edges.all? do |ids|
152
+ ids.is_a?(Array) && ids.all? { |id| id.is_a?(Integer) && id >= 0 && id < spec_list.size }
153
+ end
154
+ unless valid_edges
155
+ raise FormatError, 'edges must contain one array of valid spec indices per source'
156
+ end
157
+
158
+ @specs = Set.new(spec_list)
159
+ @edges = {}
160
+ source_list.each_with_index do |source, i|
161
+ @edges[source] = Set.new(edges[i].map { |id| spec_list[id] })
162
+ end
163
+ @generated_at = parse_time(hash['generated_at'])
164
+ @commit_sha = hash['commit_sha']
165
+ self
166
+ end
167
+
168
+ private
169
+
170
+ def parse_time(value)
171
+ return nil if value.nil?
172
+
173
+ Time.iso8601(value)
174
+ rescue ArgumentError, TypeError
175
+ raise FormatError, "invalid generated_at: #{value.inspect}"
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,71 @@
1
+ require 'fileutils'
2
+ require 'json'
3
+
4
+ module RailsTia
5
+ # Record how much work each prediction eliminates.
6
+ #
7
+ # Always record savings and full-run reasons when using selective execution in CI.
8
+ # When JUnit XML is available, also estimate savings using measured durations.
9
+ class Metrics
10
+ def initialize(config:, result:, junit_report: nil)
11
+ @config = config
12
+ @result = result
13
+ @junit_report = junit_report
14
+ end
15
+
16
+ def to_h
17
+ all_specs = @config.all_specs
18
+ base = {
19
+ 'full_run' => @result.full_run?,
20
+ 'reason' => @result.reason,
21
+ 'changed_file_count' => @result.sources.size,
22
+ 'predicted_spec_count' => @result.specs.size,
23
+ 'total_spec_count' => all_specs.size,
24
+ 'spec_ratio' => ratio(@result.specs.size, all_specs.size),
25
+ }
26
+ base.merge(time_metrics(all_specs))
27
+ end
28
+
29
+ def write(path = @config.metrics_path, data: to_h)
30
+ FileUtils.mkdir_p(File.dirname(path))
31
+ File.write(path, JSON.pretty_generate(data))
32
+ path
33
+ end
34
+
35
+ def summary(data = to_h)
36
+ if data['full_run']
37
+ "[rails_tia] Full run: #{data['reason']} (#{data['total_spec_count']} specs)"
38
+ else
39
+ format(
40
+ '[rails_tia] Selected specs: %d / %d (%.1f%%)%s',
41
+ data['predicted_spec_count'],
42
+ data['total_spec_count'],
43
+ (data['spec_ratio'] || 0) * 100,
44
+ data['time_ratio'] ? format(' / Estimated runtime %.1f%%', data['time_ratio'] * 100) : '',
45
+ )
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def time_metrics(all_specs)
52
+ return {} if @junit_report.nil? || @junit_report.empty?
53
+
54
+ durations = @junit_report.durations
55
+ predicted = @result.specs.sum { |spec| durations[spec] }
56
+ total = all_specs.sum { |spec| durations[spec] }
57
+
58
+ {
59
+ 'estimated_seconds' => predicted.round(1),
60
+ 'total_estimated_seconds' => total.round(1),
61
+ 'time_ratio' => ratio(predicted, total),
62
+ }
63
+ end
64
+
65
+ def ratio(numerator, denominator)
66
+ return nil if denominator.nil? || denominator.zero?
67
+
68
+ (numerator.to_f / denominator).round(4)
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,243 @@
1
+ require 'rails_tia/boot'
2
+ require 'minitest'
3
+ require 'tmpdir'
4
+ require 'rails_tia/coverage_collector'
5
+
6
+ module RailsTia
7
+ class MinitestCollector < CoverageCollector
8
+ class << self
9
+ attr_accessor :current
10
+ end
11
+
12
+ def initialize
13
+ super
14
+ @owner = Thread.current
15
+ @parent = Process.pid
16
+ @workers = 0
17
+ @declarations = {}
18
+ @runnable_files = {}
19
+ # const_source_location only identifies the first file to open a class.
20
+ @class_trace = TracePoint.new(:class) do |event|
21
+ klass = event.self
22
+ next unless klass.is_a?(Class) && klass < ::Minitest::Runnable
23
+
24
+ path = test_file(event.path)
25
+ (@declarations[klass] ||= Set.new) << path if path
26
+ end
27
+ @class_trace.enable
28
+ # A load error or interrupted worker pool may never reach after_run.
29
+ Map.new(generated_at: Time.at(0), commit_sha: RailsTia.commit_sha).dump(fragment_path)
30
+ end
31
+
32
+ def start
33
+ @class_trace.disable
34
+ super
35
+ install_rails_worker_hooks
36
+ end
37
+
38
+ def collect
39
+ Dir.mktmpdir('rails-tia-workers') do |dir|
40
+ @directory = dir
41
+ passed = yield
42
+ switch_spec(nil)
43
+ merge_workers
44
+ raise Error, @collection_error if @collection_error
45
+ @passed = passed
46
+ end
47
+ end
48
+
49
+ def publish
50
+ return unless Process.pid == @parent && @tracking
51
+
52
+ finish
53
+ save(!@passed, minitest_version: ::Minitest::VERSION)
54
+ end
55
+
56
+ def enter(klass, name)
57
+ if defined?(::ActiveSupport::Testing::Isolation) && klass < ::ActiveSupport::Testing::Isolation
58
+ @collection_error ||= "Cannot collect #{klass}##{name} with ActiveSupport::Testing::Isolation"
59
+ return
60
+ end
61
+ if Thread.current != @owner
62
+ raise Error, 'Minitest coverage collection does not support thread-parallel tests'
63
+ end
64
+
65
+ if Process.pid != @parent && @workers.zero?
66
+ raise Error, 'Minitest forked outside the supported Rails process pool'
67
+ end
68
+
69
+ method = klass.instance_method(name)
70
+ # Inherited and mixed-in tests run when their consumer file is selected.
71
+ # A reopened class can also define its own methods in separate test files.
72
+ files = runnable_files(klass)
73
+ path = test_file(method.source_location&.first) if method.owner == klass
74
+ files = files | [path] if path
75
+ if files.empty?
76
+ @collection_error ||= "Cannot locate #{klass}##{name} under spec_glob #{@config.spec_glob.inspect}"
77
+ return
78
+ end
79
+
80
+ if files.size > 1 && files != @current_spec
81
+ files.each { |file| @map.add(file, files) }
82
+ end
83
+ switch_spec(files)
84
+ count_example
85
+ end
86
+
87
+ attr_writer :workers
88
+
89
+ def start_worker
90
+ # The fork inherits the parent’s pre-fork counters and timings.
91
+ @coverage_calls = @example_count = 0
92
+ @report = RunReport.for('map_worker', @config) if @report
93
+ end
94
+
95
+ def write_worker
96
+ data = finish.to_h
97
+ data['collection_error'] = @collection_error
98
+ data['example_count'] = @example_count
99
+ data['coverage_calls'] = @coverage_calls
100
+ data['timings'] = @report.timings if @report
101
+ path = File.join(@directory, "#{Process.pid}.json")
102
+ File.write("#{path}.tmp", JSON.generate(data))
103
+ File.rename("#{path}.tmp", path)
104
+ end
105
+
106
+ private
107
+
108
+ def coverage_result
109
+ unless Coverage.running?
110
+ raise Error, 'Coverage stopped before Minitest map collection finished. Disable SimpleCov or other coverage tools during map generation.'
111
+ end
112
+ super
113
+ end
114
+
115
+ def merge_workers
116
+ files = Dir.glob(File.join(@directory, '*.json'))
117
+ unless files.size == @workers
118
+ raise Error, "Incomplete Minitest coverage: expected #{@workers} worker maps, received #{files.size}"
119
+ end
120
+
121
+ files.each do |path|
122
+ data = JSON.parse(File.read(path))
123
+ @collection_error ||= data['collection_error']
124
+ @map.merge!(Map.new.load_hash(data))
125
+ @example_count += data.fetch('example_count')
126
+ @coverage_calls += data.fetch('coverage_calls')
127
+ data.fetch('timings').each { |key, value| @report.timings[key.to_sym] += value } if @report
128
+ end
129
+ end
130
+
131
+ def test_file(path)
132
+ return unless path
133
+
134
+ file = relative(path)
135
+ file if File.fnmatch?(@config.spec_glob, file, Configuration::FNMATCH_FLAGS)
136
+ end
137
+
138
+ def runnable_files(klass)
139
+ @runnable_files[klass] ||= begin
140
+ paths = Set.new
141
+ klass.ancestors.each do |ancestor|
142
+ files = @declarations[ancestor]
143
+ next unless files
144
+
145
+ # A subclass can acquire tests from a reopening of its superclass.
146
+ paths.merge(files) if ancestor == klass || files.size > 1
147
+ end
148
+ origin = class_file(klass)
149
+ paths << origin if origin
150
+ paths.to_a
151
+ end
152
+ end
153
+
154
+ def class_file(klass)
155
+ name = Module.instance_method(:name).bind_call(klass)
156
+ if name && Object.const_defined?(name, false) && Object.const_get(name, false).equal?(klass)
157
+ test_file(Object.const_source_location(name, false)&.first)
158
+ end
159
+ end
160
+
161
+ def install_rails_worker_hooks
162
+ return unless defined?(::ActiveSupport::Testing::Parallelization::Worker)
163
+
164
+ parallel = ::ActiveSupport::Testing::Parallelization
165
+ parallel.prepend(ProcessPool)
166
+ parallel::Worker.prepend(Worker)
167
+ end
168
+
169
+ module ProcessPool
170
+ def start
171
+ MinitestCollector.current.workers = size
172
+ super
173
+ end
174
+ end
175
+
176
+ # Rails sends results back to a reporter in the parent. Coverage and
177
+ # ActiveSupport notifications must be read in the process running the test.
178
+ module Worker
179
+ def perform_job(job)
180
+ collect_coverage { |collector| collector.enter(job[0], job[1]) }
181
+ super
182
+ end
183
+
184
+ def work_from_queue
185
+ collect_coverage(&:start_worker)
186
+ super
187
+ ensure
188
+ collect_coverage { |collector| collector.switch_spec(nil) }
189
+ end
190
+
191
+ def run_cleanup
192
+ super
193
+ collect_coverage(&:write_worker)
194
+ end
195
+
196
+ private
197
+
198
+ def collect_coverage
199
+ yield MinitestCollector.current unless @rails_tia_collection_failed
200
+ rescue StandardError => error
201
+ # Rails deregisters the worker after cleanup returns. Leave its map
202
+ # missing so the parent rejects the run after the test queue drains.
203
+ @rails_tia_collection_failed = true
204
+ warn "[rails_tia] Cannot collect Minitest worker map: #{error.message}"
205
+ end
206
+ end
207
+
208
+ module Runner
209
+ def init_plugins(...)
210
+ super
211
+ # Rails can load test files while Minitest parses its options.
212
+ MinitestCollector.current.start
213
+ reporter << LocalReporter.new
214
+ end
215
+
216
+ def run(...)
217
+ MinitestCollector.current.collect { super }
218
+ end
219
+ end
220
+
221
+ class LocalReporter < ::Minitest::AbstractReporter
222
+ def prerecord(klass, name)
223
+ # Rails replays remote results using a name-only stand-in for the class.
224
+ MinitestCollector.current.enter(klass, name) if klass.is_a?(Class)
225
+ end
226
+ end
227
+
228
+ module Suite
229
+ # Minitest 6 renamed the class-level suite entry point.
230
+ define_method(::Minitest::Runnable.respond_to?(:run_suite) ? :run_suite : :run) do |*args|
231
+ super(*args)
232
+ ensure
233
+ MinitestCollector.current.switch_spec(nil)
234
+ end
235
+ end
236
+ end
237
+ end
238
+
239
+ RailsTia::MinitestCollector.current = RailsTia::MinitestCollector.new
240
+ Minitest.singleton_class.prepend(RailsTia::MinitestCollector::Runner)
241
+ Minitest::Runnable.singleton_class.prepend(RailsTia::MinitestCollector::Suite)
242
+ # after_run hooks run in reverse registration order, including application hooks.
243
+ Minitest.after_run { RailsTia::MinitestCollector.current.publish }
@@ -0,0 +1,6 @@
1
+ require 'rbconfig'
2
+
3
+ module RailsTia
4
+ ALLOCATION_EXTENSION = File.join('rails_tia', RbConfig::CONFIG.fetch('arch'),
5
+ RbConfig::CONFIG.fetch('ruby_version'), 'allocated_classes').freeze
6
+ end
@@ -0,0 +1,23 @@
1
+ require 'rails_tia/described_class_support'
2
+ require 'rails_tia/native_extension'
3
+
4
+ module RailsTia
5
+ class ObjectAllocations
6
+ def initialize(root, directories:)
7
+ require ALLOCATION_EXTENSION
8
+ @tracker = AllocatedClasses.new
9
+ @resolver = DescribedClassSupport.new(root: root, directories: directories)
10
+ end
11
+
12
+ def start
13
+ @tracker.drain
14
+ @tracker.start
15
+ end
16
+
17
+ def stop = @tracker.stop
18
+
19
+ def flush
20
+ @tracker.drain.flat_map { |klass| @resolver.files_for(klass, include_anonymous: true) }.uniq
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,61 @@
1
+ require 'set'
2
+
3
+ module RailsTia
4
+ # Select spec files affected by a list of changed files.
5
+ #
6
+ # Take the union of three sources:
7
+ # 1. Reverse lookup in the coverage map (primary).
8
+ # 2. Static mappings for new files, templates, and missed classes without executable bodies.
9
+ # 3. Changed spec files themselves.
10
+ class Predictor
11
+ Result = Struct.new(:full_run, :reason, :reason_code, :matches, :specs, :sources, keyword_init: true) do
12
+ def full_run? = !!full_run
13
+ end
14
+
15
+ def initialize(config:, map:)
16
+ @config = config
17
+ @map = map
18
+ @static_mapping = StaticMapping.new(config.static_mapping_rules, root: config.root)
19
+ @fallback = Fallback.new(config: config, map: map)
20
+ end
21
+
22
+ def call(context, trace: false)
23
+ reason_code, reason = @fallback.decision(context)
24
+ if reason
25
+ return Result.new(full_run: true, reason: reason, reason_code: reason_code,
26
+ specs: @config.all_specs, sources: context.changed_files)
27
+ end
28
+
29
+ specs = Set.new
30
+ glob_cache = {}
31
+ static_by_source = {} if trace
32
+ context.changed_files.each do |path|
33
+ static = @static_mapping.candidates_for(path, glob_cache: glob_cache)
34
+ specs.merge(@map.specs_for(path)).merge(static)
35
+ specs << path if spec_file?(path)
36
+ static_by_source[path] = static if trace
37
+ end
38
+
39
+ specs.keep_if { |spec| File.exist?(File.join(@config.root, spec)) }
40
+ matches = match_counts(static_by_source, specs) if trace
41
+ Result.new(full_run: false, matches: matches, specs: specs.sort, sources: context.changed_files)
42
+ end
43
+
44
+ private
45
+
46
+ def spec_file?(path)
47
+ File.fnmatch?(@config.spec_glob, path, Configuration::FNMATCH_FLAGS)
48
+ end
49
+
50
+ def match_counts(static_by_source, selected)
51
+ static_by_source.to_h do |source, static|
52
+ counts = {
53
+ mapped_specs: @map.specs_for(source).count { |spec| selected.include?(spec) },
54
+ static_specs: static.count { |spec| selected.include?(spec) },
55
+ changed_spec: spec_file?(source) && selected.include?(source),
56
+ }
57
+ [source, counts]
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,86 @@
1
+ require 'set'
2
+
3
+ module RailsTia
4
+ # Rails-specific dependency supplementation.
5
+ #
6
+ # Classes like this have no lines executed after loading, so runtime usage is invisible to coverage.
7
+ #
8
+ # class Account < ApplicationRecord
9
+ # belongs_to :user
10
+ # end
11
+ #
12
+ # Use ActiveRecord notifications to identify models touched by each spec,
13
+ # then resolve definition files with Module.const_source_location and add dependencies.
14
+ #
15
+ # In one Rails application, this increased dependency edges from 402 to 594 (+48%).
16
+ # Without supplementation, roughly one third of those dependencies were missed.
17
+ class RailsSupport
18
+ # payload[:name] has a form such as "User Load" or "User Create".
19
+ # Non-model names such as SCHEMA and TRANSACTION are rejected during constant source resolution.
20
+ SQL_EVENT = 'sql.active_record'.freeze
21
+ INSTANTIATION_EVENT = 'instantiation.active_record'.freeze
22
+
23
+ def self.available?
24
+ defined?(::ActiveSupport::Notifications) ? true : false
25
+ end
26
+
27
+ def initialize(root:)
28
+ @root = root.end_with?('/') ? root : "#{root}/"
29
+ @files = Set.new
30
+ @source_location_cache = {}
31
+ @subscriptions = []
32
+ end
33
+
34
+ def subscribe
35
+ return self unless @subscriptions.empty?
36
+
37
+ @subscriptions << ::ActiveSupport::Notifications.subscribe(INSTANTIATION_EVENT) do |*, payload|
38
+ record(payload[:class_name])
39
+ end
40
+ @subscriptions << ::ActiveSupport::Notifications.subscribe(SQL_EVENT) do |*, payload|
41
+ record(payload[:name].to_s.split(' ').first)
42
+ end
43
+ self
44
+ end
45
+
46
+ def unsubscribe
47
+ @subscriptions.each { |token| ::ActiveSupport::Notifications.unsubscribe(token) }
48
+ @subscriptions.clear
49
+ @files.clear
50
+ end
51
+
52
+ # Return files touched since the previous flush and reset the accumulated set.
53
+ def flush
54
+ files = @files.to_a
55
+ @files = Set.new
56
+ files
57
+ end
58
+
59
+ private
60
+
61
+ def record(class_name)
62
+ return if class_name.nil? || class_name.empty?
63
+
64
+ path = source_location_of(class_name)
65
+ @files << path unless path.nil?
66
+ end
67
+
68
+ # Cache resolution results because the same class may be reported hundreds of times per spec.
69
+ def source_location_of(class_name)
70
+ return @source_location_cache[class_name] if @source_location_cache.key?(class_name)
71
+
72
+ @source_location_cache[class_name] = resolve(class_name)
73
+ end
74
+
75
+ def resolve(class_name)
76
+ location = Module.const_source_location(class_name)
77
+ path = location&.first
78
+ return nil if path.nil? || !path.start_with?(@root)
79
+
80
+ path.delete_prefix(@root)
81
+ rescue NameError
82
+ # Names that cannot be resolved as constants, such as SQL and SCHEMA, are not model dependencies.
83
+ nil
84
+ end
85
+ end
86
+ end