kettle-dev 3.1.33 → 3.1.35

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bd1df5ff35332b6e32cc015b2d501bf6faab0ad35f4aa0fbdd96e0dcc3a5bd39
4
- data.tar.gz: f29c4bbd741c0067a3351e61196c15a33ffd91e081562010d0da3c9a70e0f9c9
3
+ metadata.gz: 74266be9347a9ab1512fd327dc54146ceebe62d9a05d18764c9682880c35f516
4
+ data.tar.gz: 8ae6b67df2dabf0c0b4cc0efcea129bd3d962037798450f26a539e11349b5ed3
5
5
  SHA512:
6
- metadata.gz: e145148d99b4d8b962d33a143cc7261a9525651b52748d31b991e258451af9f88a6cf678e38c31f439359d1773e9b58d9b7f5154394bcaa87e0ca9bc8345eb52
7
- data.tar.gz: e0421b686337c18156e947338a21ef079dd8cbe0b6c928c5c7607f82d03ab79191a25720142f88e8b5bbb115c25ade43cbd5a22261f27d19738794120c65e753
6
+ metadata.gz: 49deb4a4021a9c18dac62d5a4ba2d6035e802365dcd6f981555574ff13bf59752348a70f3deadd220e77edabdbbeb2e7001f6ac77f8a961a944cdb6835b0f2f0
7
+ data.tar.gz: 45539c4981d87460bacd4021ee7f77d63620ccf5fd668991e3931263dfbde91497213c079d59b7370d6bc1bbdf76453566b95f52c33e67aed9d4af6d6b940210
checksums.yaml.gz.sig CHANGED
Binary file
data/CHANGELOG.md CHANGED
@@ -30,6 +30,46 @@ Please file a bug if you notice a violation of semantic versioning.
30
30
 
31
31
  ### Security
32
32
 
