spm_version_updates 1.2.0 → 3.0.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.
@@ -0,0 +1,481 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "git_operations"
4
+ require_relative "manifest_parser"
5
+ require_relative "semver"
6
+
7
+ # Rewrites supported Package.swift dependency requirements for update records.
8
+ module ManifestUpdater
9
+ SUPPORTED_KINDS = %w(exactVersion upToNextMajorVersion upToNextMinorVersion versionRange).freeze
10
+
11
+ # Result of rewriting one manifest's dependency declarations.
12
+ Result = Struct.new(:content, :applied, :skipped, :changed, keyword_init: true) {
13
+ def changed?
14
+ changed
15
+ end
16
+ }
17
+
18
+ def self.rewrite(content, updates)
19
+ Rewriter.new(content, updates).rewrite
20
+ end
21
+
22
+ def self.update_file(manifest_path, updates)
23
+ original = File.read(manifest_path)
24
+ result = rewrite(original, updates)
25
+ File.write(manifest_path, result.content) if result.changed?
26
+ result
27
+ end
28
+
29
+ # Normalized update input used by the private rewrite pipeline.
30
+ class UpdateRecord
31
+ def initialize(attributes)
32
+ @attributes = attributes.to_h.transform_keys(&:to_s)
33
+ end
34
+
35
+ def kind
36
+ value("requirement_kind")
37
+ end
38
+
39
+ def type
40
+ value("type")
41
+ end
42
+
43
+ def normalized_url
44
+ value("normalized_url")
45
+ end
46
+
47
+ def available_version
48
+ value("available_version")
49
+ end
50
+
51
+ def applied_entry
52
+ @attributes.merge("available_version" => available_version)
53
+ end
54
+
55
+ def skipped_entry(reason)
56
+ @attributes.merge("reason" => reason)
57
+ end
58
+
59
+ private
60
+
61
+ def value(key)
62
+ @attributes[key]
63
+ end
64
+ end
65
+ private_constant :UpdateRecord
66
+
67
+ # Collects the rewrite outcome while package declarations are scanned.
68
+ class RewriteChanges
69
+ attr_reader :edits, :applied, :skipped
70
+
71
+ def initialize
72
+ @edits = []
73
+ @applied = []
74
+ @skipped = []
75
+ end
76
+
77
+ def apply(update, edits)
78
+ @edits.concat(edits)
79
+ @applied << update.applied_entry
80
+ end
81
+
82
+ def skip(update, reason)
83
+ @skipped << update.skipped_entry(reason)
84
+ end
85
+ end
86
+ private_constant :RewriteChanges
87
+
88
+ # Success or failure from attempting to rewrite one update record.
89
+ RewritePlan = Struct.new(:edits, :reason, keyword_init: true) {
90
+ def self.success(edits)
91
+ new(edits:, reason: nil)
92
+ end
93
+
94
+ def self.failure(reason)
95
+ new(edits: [], reason:)
96
+ end
97
+
98
+ def failed?
99
+ reason
100
+ end
101
+ }
102
+ private_constant :RewritePlan
103
+
104
+ # Computes all declaration edits for one update record.
105
+ class EditPlanner
106
+ def initialize(update, spans)
107
+ @update = update
108
+ @spans = spans
109
+ end
110
+
111
+ def plan
112
+ return RewritePlan.failure("declaration_not_found") if matching_spans.empty?
113
+
114
+ plan_matching_spans
115
+ end
116
+
117
+ private
118
+
119
+ attr_reader :update
120
+
121
+ def matching_spans
122
+ @matching_spans ||= @spans.select { |span| SpanPackage.new(span).normalized_url == update.normalized_url }
123
+ end
124
+
125
+ def plan_matching_spans
126
+ attempts = matching_spans.map { |span| EditAttempt.new(update, span).plan }
127
+ attempts.find(&:failed?) || RewritePlan.success(attempts.flat_map(&:edits))
128
+ end
129
+ end
130
+ private_constant :EditPlanner
131
+
132
+ # Package metadata parsed from one declaration span.
133
+ class SpanPackage
134
+ def initialize(span)
135
+ @span = span
136
+ end
137
+
138
+ def normalized_url
139
+ GitOperations.trim_repo_url(url.value)
140
+ end
141
+
142
+ private
143
+
144
+ def url
145
+ UrlLiteral.new(@span.body)
146
+ end
147
+ end
148
+ private_constant :SpanPackage
149
+
150
+ # Reads a Package.swift dependency URL literal from one declaration body.
151
+ class UrlLiteral
152
+ def initialize(body)
153
+ @body = body
154
+ end
155
+
156
+ def value
157
+ @body[/\burl\s*:\s*"([^"]+)"/, 1]
158
+ end
159
+ end
160
+ private_constant :UrlLiteral
161
+
162
+ # Source body checks that determine whether a declaration can be safely edited.
163
+ class DeclarationBody
164
+ def initialize(body)
165
+ @body = body
166
+ end
167
+
168
+ def unsupported_syntax?
169
+ @body.include?("\\(") || @body.match?(/#+"/)
170
+ end
171
+ end
172
+ private_constant :DeclarationBody
173
+
174
+ # Attempts the single-span edit for one update and returns a rewrite plan.
175
+ class EditAttempt
176
+ def initialize(update, span)
177
+ @update = update
178
+ @span = span
179
+ end
180
+
181
+ def plan
182
+ return RewritePlan.failure("unsupported_syntax") if unsupported_syntax?
183
+ return RewritePlan.failure("requirement_mismatch") unless requirement_matches? && edit
184
+ return RewritePlan.failure("verification_failed") unless verifier.verified?
185
+
186
+ RewritePlan.success([edit])
187
+ end
188
+
189
+ private
190
+
191
+ attr_reader :update, :span
192
+
193
+ def unsupported_syntax?
194
+ DeclarationBody.new(span.body).unsupported_syntax?
195
+ end
196
+
197
+ def requirement_matches?
198
+ requirement && requirement["kind"] == update.kind
199
+ end
200
+
201
+ def requirement
202
+ @requirement ||= ManifestParser.requirement_for(span.body)
203
+ end
204
+
205
+ def edit
206
+ @edit ||= RequirementEdit.new(update, span).to_h
207
+ end
208
+
209
+ def verifier
210
+ EditVerifier.new(update, span, edit)
211
+ end
212
+ end
213
+ private_constant :EditAttempt
214
+
215
+ # Builds the byte-range replacement for one supported requirement.
216
+ class RequirementEdit
217
+ def initialize(update, span)
218
+ @update = update
219
+ @span = span
220
+ end
221
+
222
+ def to_h
223
+ return unless target && offset
224
+
225
+ body_start = span.body_start
226
+ {
227
+ start: body_start + offset[0],
228
+ finish: body_start + offset[1],
229
+ replacement: target
230
+ }
231
+ end
232
+
233
+ private
234
+
235
+ attr_reader :update, :span
236
+
237
+ def target
238
+ @target ||= TargetVersion.new(update, span.body).value
239
+ end
240
+
241
+ def offset
242
+ @offset ||= VersionLiteralLocator.new(span.body, update).offset
243
+ end
244
+ end
245
+ private_constant :RequirementEdit
246
+
247
+ # Chooses the target version, including range upper-bound expansion.
248
+ class TargetVersion
249
+ def initialize(update, body)
250
+ @update = update
251
+ @body = body
252
+ end
253
+
254
+ def value
255
+ return @update.available_version unless expand_range_maximum?
256
+
257
+ maximum_for_range
258
+ end
259
+
260
+ private
261
+
262
+ def expand_range_maximum?
263
+ @update.kind == "versionRange" && @update.type == "above_maximum"
264
+ end
265
+
266
+ def maximum_for_range
267
+ available_version = @update.available_version
268
+ return available_version if range.closed?
269
+
270
+ version = SpmVersionUpdates::Semver.new(available_version)
271
+ "#{version.major + 1}.0.0"
272
+ rescue ArgumentError
273
+ nil
274
+ end
275
+
276
+ def range
277
+ @range ||= VersionRangeLiteral.new(@body)
278
+ end
279
+ end
280
+ private_constant :TargetVersion
281
+
282
+ # Locates the version literal that should be replaced inside a declaration.
283
+ class VersionLiteralLocator
284
+ def initialize(body, update)
285
+ @body = body
286
+ @update = update
287
+ end
288
+
289
+ def offset
290
+ case @update.kind
291
+ when "exactVersion" then exact_offset
292
+ when "upToNextMajorVersion" then major_offset
293
+ when "upToNextMinorVersion" then minor_offset
294
+ when "versionRange" then range_offset
295
+ end
296
+ end
297
+
298
+ private
299
+
300
+ def exact_offset
301
+ first_capture([/\bexact\s*:\s*"([^"]+)"/, /\.exact\s*\(\s*"([^"]+)"/])
302
+ end
303
+
304
+ def major_offset
305
+ first_capture([/\.upToNextMajor\s*\(\s*from\s*:\s*"([^"]+)"/, /\bfrom\s*:\s*"([^"]+)"/])
306
+ end
307
+
308
+ def minor_offset
309
+ first_capture([/\.upToNextMinor\s*\(\s*from\s*:\s*"([^"]+)"/])
310
+ end
311
+
312
+ def range
313
+ @range ||= VersionRangeLiteral.new(@body)
314
+ end
315
+
316
+ def range_offset
317
+ @update.type == "above_maximum" ? range.maximum_offset : range.minimum_offset
318
+ end
319
+
320
+ def first_capture(patterns)
321
+ patterns.each { |pattern|
322
+ match = @body.match(pattern)
323
+ return match.offset(1) if match
324
+ }
325
+ nil
326
+ end
327
+ end
328
+ private_constant :VersionLiteralLocator
329
+
330
+ # Parsed Swift range literal for supported version-range requirements.
331
+ class VersionRangeLiteral
332
+ def initialize(body)
333
+ @match = body.match(/"([^"]+)"\s*(\.\.[.<])\s*"([^"]+)"/)
334
+ end
335
+
336
+ def closed?
337
+ operator == "..."
338
+ end
339
+
340
+ def minimum_offset
341
+ return unless @match
342
+
343
+ @match.offset(1)
344
+ end
345
+
346
+ def maximum_offset
347
+ return unless @match
348
+
349
+ @match.offset(3)
350
+ end
351
+
352
+ private
353
+
354
+ def operator
355
+ @match&.[](2)
356
+ end
357
+ end
358
+ private_constant :VersionRangeLiteral
359
+
360
+ # Verifies a generated edit still parses to the original requirement kind.
361
+ class EditVerifier
362
+ def initialize(update, span, edit)
363
+ @update = update
364
+ @span = span
365
+ @edit = edit
366
+ end
367
+
368
+ def verified?
369
+ return false unless edited_requirement_kind == @update.kind
370
+
371
+ edited_value == @edit[:replacement]
372
+ end
373
+
374
+ private
375
+
376
+ def edited_requirement_kind
377
+ ManifestParser.requirement_for(edited_body)&.fetch("kind", nil)
378
+ end
379
+
380
+ def edited_value
381
+ offset = VersionLiteralLocator.new(edited_body, @update).offset
382
+ offset && edited_body[offset[0]...offset[1]]
383
+ end
384
+
385
+ def edited_body
386
+ @edited_body ||= EditedBody.new(@span, @edit).value
387
+ end
388
+ end
389
+ private_constant :EditVerifier
390
+
391
+ # Applies one edit against a declaration body for verification.
392
+ class EditedBody
393
+ def initialize(span, edit)
394
+ @span = span
395
+ @edit = edit
396
+ end
397
+
398
+ def value
399
+ @value ||= @span.body.dup.tap { |body| body[relative_range] = @edit[:replacement] }
400
+ end
401
+
402
+ private
403
+
404
+ def relative_range
405
+ relative_start...relative_finish
406
+ end
407
+
408
+ def relative_start
409
+ @edit[:start] - @span.body_start
410
+ end
411
+
412
+ def relative_finish
413
+ @edit[:finish] - @span.body_start
414
+ end
415
+ end
416
+ private_constant :EditedBody
417
+
418
+ # Applies collected edits from right to left to preserve byte offsets.
419
+ class AppliedEdit
420
+ def initialize(attributes)
421
+ @attributes = attributes
422
+ end
423
+
424
+ def start
425
+ @attributes[:start]
426
+ end
427
+
428
+ def apply_to(content)
429
+ content[start...@attributes[:finish]] = @attributes[:replacement]
430
+ end
431
+ end
432
+ private_constant :AppliedEdit
433
+
434
+ # Applies collected edits from right to left to preserve byte offsets.
435
+ class EditApplier
436
+ def initialize(content, edits)
437
+ @content = content
438
+ @edits = edits.map { |edit| AppliedEdit.new(edit) }
439
+ end
440
+
441
+ def content
442
+ @edits.sort_by { |edit| -edit.start }
443
+ .each_with_object(@content.dup) { |edit, updated|
444
+ edit.apply_to(updated)
445
+ }
446
+ end
447
+ end
448
+ private_constant :EditApplier
449
+
450
+ # Stateful implementation kept private so the public API remains small.
451
+ class Rewriter
452
+ def initialize(content, updates)
453
+ @content = content
454
+ @updates = Array(updates).map { |update| UpdateRecord.new(update) }
455
+ @spans = ManifestParser.package_call_spans(content)
456
+ @changes = RewriteChanges.new
457
+ end
458
+
459
+ def rewrite
460
+ @updates.each { |update| rewrite_update(update) }
461
+ updated_content = EditApplier.new(@content, @changes.edits).content
462
+ Result.new(content: updated_content, applied: @changes.applied, skipped: @changes.skipped, changed: updated_content != @content)
463
+ end
464
+
465
+ private
466
+
467
+ def rewrite_update(update)
468
+ plan = rewrite_plan(update)
469
+ return @changes.skip(update, plan.reason) if plan.failed?
470
+
471
+ @changes.apply(update, plan.edits)
472
+ end
473
+
474
+ def rewrite_plan(update)
475
+ return RewritePlan.failure("unsupported_requirement_kind") unless SUPPORTED_KINDS.include?(update.kind)
476
+
477
+ EditPlanner.new(update, @spans).plan
478
+ end
479
+ end
480
+ private_constant :Rewriter
481
+ end
@@ -27,13 +27,29 @@ module PackageResolved
27
27
  # @raise [MalformedFileError] if the file is not valid JSON
28
28
  # @return [Hash<String, String>] normalized repository URL => version or revision
29
29
  def self.versions_from(path)
30
+ pins_from(path).to_h { |pin| [pin["normalized_url"], pin["version"] || pin["revision"]] }
31
+ end
32
+
33
+ # Extract structured pins from a `Package.resolved` file.
34
+ #
35
+ # @param [String] path The path to a `Package.resolved` file
36
+ # @raise [MalformedFileError] if the file is not valid JSON
37
+ # @return [Array<Hash>] pin records with normalized_url, repository_url,
38
+ # version, and revision
39
+ def self.pins_from(path)
30
40
  contents = load_contents(path)
31
41
  pins = contents["pins"] || contents.dig("object", "pins") || []
32
- pins.to_h { |pin|
33
- [
34
- GitOperations.trim_repo_url(pin["location"] || pin["repositoryURL"]),
35
- pin.dig("state", "version") || pin.dig("state", "revision"),
36
- ]
42
+ pins.map { |pin| pin_record(pin) }
43
+ end
44
+
45
+ def self.pin_record(pin)
46
+ repository_url = pin["location"] || pin["repositoryURL"]
47
+ state = pin["state"] || {}
48
+ {
49
+ "normalized_url" => GitOperations.trim_repo_url(repository_url),
50
+ "repository_url" => repository_url,
51
+ "version" => state["version"],
52
+ "revision" => state["revision"]
37
53
  }
38
54
  end
39
55
 
@@ -43,5 +59,6 @@ module PackageResolved
43
59
  raise(MalformedFileError.new(path, error.message))
44
60
  end
45
61
 
46
- private_class_method :load_contents
62
+ private_class_method :load_contents,
63
+ :pin_record
47
64
  end
@@ -81,6 +81,25 @@ class RepositoryUpdateRules
81
81
  nil
82
82
  end
83
83
 
84
+ def self.record_value(record, key)
85
+ record[key] || record[key.to_sym]
86
+ end
87
+
88
+ def initialize(rules_by_repo)
89
+ @rules_by_repo = rules_by_repo
90
+ end
91
+
92
+ def empty?
93
+ @rules_by_repo.empty?
94
+ end
95
+
96
+ def suppressed?(record)
97
+ return false unless semantic_record?(record)
98
+
99
+ rule = @rules_by_repo[normalized_record_url(record)]
100
+ rule ? rule.suppressed?(record) : false
101
+ end
102
+
84
103
  def self.parse_repositories(repositories, source)
85
104
  repositories.each_with_object({}).with_index(1) { |(entry, rules), index|
86
105
  rule = parse_entry(entry, "#{source} repositories[#{index}]")
@@ -170,10 +189,6 @@ class RepositoryUpdateRules
170
189
  raise(SpmVersionUpdates::ConfigurationError, "#{source} #{key} must be patch, minor, or major")
171
190
  end
172
191
 
173
- def self.record_value(record, key)
174
- record[key] || record[key.to_sym]
175
- end
176
-
177
192
  def self.yaml_key(name)
178
193
  YAML_KEYS.fetch(name)
179
194
  end
@@ -193,21 +208,6 @@ class RepositoryUpdateRules
193
208
  :yaml_key
194
209
  )
195
210
 
196
- def initialize(rules_by_repo)
197
- @rules_by_repo = rules_by_repo
198
- end
199
-
200
- def empty?
201
- @rules_by_repo.empty?
202
- end
203
-
204
- def suppressed?(record)
205
- return false unless semantic_record?(record)
206
-
207
- rule = @rules_by_repo[normalized_record_url(record)]
208
- rule ? rule.suppressed?(record) : false
209
- end
210
-
211
211
  private
212
212
 
213
213
  def semantic_record?(record)
@@ -5,7 +5,7 @@ require "semverify"
5
5
  # Namespace for the core gem's published constants (gem version and the
6
6
  # {SpmVersionUpdates::Semver} value object).
7
7
  module SpmVersionUpdates
8
- # SemVer value object used by both the GitHub Action and legacy Danger plugin.
8
+ # SemVer value object used by both the GitHub Action and Danger plugin.
9
9
  class Semver
10
10
  include Comparable
11
11