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,42 @@
1
+ require 'set'
2
+
3
+ module RailsTia
4
+ # Check predictions for missed failures.
5
+ #
6
+ # Check whether specs that failed in a full-suite JUnit report were predicted for the same change.
7
+ # A missing spec indicates a gap in the dependency map or configuration.
8
+ #
9
+ # Keep auditing full-suite runs in CI to detect failures silently omitted by selective execution.
10
+ class Audit
11
+ Result = Struct.new(:failed_specs, :predicted_specs, :missed_specs, :validation_errors, keyword_init: true) do
12
+ def ok? = Array(validation_errors).empty? && missed_specs.empty?
13
+
14
+ def summary
15
+ unless Array(validation_errors).empty?
16
+ return "[rails_tia] Cannot validate audit:\n" + validation_errors.map { |error| " - #{error}" }.join("\n")
17
+ end
18
+
19
+ return "[rails_tia] No missed failures (all #{failed_specs.size} failing specs were predicted)" if ok?
20
+
21
+ "[rails_tia] Prediction missed #{missed_specs.size} failing specs:\n" +
22
+ missed_specs.sort.map { |spec| " - #{spec}" }.join("\n")
23
+ end
24
+ end
25
+
26
+ def initialize(junit_report:, predicted_specs:, full_run: false)
27
+ @junit_report = junit_report
28
+ @predicted_specs = Set.new(predicted_specs)
29
+ @full_run = full_run
30
+ end
31
+
32
+ def call
33
+ failed = @junit_report.failed_files
34
+ Result.new(
35
+ failed_specs: failed,
36
+ predicted_specs: @predicted_specs,
37
+ missed_specs: @full_run ? Set.new : failed - @predicted_specs,
38
+ validation_errors: @junit_report.validation_errors,
39
+ )
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,12 @@
1
+ # Start Coverage before the test framework or application when generating a map.
2
+ #
3
+ # bundle exec ruby -rrails_tia/boot -S rspec ...
4
+ #
5
+ # For a combined RSpec run, start SimpleCov first so it can choose the coverage modes.
6
+ # One-shot line coverage cannot identify later specs that execute the same line.
7
+ require 'coverage'
8
+
9
+ # Bootsnap's instruction sequence cache cannot compile while coverage is active on Ruby 3.4.
10
+ ENV['DISABLE_BOOTSNAP_COMPILE_CACHE'] = '1'
11
+
12
+ Coverage.start(lines: true) unless Coverage.running?
@@ -0,0 +1,38 @@
1
+ module RailsTia
2
+ module Ci
3
+ # CI adapter interface.
4
+ # Keep CI-specific details behind this interface so Predictor and downstream logic stay CI-independent.
5
+ class Base
6
+ class UnsupportedError < StandardError; end
7
+
8
+ def initialize(config)
9
+ @config = config
10
+ end
11
+
12
+ def self.available?
13
+ false
14
+ end
15
+
16
+ # Collect inputs for prediction.
17
+ def context
18
+ Context.new(
19
+ changed_files: changed_files,
20
+ labels: labels,
21
+ commit_message: commit_message,
22
+ merge_request: merge_request?,
23
+ )
24
+ end
25
+
26
+ def changed_files = raise(NotImplementedError)
27
+ def merge_request? = raise(NotImplementedError)
28
+ def labels = []
29
+ def commit_message = nil
30
+ def map_download_dir = @config.map_fragment_dir
31
+
32
+ # Download map fragments to dest_dir and return their paths.
33
+ def fetch_map_fragments(_dest_dir)
34
+ raise UnsupportedError, "#{self.class.name} does not support map fetching"
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,49 @@
1
+ require 'open3'
2
+ require 'rails_tia/ci/base'
3
+
4
+ module RailsTia
5
+ module Ci
6
+ # Generic adapter that uses Git without a CI API.
7
+ # Prefer CI-specific adapters because shallow clones may lack the common ancestor needed for a diff.
8
+ class Git < Base
9
+ class CommandError < StandardError; end
10
+
11
+ DEFAULT_BASE = 'origin/master'.freeze
12
+
13
+ def self.available?
14
+ system('git rev-parse --git-dir', out: File::NULL, err: File::NULL)
15
+ end
16
+
17
+ def merge_request?
18
+ true
19
+ end
20
+
21
+ def changed_files
22
+ changed_paths("#{base}...HEAD")
23
+ end
24
+
25
+ def commit_message
26
+ capture('git', 'log', '-1', '--pretty=%B')
27
+ end
28
+
29
+ private
30
+
31
+ def changed_paths(revision)
32
+ capture('git', 'diff', '--name-only', '--no-renames', '-z', revision).split("\0")
33
+ end
34
+
35
+ def base
36
+ ENV['RAILS_TIA_DIFF_BASE'] || DEFAULT_BASE
37
+ end
38
+
39
+ def capture(*command)
40
+ stdout, stderr, status = Open3.capture3(*command, chdir: @config.root)
41
+ unless status.success?
42
+ raise CommandError, "Command failed: #{command.join(' ')}: #{stderr.strip}"
43
+ end
44
+
45
+ stdout
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,237 @@
1
+ require 'fileutils'
2
+ require 'stringio'
3
+ require 'tmpdir'
4
+ require 'zip'
5
+ require 'rails_tia/ci/git'
6
+ require 'rails_tia/http'
7
+
8
+ module RailsTia
9
+ module Ci
10
+ class GithubActions < Git
11
+ class Error < StandardError; end
12
+
13
+ def merge_request?
14
+ ENV['GITHUB_EVENT_NAME'] == 'pull_request'
15
+ end
16
+
17
+ def changed_files
18
+ return [] unless merge_request?
19
+
20
+ changed_paths("#{base_commit}..HEAD")
21
+ end
22
+
23
+ def labels
24
+ return [] unless merge_request?
25
+
26
+ labels = pull_request.fetch('labels', [])
27
+ unless labels.is_a?(Array) && labels.all? { |label| label.is_a?(Hash) && label['name'].is_a?(String) }
28
+ raise Error, 'Invalid labels in the GitHub pull_request event'
29
+ end
30
+
31
+ labels.map { |label| label.fetch('name') }
32
+ end
33
+
34
+ def commit_message
35
+ return unless merge_request?
36
+
37
+ capture('git', 'log', '-1', '--pretty=%B', merge_checkout? ? 'HEAD^2' : 'HEAD')
38
+ end
39
+
40
+ def map_download_dir = File.join(@config.map_fragment_dir, 'github-actions')
41
+
42
+ def fetch_map_fragments(dest_dir)
43
+ return [] unless merge_request?
44
+
45
+ run = map_run
46
+ return [] unless run
47
+
48
+ artifact = map_artifact(run)
49
+ return [] if artifact.nil? || artifact.fetch('expired')
50
+
51
+ archive = download_artifact(run, artifact.fetch('id'))
52
+ return [] unless archive
53
+
54
+ stage_map(archive, artifact.fetch('id'), dest_dir)
55
+ end
56
+
57
+ private
58
+
59
+ def base_commit
60
+ # Derive the baseline from the checked-out merge commit so a moving base branch
61
+ # cannot make the Git diff and downloaded map describe different commits.
62
+ @base_commit ||= merge_checkout? ? merge_checkout_base : head_merge_base
63
+ end
64
+
65
+ def merge_checkout_base
66
+ capture('git', 'rev-parse', '--verify', 'HEAD^1').strip
67
+ rescue CommandError => e
68
+ raise Error, "Cannot read the PR merge commit's base parent. Set actions/checkout fetch-depth: 2. #{e.message}"
69
+ end
70
+
71
+ def head_merge_base
72
+ unless checkout_sha == pull_request.dig('head', 'sha')
73
+ raise Error, 'Check out the GitHub pull request merge commit or pull request head'
74
+ end
75
+
76
+ base_sha = pull_request.dig('base', 'sha')
77
+ unless base_sha.is_a?(String) && base_sha.match?(/\A[0-9a-f]{40}\z/)
78
+ raise Error, 'Missing or invalid base SHA in the GitHub pull_request event'
79
+ end
80
+
81
+ capture('git', 'merge-base', base_sha, 'HEAD').strip
82
+ rescue TypeError
83
+ raise Error, 'Invalid head or base data in the GitHub pull_request event'
84
+ end
85
+
86
+ def checkout_sha
87
+ @checkout_sha ||= capture('git', 'rev-parse', 'HEAD').strip
88
+ end
89
+
90
+ def merge_checkout?
91
+ ENV['GITHUB_REF'].to_s.match?(%r{\Arefs/pull/\d+/merge\z}) && checkout_sha == ENV['GITHUB_SHA']
92
+ end
93
+
94
+ def pull_request
95
+ @pull_request ||= begin
96
+ event = JSON.parse(File.read(environment('GITHUB_EVENT_PATH')))
97
+ pr = event['pull_request'] if event.is_a?(Hash)
98
+ raise Error, 'Missing pull_request data in the GitHub event' unless pr.is_a?(Hash)
99
+
100
+ pr
101
+ end
102
+ rescue JSON::ParserError, SystemCallError => e
103
+ raise Error, "Cannot read the GitHub pull_request event: #{e.message}"
104
+ end
105
+
106
+ def map_run
107
+ workflow = option('map_workflow')
108
+ unless workflow.match?(/\A(\d+|[\w.-]+\.ya?ml)\z/)
109
+ raise Error, 'ci.github_actions.map_workflow must be a workflow filename or numeric ID'
110
+ end
111
+
112
+ event = option('map_event')
113
+ unless %w(push schedule).include?(event)
114
+ raise Error, 'ci.github_actions.map_event must be push or schedule'
115
+ end
116
+
117
+ query = URI.encode_www_form(branch: environment('GITHUB_BASE_REF'), event: event,
118
+ status: 'success', head_sha: base_commit, per_page: 1)
119
+ run = response_items("#{actions_path}/workflows/#{workflow}/runs?#{query}", 'workflow_runs').first
120
+ if run && (run['head_sha'] != base_commit || !valid_id?(run['id']))
121
+ raise Error, 'Invalid GitHub map workflow run or unexpected source commit'
122
+ end
123
+
124
+ run
125
+ end
126
+
127
+ def map_artifact(run)
128
+ name = option('map_artifact_name')
129
+ query = URI.encode_www_form(name: name, per_page: 2)
130
+ artifacts = response_items("#{actions_path}/runs/#{run.fetch('id')}/artifacts?#{query}", 'artifacts')
131
+ if artifacts.empty?
132
+ warn "[rails_tia] No #{name.inspect} map artifact in GitHub workflow run #{run.fetch('id')}"
133
+ return
134
+ end
135
+
136
+ artifact = artifacts.first
137
+ unless artifacts.size == 1 && artifact['name'] == name && valid_id?(artifact['id']) &&
138
+ [true, false].include?(artifact['expired'])
139
+ raise Error, "Expected one #{name.inspect} map artifact in GitHub workflow run #{run.fetch('id')}"
140
+ end
141
+
142
+ artifact
143
+ end
144
+
145
+ def download_artifact(run, artifact_id)
146
+ http.get("#{actions_path}/artifacts/#{artifact_id}/zip")
147
+ rescue Http::Gone
148
+ nil
149
+ rescue Http::NotFound
150
+ # A 404 alone can also mean the token cannot access the resource.
151
+ artifact = map_artifact(run)
152
+ raise if artifact && artifact.fetch('id') == artifact_id && !artifact.fetch('expired')
153
+
154
+ nil
155
+ end
156
+
157
+ def stage_map(archive, artifact_id, dest_dir)
158
+ FileUtils.mkdir_p(dest_dir)
159
+ Dir.mktmpdir('fetch-', dest_dir) do |staging|
160
+ path = extract_map(archive, artifact_id, staging)
161
+ map = Map.load(path)
162
+ if map.empty? || map.commit_sha != base_commit || map.generated_at.nil?
163
+ raise Map::FormatError, "Invalid map or unexpected source commit in GitHub artifact #{artifact_id}"
164
+ end
165
+ return [] if map.stale?(max_age_days: @config.map_max_age_days)
166
+
167
+ output = File.join(dest_dir, File.basename(path))
168
+ File.rename(path, output)
169
+ [output]
170
+ end
171
+ rescue Zip::Error => e
172
+ raise Map::FormatError, "Invalid ZIP for GitHub map artifact #{artifact_id}: #{e.message}"
173
+ end
174
+
175
+ def extract_map(archive, artifact_id, staging)
176
+ path = nil
177
+ Zip::File.open_buffer(StringIO.new(archive)) do |zip|
178
+ entries = zip.entries.reject(&:directory?).select { |entry| entry.name.end_with?('.json', '.json.gz') }
179
+ unless entries.size == 1
180
+ raise Map::FormatError, 'Expected exactly one merged map (.json or .json.gz) in the GitHub artifact'
181
+ end
182
+
183
+ entry = entries.first
184
+ extension = entry.name.end_with?('.gz') ? '.json.gz' : '.json'
185
+ path = File.join(staging, "github-actions-#{artifact_id}#{extension}")
186
+ File.binwrite(path, zip.get_input_stream(entry).read)
187
+ end
188
+ path
189
+ end
190
+
191
+ def response_items(path, key)
192
+ payload = http.get_json(path)
193
+ items = payload[key] if payload.is_a?(Hash)
194
+ return items if items.is_a?(Array) && items.all?(Hash)
195
+
196
+ raise Error, "Invalid GitHub API response for #{path}: expected #{key} array"
197
+ rescue JSON::ParserError
198
+ raise Error, "Invalid JSON in GitHub API response for #{path}"
199
+ end
200
+
201
+ def valid_id?(id) = id.is_a?(Integer) && id.positive?
202
+
203
+ def option(name)
204
+ value = @config.github_actions_options[name].to_s
205
+ raise Error, "Set ci.github_actions.#{name} to fetch maps from GitHub Actions" if value.empty?
206
+
207
+ value
208
+ end
209
+
210
+ def actions_path
211
+ repository = environment('GITHUB_REPOSITORY')
212
+ unless repository.match?(%r{\A[\w-]+/[\w.-]+\z})
213
+ raise Error, 'Invalid GITHUB_REPOSITORY; expected owner/repository'
214
+ end
215
+
216
+ "/repos/#{repository}/actions"
217
+ end
218
+
219
+ def http
220
+ @http ||= Http.new(
221
+ base_url: environment('GITHUB_API_URL'),
222
+ headers: {
223
+ 'Accept' => 'application/vnd.github+json',
224
+ 'Authorization' => "Bearer #{environment('GITHUB_TOKEN')}",
225
+ },
226
+ )
227
+ end
228
+
229
+ def environment(name)
230
+ value = ENV[name].to_s
231
+ raise Error, "Set #{name} to use the github_actions adapter" if value.empty?
232
+
233
+ value
234
+ end
235
+ end
236
+ end
237
+ end
@@ -0,0 +1,199 @@
1
+ require 'fileutils'
2
+ require 'stringio'
3
+ require 'tmpdir'
4
+ require 'zip'
5
+ require 'rails_tia/http'
6
+ require 'rails_tia/ci/base'
7
+
8
+ module RailsTia
9
+ module Ci
10
+ # GitLab CI adapter.
11
+ #
12
+ # Do not use Git for changed files: shallow CI clones (GIT_DEPTH) may lack the common
13
+ # ancestor with the target branch, making git diff origin/master...HEAD unavailable.
14
+ # Fetch merge request diffs through the API instead.
15
+ class Gitlab < Base
16
+ class AuthenticationError < StandardError; end
17
+
18
+ PER_PAGE = 100
19
+
20
+ def self.available?
21
+ !ENV['CI_API_V4_URL'].to_s.empty? && !ENV['CI_PROJECT_ID'].to_s.empty?
22
+ end
23
+
24
+ def merge_request?
25
+ ENV['CI_PIPELINE_SOURCE'] == 'merge_request_event'
26
+ end
27
+
28
+ def labels
29
+ ENV['CI_MERGE_REQUEST_LABELS'].to_s.split(',').map(&:strip).reject(&:empty?)
30
+ end
31
+
32
+ def commit_message
33
+ ENV['CI_COMMIT_MESSAGE']
34
+ end
35
+
36
+ def changed_files
37
+ iid = ENV['CI_MERGE_REQUEST_IID']
38
+ return [] if iid.to_s.empty?
39
+
40
+ paths = []
41
+ each_page("/projects/#{project_id}/merge_requests/#{iid}/diffs") do |diff|
42
+ # Include dependencies of the old path when a file is renamed or deleted.
43
+ paths << diff['new_path'] unless diff['deleted_file']
44
+ paths << diff['old_path']
45
+ end
46
+ paths.compact.uniq
47
+ end
48
+
49
+ def fetch_map_fragments(dest_dir)
50
+ pipeline = latest_map_pipeline
51
+ if pipeline.nil?
52
+ warn '[rails_tia] No map-generation pipeline found'
53
+ return []
54
+ end
55
+
56
+ warn "[rails_tia] Map source pipeline: #{pipeline['id']} (#{pipeline['created_at']})"
57
+ FileUtils.mkdir_p(dest_dir)
58
+
59
+ jobs = pipeline_jobs(pipeline['id']).select { |job| map_job?(job['name']) }
60
+ validate_map_jobs!(jobs)
61
+ # Validate everything in staging; do not publish partial fragments if any step fails.
62
+ Dir.mktmpdir('fetch-', dest_dir) do |staging|
63
+ fragments = jobs.flat_map do |job|
64
+ downloaded = download_fragments(job, staging)
65
+ raise Map::FormatError, "No map fragments found for #{job['name']}" if downloaded.empty?
66
+
67
+ downloaded.each { |path| validate_fragment!(path, pipeline) }
68
+ downloaded
69
+ end
70
+ fragments.map do |path|
71
+ output = File.join(dest_dir, File.basename(path))
72
+ FileUtils.mv(path, output)
73
+ output
74
+ end
75
+ end
76
+ end
77
+
78
+ private
79
+
80
+ def options = @config.gitlab_options
81
+ def project_id = ENV.fetch('CI_PROJECT_ID')
82
+
83
+ def http
84
+ @http ||= Http.new(
85
+ base_url: ENV.fetch('CI_API_V4_URL'),
86
+ headers: auth_header,
87
+ )
88
+ end
89
+
90
+ # A normal CI_JOB_TOKEN is insufficient for MR diffs and pipeline/job discovery.
91
+ def auth_header
92
+ token = ENV['RAILS_TIA_GITLAB_TOKEN']
93
+ if token.to_s.empty?
94
+ raise AuthenticationError,
95
+ 'GitLab API requires RAILS_TIA_GITLAB_TOKEN with read_api scope. CI_JOB_TOKEN alone does not support MR diffs or map discovery'
96
+ end
97
+
98
+ { 'PRIVATE-TOKEN' => token }
99
+ end
100
+
101
+ def each_page(path)
102
+ page = 1
103
+ loop do
104
+ separator = path.include?('?') ? '&' : '?'
105
+ chunk = http.get_json("#{path}#{separator}per_page=#{PER_PAGE}&page=#{page}")
106
+ break if chunk.empty?
107
+
108
+ chunk.each { |item| yield item }
109
+ break if chunk.size < PER_PAGE
110
+
111
+ page += 1
112
+ end
113
+ end
114
+
115
+ def latest_map_pipeline
116
+ # Encode values so refs containing characters such as + or # are not altered.
117
+ query = URI.encode_www_form(
118
+ ref: options.fetch('map_ref'),
119
+ status: 'success',
120
+ source: options.fetch('map_pipeline_source'),
121
+ per_page: 1,
122
+ )
123
+ http.get_json("/projects/#{project_id}/pipelines?#{query}").first
124
+ end
125
+
126
+ def pipeline_jobs(pipeline_id)
127
+ jobs = []
128
+ each_page("/projects/#{project_id}/pipelines/#{pipeline_id}/jobs?include_retried=false") { |job| jobs << job }
129
+ jobs
130
+ end
131
+
132
+ # Parallel job names look like "rails_tia_map 3/18", so match by prefix.
133
+ def map_job?(name)
134
+ expected = options['map_job_name']
135
+ return false if expected.to_s.empty?
136
+
137
+ name == expected || name.start_with?("#{expected} ")
138
+ end
139
+
140
+ # Listing only successful nodes would misidentify failed or missing nodes as a complete map.
141
+ def validate_map_jobs!(jobs)
142
+ expected = options['map_job_name']
143
+ raise Map::FormatError, "No map-generation jobs found: #{expected.inspect}" if jobs.empty?
144
+ unless jobs.all? { |job| job['status'] == 'success' }
145
+ raise Map::FormatError, 'Not all map-generation jobs succeeded'
146
+ end
147
+ return if jobs.size == 1 && jobs.first['name'] == expected
148
+
149
+ matches = jobs.map { |job| job['name'].match(/\A#{Regexp.escape(expected)} (\d+)\/(\d+)\z/) }
150
+ if matches.any?(&:nil?)
151
+ raise Map::FormatError, 'Map-generation job names must use a single job name or the name index/total format'
152
+ end
153
+ totals = matches.map { |match| match[2].to_i }.uniq
154
+ indices = matches.map { |match| match[1].to_i }.sort
155
+ unless totals.size == 1 && totals.first.positive? && indices == (1..totals.first).to_a
156
+ raise Map::FormatError, 'Map-generation nodes are missing or duplicated'
157
+ end
158
+ end
159
+
160
+ def validate_fragment!(path, pipeline)
161
+ map = Map.load(path)
162
+ raise Map::FormatError, "Empty map fragment: #{path}" if map.empty?
163
+ raise Map::FormatError, "Invalid or stale map fragment: #{path}" if map.stale?(max_age_days: @config.map_max_age_days)
164
+ if pipeline['sha'] && map.commit_sha != pipeline['sha']
165
+ raise Map::FormatError, "Map fragment does not match the source commit: #{path}"
166
+ end
167
+ end
168
+
169
+ # Enumerate job artifacts instead of guessing filenames or process counts.
170
+ def download_fragments(job, dest_dir)
171
+ archive = http.get("/projects/#{project_id}/jobs/#{job['id']}/artifacts")
172
+ saved = []
173
+ Zip::File.open_buffer(StringIO.new(archive)) do |zip|
174
+ saved = zip.entries.reject(&:directory?).select { |entry| fragment_entry?(entry.name) }.sort_by(&:name)
175
+ .each_with_index.map do |entry, index|
176
+ # Do not use archive entry paths as output paths; avoid collisions and path traversal.
177
+ output = File.join(dest_dir, "job_#{job['id']}_#{index}_#{File.basename(entry.name)}")
178
+ File.binwrite(output, zip.get_input_stream(entry).read)
179
+ output
180
+ end
181
+ end
182
+ saved
183
+ rescue Http::Error, Zip::Error => e
184
+ raise Map::FormatError, "Cannot fetch artifacts for #{job['name']}: #{e.message}"
185
+ end
186
+
187
+ def fragment_entry?(name)
188
+ return false unless name.end_with?('.json', '.json.gz')
189
+
190
+ pattern = options['map_artifact_glob']
191
+ if pattern.to_s.empty?
192
+ pattern = @config.map_fragment_dir.delete_prefix("#{@config.root}/")
193
+ end
194
+ pattern = "#{pattern.chomp('/')}/**/*.json*" unless pattern.match?(/[\*?\[{]/) || pattern.end_with?('.json', '.json.gz')
195
+ File.fnmatch?(pattern, name, Configuration::FNMATCH_FLAGS)
196
+ end
197
+ end
198
+ end
199
+ end
@@ -0,0 +1,36 @@
1
+ require 'rails_tia/ci/base'
2
+ require 'rails_tia/ci/gitlab'
3
+ require 'rails_tia/ci/git'
4
+ require 'rails_tia/ci/github_actions'
5
+
6
+ module RailsTia
7
+ module Ci
8
+ ADAPTERS = {
9
+ 'gitlab' => Gitlab,
10
+ 'github_actions' => GithubActions,
11
+ 'git' => Git,
12
+ }.freeze
13
+
14
+ # In auto mode, prefer a CI-specific adapter and fall back to Git if none is available.
15
+ AUTO_ORDER = %w(gitlab git).freeze
16
+
17
+ class UnknownAdapterError < StandardError; end
18
+
19
+ def self.build(config)
20
+ name = config.ci_adapter
21
+ return build_auto(config) if name == 'auto'
22
+
23
+ klass = ADAPTERS[name]
24
+ raise UnknownAdapterError, "Unknown CI adapter: #{name.inspect}" if klass.nil?
25
+
26
+ klass.new(config)
27
+ end
28
+
29
+ def self.build_auto(config)
30
+ name = AUTO_ORDER.find { |candidate| ADAPTERS.fetch(candidate).available? }
31
+ raise UnknownAdapterError, 'No CI adapter is available' if name.nil?
32
+
33
+ ADAPTERS.fetch(name).new(config)
34
+ end
35
+ end
36
+ end