33
+ ## [3.1.35] - 2026-11-28
34
+
35
+ - TAG: [v3.1.35][3.1.35t]
36
+ - COVERAGE: 91.69% -- 6322/6895 lines in 51 files
37
+ - BRANCH COVERAGE: 75.95% -- 2450/3226 branches in 51 files
38
+ - 57.40% documented
39
+
40
+ ### Added
41
+
42
+ - `Kettle::Dev::KlocBadge` helper for computing and updating README KLOC badges from CHANGELOG coverage sections or member-scoped SimpleCov `coverage/coverage.json` files
43
+
44
+ ### Fixed
45
+
46
+ - `spec_helper`: clear all ambient `KETTLE_RELEASE_*`, `K_RELEASE_*`, `GITHUB_TOKEN`, and `GH_TOKEN` env vars before each example so running `kettle-dev`'s test suite inside a `kettle-family` publish (which exports `KETTLE_RELEASE_REQUIRE_GITHUB_RELEASE=true`) cannot trigger real GitHub release checks in `ReleaseCLI#run` specs
47
+
48
+ - `kettle-release`: guard README KLOC badge updates against `0/0` coverage denominators (preventing badges from being overwritten with `0.000`) and resolve member-scoped `coverage/coverage.json` instead of aggregate root `CHANGELOG.md` totals in shared-changelog monorepos
49
+
50
+ - `CIHelpers#claim_ci_rate_slot`: use `Process.clock_gettime(Process::CLOCK_REALTIME)` instead of `Time.now` so Timecop-warped examples cannot compute multi-minute waits against real-clock timestamps written by background threads or peer workers, and preserve `K_RELEASE_CI_RATE_STATE_FILE` while stubbing `CIHelpers.sleep` in `spec_helper`
51
+
52
+ ## [3.1.34] - 2026-11-27
53
+
54
+ - TAG: [v3.1.34][3.1.34t]
55
+ - COVERAGE: 91.87% -- 6259/6813 lines in 50 files
56
+ - BRANCH COVERAGE: 75.79% -- 2413/3184 branches in 50 files
57
+ - 56.67% documented
58
+
59
+ ### Changed
60
+
61
+ - [kc] kettle-jem/prepare: updated 9 project files since the last release:
62
+ - dependencies (9)
63
+
64
+ - [kc] kettle-jem/template: updated 3 project files since the last release:
65
+ - code and tests (2)
66
+ - other (1)
67
+
68
+ ### Fixed
69
+
70
+ - GitHub CI monitoring (`CIHelpers` / `CIMonitor` / `ReleaseCLI`): follow HTTP `301`/`302`/`307`/`308` redirects (forwarding `Authorization` only on same-host redirects, capped at 5 hops) instead of silently returning `nil` for 300s, switch monitoring to the canonical `owner/repo` on permanent redirects, and surface a loud warning + non-blocking diagnostic + final summary `Warnings:` line with the exact `git remote set-url` command; pre-empt the 300s workflow-start timeout by failing fast on wrong/nonexistent remotes (HTTP 404), unpushed commits (`git ls-remote` + GitHub `/commits/:sha` 404/422 suggesting `--start-step 9`), disabled GitHub Actions or disabled workflows, broken workflow YAML, and branch trigger mismatches (fixes #71)
71
+ - `ReleaseCLI#push!` and `push_tags!`: record optional remotes skipped during fetch parity (`fetch_remote_for_parity!`) in `@skip_remotes`, exclude the aggregate `"all"` remote from individual remote candidates, fall back to pushing active individual remotes (`origin` first) if `git push all` / `git push all --tags` fails (preventing an unreachable optional mirror such as Codeberg from aborting `git push all` before GitHub is pushed), and abort with `--start-step 9` when pushing to a required remote fails instead of silently continuing into CI monitoring (fixes #73)
72
+
33
73
  ## [3.1.33] - 2026-11-27
34
74
 
35
75
  - TAG: [v3.1.33][3.1.33t]
@@ -4408,7 +4448,11 @@ Please file a bug if you notice a violation of semantic versioning.
4408
4448
  - Selecting will run the selected workflow via `act`
4409
4449
  - This may move to its own gem in the future.
4410
4450
 
4411
- [Unreleased]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.33...HEAD
4451
+ [Unreleased]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.35...HEAD
4452
+ [3.1.35]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.34...v3.1.35
4453
+ [3.1.35t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.35
4454
+ [3.1.34]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.33...v3.1.34
4455
+ [3.1.34t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.34
4412
4456
  [3.1.33]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.32...v3.1.33
4413
4457
  [3.1.33t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.33
4414
4458
  [3.1.32]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.31...v3.1.32
data/README.md CHANGED
@@ -1034,7 +1034,7 @@ Thanks for RTFM. ☺️
1034
1034
  [📌gitmoji]: https://gitmoji.dev
1035
1035
  [📌gitmoji-img]: https://img.shields.io/badge/gitmoji_commits-%20%F0%9F%98%9C%20%F0%9F%98%8D-34495e.svg?style=flat-square
1036
1036
  [🧮kloc]: https://www.youtube.com/watch?v=dQw4w9WgXcQ
1037
- [🧮kloc-img]: https://img.shields.io/badge/KLOC-6.545-FFDD67.svg?style=for-the-badge&logo=YouTube&logoColor=blue
1037
+ [🧮kloc-img]: https://img.shields.io/badge/KLOC-6.895-FFDD67.svg?style=for-the-badge&logo=YouTube&logoColor=blue
1038
1038
  [🔐security]: https://github.com/kettle-dev/kettle-dev/blob/main/SECURITY.md
1039
1039
  [🔐security-img]: https://img.shields.io/badge/security-policy-259D6C.svg?style=flat
1040
1040
  [📄copyright-notice-explainer]: https://opensource.stackexchange.com/questions/5778/why-do-licenses-such-as-the-mit-license-specify-a-single-year
@@ -12,6 +12,11 @@ module Kettle
12
12
  # GitHub API rejected the request because the token is invalid/revoked.
13
13
  class CIAuthError < StandardError; end
14
14
 
15
+ # Non-retryable CI setup/configuration failure (wrong remote / 404,
16
+ # unpushed commit, Actions disabled, broken workflow YAML, trigger mismatch,
17
+ # or redirect loop) that must fail fast rather than waiting for timeout.
18
+ class CIConfigurationError < StandardError; end
19
+
15
20
  # GitHub API quota exhausted. Recoverable: retry after the reset time.
16
21
  class CIRateLimitError < StandardError
17
22
  attr_reader :reset_at
@@ -155,12 +160,10 @@ module Kettle
155
160
  "id" => run["id"],
156
161
  "head_sha" => run["head_sha"]
157
162
  }
158
- rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError
159
- # Auth failures are fatal; rate limits are recoverable but must reach
160
- # the monitor (which parks until the reset) — swallowing either turns
161
- # the poll into an infinite 0/N tick.
162
- # fail the same way, so swallowing this turns the monitor into an
163
- # infinite 0/N tick. Re-raise for the caller to abort with guidance.
163
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
164
+ # Auth and configuration failures are fatal; rate limits are recoverable
165
+ # but must reach the monitor (which parks until the reset) — swallowing
166
+ # any of them turns the poll into an infinite 0/N tick.
164
167
  raise
165
168
  rescue => e
166
169
  Kettle::Dev.debug_error(e, __method__)
@@ -239,6 +242,14 @@ module Kettle
239
242
  sleep(wait) if wait.positive?
240
243
  end
241
244
 
245
+ # Un-mocked wall-clock seconds for cross-process rate-limit coordination.
246
+ # Must not use Time.now: Timecop in test suites shifts Time.now relative
247
+ # to background threads and other OS processes, turning slot - now into
248
+ # multi-minute real sleep() calls when CI runs near midnight UTC.
249
+ def ci_rate_now
250
+ Process.clock_gettime(Process::CLOCK_REALTIME)
251
+ end
252
+
242
253
  # Returns how long the caller must wait before its request (0.0 when the
243
254
  # budget is unspent). Never sleeps itself. Lock hold time is bounded by
244
255
  # the file IO only.
@@ -258,7 +269,7 @@ module Kettle
258
269
  f.flock(File::LOCK_EX)
259
270
  payload = f.size.zero? ? {} : JSON.parse(f.read)
260
271
  last = payload["next_slot"] || payload["last_request"] || 0.0
261
- now = Time.now.to_f
272
+ now = ci_rate_now
262
273
  # Absurdly future (clock skew) or ancient entries start fresh.
263
274
  last = 0.0 if !last.is_a?(Numeric) || (last - now).abs > 3600
264
275
  slot = [last + CI_RATE_MIN_INTERVAL, now].max
@@ -282,7 +293,7 @@ module Kettle
282
293
  # rubocop:disable ThreadSafety/ClassInstanceVariable -- callers hold @ci_rate_lock, so this state has no concurrent writers; the degradation path is intentionally module-scoped.
283
294
  def ci_rate_claim_in_process
284
295
  @ci_rate_inproc_last = 0.0 unless defined?(@ci_rate_inproc_last)
285
- now = Time.now.to_f
296
+ now = ci_rate_now
286
297
  slot = [@ci_rate_inproc_last + CI_RATE_MIN_INTERVAL, now].max
287
298
  @ci_rate_inproc_last = slot
288
299
  wait = slot - now
@@ -290,17 +301,63 @@ module Kettle
290
301
  end
291
302
  # rubocop:enable ThreadSafety/ClassInstanceVariable
292
303
 
293
- def github_get_json(url, token:)
294
- github_rate_limit_wait!
295
- uri = URI(url)
296
- req = Net::HTTP::Get.new(uri)
297
- req["User-Agent"] = "kettle-dev/ci-helpers"
298
- req["Authorization"] = "token #{token}" if token && !token.empty?
299
- res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
300
- # Dispatch on is_a? rather than `case`/===: verifying doubles
301
- # (instance_double(Net::HTTPOK)) used in specs do not reliably match
302
- # `Net::HTTPSuccess === res`, which silently degraded every stubbed
303
- # response to "no data".
304
+ MAX_GITHUB_REDIRECTS = 5
305
+ PERMANENT_REDIRECT_CODES = [301, 308].freeze
306
+
307
+ def github_request(url, token:, on_redirect: nil, max_redirects: MAX_GITHUB_REDIRECTS)
308
+ current_url = url.to_s
309
+ initial_host = URI(current_url).hostname
310
+ redirects = []
311
+
312
+ (max_redirects + 1).times do
313
+ github_rate_limit_wait!
314
+ uri = URI(current_url)
315
+ req = Net::HTTP::Get.new(uri)
316
+ req["User-Agent"] = "kettle-dev/ci-helpers"
317
+ if token && !token.empty? && uri.hostname == initial_host
318
+ req["Authorization"] = "token #{token}"
319
+ end
320
+ res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
321
+
322
+ # Dispatch on is_a? rather than `case`/===: verifying doubles
323
+ # (instance_double(Net::HTTPOK)) used in specs do not reliably match
324
+ # `Net::HTTPSuccess === res`, which silently degraded every stubbed
325
+ # response to "no data".
326
+ return [res, redirects] if res.is_a?(Net::HTTPSuccess)
327
+
328
+ if res.is_a?(Net::HTTPRedirection)
329
+ location = res["location"] || res["Location"]
330
+ return [res, redirects] if location.nil? || location.empty?
331
+
332
+ next_url = URI.join(current_url, location).to_s
333
+ hop = {from: current_url, to: next_url, code: res.code.to_i}
334
+ redirects << hop
335
+ on_redirect&.call(hop)
336
+ current_url = next_url
337
+ next
338
+ end
339
+
340
+ return [res, redirects]
341
+ end
342
+
343
+ raise(
344
+ Kettle::Dev::CIConfigurationError,
345
+ "GitHub API exceeded #{max_redirects} redirects starting from #{url}."
346
+ )
347
+ end
348
+
349
+ def github_get_json(url, token:, on_redirect: nil, **options)
350
+ res, redirects = github_request(url, token: token, on_redirect: on_redirect)
351
+ if on_redirect.nil?
352
+ permanent = redirects.find { |hop| PERMANENT_REDIRECT_CODES.include?(hop[:code]) }
353
+ if permanent
354
+ warn(
355
+ "[kettle-dev] WARNING: GitHub API permanently redirected #{permanent[:from]} -> " \
356
+ "#{redirects.last[:to]} (HTTP #{permanent[:code]}). Update your git remote URL to the canonical repository."
357
+ )
358
+ end
359
+ end
360
+
304
361
  if res.is_a?(Net::HTTPSuccess)
305
362
  JSON.parse(res.body)
306
363
  elsif res.is_a?(Net::HTTPUnauthorized)
@@ -317,9 +374,9 @@ module Kettle
317
374
  # Rate limited: recoverable. Honor the reset time, then let the
318
375
  # caller retry the poll cycle.
319
376
  reset_at = Time.at(res["X-RateLimit-Reset"].to_i).utc
320
- raise(
321
- Kettle::Dev::CIRateLimitError,
322
- "GitHub API rate limit exceeded; resets at #{reset_at.strftime("%H:%M:%SZ")}"
377
+ raise Kettle::Dev::CIRateLimitError.new(
378
+ "GitHub API rate limit exceeded; resets at #{reset_at.strftime("%H:%M:%SZ")}",
379
+ reset_at: reset_at
323
380
  )
324
381
  end
325
382
 
@@ -331,6 +388,344 @@ module Kettle
331
388
  end
332
389
  end
333
390
 
391
+ # Fetch GitHub repository metadata, following redirects and detecting 404.
392
+ # Returns nil on transient/network errors so callers can fail open when offline.
393
+ # @param owner [String]
394
+ # @param repo [String]
395
+ # @param token [String, nil]
396
+ # @return [Hash, nil]
397
+ def github_repo_info(owner:, repo:, token: default_token, **options)
398
+ return unless owner && repo
399
+
400
+ url = "https://api.github.com/repos/#{owner}/#{repo}"
401
+ res, redirects = github_request(url, token: token)
402
+ if res.is_a?(Net::HTTPSuccess)
403
+ data = JSON.parse(res.body)
404
+ {
405
+ "data" => data,
406
+ "full_name" => data["full_name"],
407
+ "default_branch" => data["default_branch"],
408
+ "archived" => data["archived"],
409
+ "redirected" => redirects.any? { |hop| PERMANENT_REDIRECT_CODES.include?(hop[:code]) },
410
+ "redirects" => redirects
411
+ }
412
+ elsif res.is_a?(Net::HTTPNotFound)
413
+ raise(
414
+ Kettle::Dev::CIConfigurationError,
415
+ "GitHub repository #{owner}/#{repo} not found (HTTP 404). " \
416
+ "Check the git remote URL and ensure GITHUB_TOKEN / GH_TOKEN has access to this repository."
417
+ )
418
+ elsif res.is_a?(Net::HTTPUnauthorized)
419
+ raise(
420
+ Kettle::Dev::CIAuthError,
421
+ "GitHub API rejected the request (401: invalid or revoked token) for #{url}. " \
422
+ "Check GITHUB_TOKEN / GH_TOKEN."
423
+ )
424
+ elsif res.is_a?(Net::HTTPForbidden) && res["X-RateLimit-Remaining"].to_i.zero?
425
+ reset_at = Time.at(res["X-RateLimit-Reset"].to_i).utc
426
+ raise Kettle::Dev::CIRateLimitError.new(
427
+ "GitHub API rate limit exceeded; resets at #{reset_at.strftime("%H:%M:%SZ")}",
428
+ reset_at: reset_at
429
+ )
430
+ end
431
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
432
+ raise
433
+ rescue => e
434
+ Kettle::Dev.debug_error(e, __method__)
435
+ nil
436
+ end
437
+
438
+ # Check whether a commit SHA exists on GitHub for the given repository.
439
+ # Returns true when present, false on 404/422 (missing commit), or nil on unknown/network error.
440
+ # @param owner [String]
441
+ # @param repo [String]
442
+ # @param head_sha [String]
443
+ # @param token [String, nil]
444
+ # @return [Boolean, nil]
445
+ def github_commit_exists?(owner:, repo:, head_sha:, token: default_token, **options)
446
+ return nil unless owner && repo && head_sha && !head_sha.empty?
447
+
448
+ url = "https://api.github.com/repos/#{owner}/#{repo}/commits/#{URI.encode_www_form_component(head_sha)}"
449
+ res, _redirects = github_request(url, token: token)
450
+ return true if res.is_a?(Net::HTTPSuccess)
451
+ return false if res.is_a?(Net::HTTPNotFound) || res.is_a?(Net::HTTPUnprocessableEntity)
452
+
453
+ if res.is_a?(Net::HTTPUnauthorized)
454
+ raise(
455
+ Kettle::Dev::CIAuthError,
456
+ "GitHub API rejected the request (401: invalid or revoked token) for #{url}. " \
457
+ "Check GITHUB_TOKEN / GH_TOKEN."
458
+ )
459
+ elsif res.is_a?(Net::HTTPForbidden) && res["X-RateLimit-Remaining"].to_i.zero?
460
+ reset_at = Time.at(res["X-RateLimit-Reset"].to_i).utc
461
+ raise Kettle::Dev::CIRateLimitError.new(
462
+ "GitHub API rate limit exceeded; resets at #{reset_at.strftime("%H:%M:%SZ")}",
463
+ reset_at: reset_at
464
+ )
465
+ end
466
+ nil
467
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
468
+ raise
469
+ rescue => e
470
+ Kettle::Dev.debug_error(e, __method__)
471
+ nil
472
+ end
473
+
474
+ # Fetch GitHub Actions repository permissions (e.g. {"enabled" => true/false}).
475
+ # Returns nil when unavailable (e.g., 403/404 or network error).
476
+ # @param owner [String]
477
+ # @param repo [String]
478
+ # @param token [String, nil]
479
+ # @return [Hash, nil]
480
+ def github_actions_permissions(owner:, repo:, token: default_token, **options)
481
+ return nil unless owner && repo
482
+
483
+ github_get_json(
484
+ "https://api.github.com/repos/#{owner}/#{repo}/actions/permissions",
485
+ token: token
486
+ )
487
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
488
+ raise
489
+ rescue => e
490
+ Kettle::Dev.debug_error(e, __method__)
491
+ nil
492
+ end
493
+
494
+ # Fetch GitHub Actions workflow definitions registered on GitHub.
495
+ # Returns nil when unavailable.
496
+ # @param owner [String]
497
+ # @param repo [String]
498
+ # @param token [String, nil]
499
+ # @return [Array<Hash>, nil]
500
+ def github_actions_workflows(owner:, repo:, token: default_token, **options)
501
+ return nil unless owner && repo
502
+
503
+ data = github_get_json(
504
+ "https://api.github.com/repos/#{owner}/#{repo}/actions/workflows?per_page=100",
505
+ token: token
506
+ )
507
+ return nil unless data.is_a?(Hash) && data.key?("workflows")
508
+
509
+ Array(data["workflows"])
510
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
511
+ raise
512
+ rescue => e
513
+ Kettle::Dev.debug_error(e, __method__)
514
+ nil
515
+ end
516
+
517
+ # Rewrite a GitHub remote URL to point at a new owner/repo while preserving
518
+ # SSH vs HTTPS scheme and optional .git suffix.
519
+ # @param url [String]
520
+ # @param new_owner [String]
521
+ # @param new_repo [String]
522
+ # @return [String]
523
+ def rewrite_github_remote_url(url, new_owner, new_repo)
524
+ raw = url.to_s.strip
525
+ suffix = raw.end_with?(".git") ? ".git" : ""
526
+ if raw.start_with?("git@github.com:")
527
+ "git@github.com:#{new_owner}/#{new_repo}#{suffix}"
528
+ elsif raw =~ %r{\A((?:git\+)?ssh://[^/]+/)}
529
+ "#{Regexp.last_match(1)}#{new_owner}/#{new_repo}#{suffix}"
530
+ else
531
+ "https://github.com/#{new_owner}/#{new_repo}#{suffix}"
532
+ end
533
+ end
534
+
535
+ # Parse monitored local workflow YAML files and fail fast on syntax or structure errors.
536
+ # @param root [String]
537
+ # @param workflows [Array<String>]
538
+ # @return [Hash{String => Hash}] parsed workflow documents keyed by filename
539
+ def validate_workflow_yaml!(root:, workflows:, **options)
540
+ documents = {}
541
+ Array(workflows).each do |wf|
542
+ path = File.join(root.to_s, ".github", "workflows", wf)
543
+ next unless File.file?(path)
544
+
545
+ begin
546
+ doc = Kettle::Dev.safe_load_yaml(File.read(path), aliases: true)
547
+ rescue Psych::Exception => error
548
+ raise(
549
+ Kettle::Dev::CIConfigurationError,
550
+ "Workflow YAML syntax error in .github/workflows/#{wf}: #{error.message}. " \
551
+ "Fix the workflow file before releasing."
552
+ )
553
+ end
554
+
555
+ unless doc.is_a?(Hash)
556
+ raise(
557
+ Kettle::Dev::CIConfigurationError,
558
+ "Workflow .github/workflows/#{wf} is not a valid YAML mapping. " \
559
+ "Fix the workflow file before releasing."
560
+ )
561
+ end
562
+
563
+ documents[wf] = doc
564
+ end
565
+ documents
566
+ end
567
+
568
+ # Validate that each parsed workflow document can actually trigger on the
569
+ # target branch. Raises CIConfigurationError when one or more workflows
570
+ # have incompatible triggers.
571
+ # @param documents [Hash{String => Hash}]
572
+ # @param branch [String]
573
+ # @param default_branch [String, nil]
574
+ # @return [void]
575
+ def validate_workflow_triggers!(documents:, branch:, default_branch: nil, **options)
576
+ mismatched = []
577
+ documents.each do |wf, doc|
578
+ next if workflow_can_trigger_for_branch?(doc, branch: branch, default_branch: default_branch)
579
+
580
+ triggers = workflow_triggers(doc)
581
+ mismatched << "#{wf} (#{describe_workflow_triggers(triggers)})"
582
+ end
583
+ return if mismatched.empty?
584
+
585
+ raise(
586
+ Kettle::Dev::CIConfigurationError,
587
+ "GitHub Actions workflow trigger mismatch for branch '#{branch}': #{mismatched.join(", ")}. " \
588
+ "Update the workflow `on:` triggers for '#{branch}' or select runnable workflows with --ci-workflows."
589
+ )
590
+ end
591
+
592
+ # Extract the `on:` trigger block from a parsed workflow document.
593
+ # Psych (YAML 1.1) parses an unquoted `on:` key as boolean `true`.
594
+ # @param document [Hash]
595
+ # @return [Object]
596
+ def workflow_triggers(document)
597
+ return nil unless document.is_a?(Hash)
598
+
599
+ document.key?("on") ? document["on"] : document[true]
600
+ end
601
+
602
+ # Whether a workflow document can trigger for the given branch.
603
+ # On the default branch, ReleaseCLI pushes directly without opening a PR or
604
+ # dispatching workflow_dispatch, so a matching `push` trigger is required.
605
+ # On non-default branches (or when default_branch is unknown), `pull_request`
606
+ # or `workflow_dispatch` may trigger CI as well.
607
+ # @param document [Hash]
608
+ # @param branch [String]
609
+ # @param default_branch [String, nil]
610
+ # @return [Boolean]
611
+ def workflow_can_trigger_for_branch?(document, branch:, default_branch: nil, **options)
612
+ triggers = workflow_triggers(document)
613
+ return false if triggers.nil?
614
+ return true if push_trigger_matches_branch?(triggers, branch)
615
+
616
+ on_default_branch = !default_branch.nil? && !default_branch.empty? && branch == default_branch
617
+ return false if on_default_branch
618
+
619
+ trigger_present?(triggers, "pull_request") || trigger_present?(triggers, "workflow_dispatch")
620
+ end
621
+
622
+ # @param triggers [Object]
623
+ # @param branch [String]
624
+ # @return [Boolean]
625
+ def push_trigger_matches_branch?(triggers, branch)
626
+ case triggers
627
+ when String, Symbol
628
+ triggers.to_s == "push"
629
+ when Array
630
+ triggers.any? { |t| t.to_s == "push" }
631
+ when Hash
632
+ return false unless triggers.key?("push") || triggers.key?(:push)
633
+
634
+ push_cfg = triggers.key?("push") ? triggers["push"] : triggers[:push]
635
+ return true if push_cfg.nil?
636
+ return true unless push_cfg.is_a?(Hash)
637
+
638
+ branches = push_cfg["branches"]
639
+ branches_ignore = push_cfg["branches-ignore"]
640
+ tags = push_cfg["tags"]
641
+ tags_ignore = push_cfg["tags-ignore"]
642
+
643
+ return false if branches.nil? && branches_ignore.nil? && (!tags.nil? || !tags_ignore.nil?)
644
+ return github_branch_patterns_match?(branch, Array(branches)) unless branches.nil?
645
+ return !github_branch_patterns_match?(branch, Array(branches_ignore)) unless branches_ignore.nil?
646
+
647
+ true
648
+ else
649
+ false
650
+ end
651
+ end
652
+
653
+ # @param triggers [Object]
654
+ # @param name [String]
655
+ # @return [Boolean]
656
+ def trigger_present?(triggers, name)
657
+ case triggers
658
+ when String, Symbol
659
+ triggers.to_s == name
660
+ when Array
661
+ triggers.any? { |t| t.to_s == name }
662
+ when Hash
663
+ triggers.key?(name) || triggers.key?(name.to_sym)
664
+ else
665
+ false
666
+ end
667
+ end
668
+
669
+ # Evaluate GitHub Actions branch glob patterns (including leading `!` negations).
670
+ # @param branch [String]
671
+ # @param patterns [Array<String>]
672
+ # @return [Boolean]
673
+ def github_branch_patterns_match?(branch, patterns)
674
+ matched = false
675
+ Array(patterns).each do |raw_pattern|
676
+ pattern = raw_pattern.to_s
677
+ if pattern.start_with?("!")
678
+ negated = pattern.sub(/\A!/, "")
679
+ matched = false if github_glob_to_regexp(negated).match?(branch)
680
+ elsif github_glob_to_regexp(pattern).match?(branch)
681
+ matched = true
682
+ end
683
+ end
684
+ matched
685
+ end
686
+
687
+ # Convert a GitHub Actions glob pattern (`**`, `*`, `?`) into an anchored Regexp.
688
+ # @param pattern [String]
689
+ # @return [Regexp]
690
+ def github_glob_to_regexp(pattern)
691
+ escaped = pattern.to_s.gsub(/(\*\*|\*|\?|[^*?]+)/) do |token|
692
+ case token
693
+ when "**" then ".*"
694
+ when "*" then "[^/]*"
695
+ when "?" then "[^/]"
696
+ else Regexp.escape(token)
697
+ end
698
+ end
699
+ /\A#{escaped}\z/
700
+ end
701
+
702
+ # Human-readable summary of a workflow's configured `on:` triggers.
703
+ # @param triggers [Object]
704
+ # @return [String]
705
+ def describe_workflow_triggers(triggers)
706
+ case triggers
707
+ when nil
708
+ "missing `on:` triggers"
709
+ when String, Symbol
710
+ "triggers: #{triggers}"
711
+ when Array
712
+ "triggers: #{triggers.join(", ")}"
713
+ when Hash
714
+ parts = triggers.map do |key, value|
715
+ if key.to_s == "push" && value.is_a?(Hash) && value["branches"]
716
+ "push[branches: #{Array(value["branches"]).join(", ")}]"
717
+ elsif key.to_s == "push" && value.is_a?(Hash) && value["branches-ignore"]
718
+ "push[branches-ignore: #{Array(value["branches-ignore"]).join(", ")}]"
719
+ else
720
+ key.to_s
721
+ end
722
+ end
723
+ "triggers: #{parts.join(", ")}"
724
+ else
725
+ "invalid `on:` triggers"
726
+ end
727
+ end
728
+
334
729
  # Whether a run has completed successfully.
335
730
  # @param run [Hash, nil]
336
731
  # @return [Boolean]
@@ -372,10 +767,9 @@ module Kettle
372
767
  "html_url" => job["html_url"]
373
768
  }
374
769
  end
375
- rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError
376
- # See latest_run: auth/rate-limit failures must abort or park the
377
- # monitor, not degrade
378
- # to "no jobs yet".
770
+ rescue Kettle::Dev::CIAuthError, Kettle::Dev::CIRateLimitError, Kettle::Dev::CIConfigurationError
771
+ # See latest_run: auth/configuration/rate-limit failures must abort or
772
+ # park the monitor, not degrade to "no jobs yet".
379
773
  raise
380
774
  rescue => e
381
775
  Kettle::Dev.debug_error(e, __method__)