kettle-dev 3.1.34 → 3.1.36

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: 65c7579f03a20c8b1b277cc6e8045460d69538f2e5c2fd3fad7bc83869281220
4
- data.tar.gz: 302eaebac2fe66f1338a2d53061599b984f978e75e948dcad5ca2525665a0fa8
3
+ metadata.gz: 6aba42924fa36bffd3d25687913a2c18f79884d3503e979e66d0f54e4f984b8a
4
+ data.tar.gz: a4cd7b3978fa34eb87cfc79fe67d1579f15cbd63abece42b893ed75118951d7c
5
5
  SHA512:
6
- metadata.gz: 24d348c72c38bc3e2537470b15e14d96c070d56b5ee22c41871ed43fa8b1c345e80fa5dc17529c1380810904920e1567dbb92c594fc947b5474b813ba2b8f5d1
7
- data.tar.gz: 417d2b247efea41fa6b45c1087d8b0707fb7e252e5fe74cfe237074c1158492cd0f517b7b4bc2344a6499faeceef0124e9715b49c2e6b19fd2cf24f6511b84d4
6
+ metadata.gz: e44ec33626a3c83166009a9cf03d58f1d0b8560e50bf33170d7552239ef86dbbf7c61870a0c3d63ffc711b0d783899f5962c24f531ba72d193cad39e32abd8d8
7
+ data.tar.gz: c3704ef5aed6ad4f085e4f8ad891520922c0b4ffebc66deec30c48f167ae75211cb2f4f43c0ba8b2a2df7e1c6cf00f46396acf53b7dc7305906628de8c2454e2
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.36] - 2026-11-29
34
+
35
+ - TAG: [v3.1.36][3.1.36t]
36
+ - COVERAGE: 91.60% -- 6404/6991 lines in 51 files
37
+ - BRANCH COVERAGE: 76.01% -- 2494/3281 branches in 51 files
38
+ - 57.19% documented
39
+
40
+ ### Added
41
+
42
+ - `kettle-dvcs` now writes per-forge availability to `.kettle/forges.yml` (`live` / `pending` / `off`, with `off` preserved across runs), which kettle-jem renders into README forge badges and the Federated DVCS table.
43
+ - `kettle-dvcs --create` creates missing mirrors when fetch fails: GitLab via push-to-create (flipping the default-private visibility to public via API when `GL_TOKEN`/`GITLAB_TOKEN` is set, and refusing to treat rename redirects as creation), Codeberg via the Forgejo API (`CB_TOKEN`/`CODEBERG_TOKEN`, since Codeberg disables push-to-create), each verified with a follow-up fetch.
44
+
45
+ ### Changed
46
+
47
+ - `kettle-release` now syncs the checkout to its upstream (`Kettle::Dev::Rebase`) before step 0, so the release-prep commit is built on current upstream instead of conflicting when the trunk is synced at step 8. A conflicting sync aborts before any changes; branch-stack branches, local-CI releases, nested runs, and resumes past step 1 are skipped.
48
+ - `kettle-dvcs` no longer edits `README.md` (the summary-toggle regex had drifted from the kettle-jem template and was a no-op); kettle-jem owns README rendering from the state file instead.
49
+
50
+ ### Fixed
51
+
52
+ - `appraisal_rake_spec` failure-mode mocks now match fallback targets on the command only, not the env hash; the rake derives its env partly from ambient `*_DEV` / `*_LOCAL` selectors (e.g. `STRUCTUREDMERGE_DEV`), so exact hash equality broke the fallback specs whenever those were set.
53
+
54
+ ## [3.1.35] - 2026-11-28
55
+
56
+ - TAG: [v3.1.35][3.1.35t]
57
+ - COVERAGE: 91.69% -- 6322/6895 lines in 51 files
58
+ - BRANCH COVERAGE: 75.95% -- 2450/3226 branches in 51 files
59
+ - 57.40% documented
60
+
61
+ ### Added
62
+
63
+ - `Kettle::Dev::KlocBadge` helper for computing and updating README KLOC badges from CHANGELOG coverage sections or member-scoped SimpleCov `coverage/coverage.json` files
64
+
65
+ ### Fixed
66
+
67
+ - `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
68
+
69
+ - `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
70
+
71
+ - `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`
72
+
33
73
  ## [3.1.34] - 2026-11-27
34
74
 
35
75
  - TAG: [v3.1.34][3.1.34t]
@@ -4429,7 +4469,11 @@ Please file a bug if you notice a violation of semantic versioning.
4429
4469
  - Selecting will run the selected workflow via `act`
4430
4470
  - This may move to its own gem in the future.
4431
4471
 
4432
- [Unreleased]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.34...HEAD
4472
+ [Unreleased]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.36...HEAD
4473
+ [3.1.36]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.35...v3.1.36
4474
+ [3.1.36t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.36
4475
+ [3.1.35]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.34...v3.1.35
4476
+ [3.1.35t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.35
4433
4477
  [3.1.34]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.33...v3.1.34
4434
4478
  [3.1.34t]: https://github.com/kettle-dev/kettle-dev/releases/tag/v3.1.34
4435
4479
  [3.1.33]: https://github.com/kettle-dev/kettle-dev/compare/v3.1.32...v3.1.33
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.813-FFDD67.svg?style=for-the-badge&logo=YouTube&logoColor=blue
1037
+ [🧮kloc-img]: https://img.shields.io/badge/KLOC-6.991-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
data/exe/kettle-dvcs CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  # kettle-dvcs: Normalize git remotes across GitHub, GitLab, and Codeberg
7
7
  # - Aligns/creates remotes for the three forges and an 'all' remote
8
- # - Attempts fetch from each forge and updates README federation summary
8
+ # - Attempts fetch from each forge and records per-forge state in .kettle/forges.yml
9
9
 
10
10
  # Immediate, unbuffered output
11
11
  $stdout.sync = true
@@ -49,13 +49,16 @@ if ARGV.include?("-h") || ARGV.include?("--help")
49
49
  --gitlab-name NAME Remote name for GitLab (default: gl)
50
50
  --codeberg-name NAME Remote name for Codeberg (default: cb)
51
51
  --status Fetch remotes; show ahead/behind vs origin/main
52
+ --create Create missing mirrors when fetch fails
53
+ (GitLab via push-to-create; Codeberg via API, CB_TOKEN required)
52
54
  --force Non-interactive; accept defaults
53
55
 
54
56
  Behavior:
55
57
  - Ensures remotes exist and have consistent URLs
56
58
  - Creates an 'all' remote that fetches from origin only and pushes to all three
57
59
  - Prints `git remote -v`
58
- - Fetches each forge to detect availability and updates README accordingly
60
+ - Fetches each forge to detect availability and writes .kettle/forges.yml,
61
+ which kettle-jem renders into README forge badges and the Federated DVCS table
59
62
 
60
63
  Environment:
61
64
  KETTLE_DEV_DISABLE_GIT_GEM=true # force CLI git backend even if 'git' gem present
@@ -242,6 +242,14 @@ module Kettle
242
242
  sleep(wait) if wait.positive?
243
243
  end
244
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
+
245
253
  # Returns how long the caller must wait before its request (0.0 when the
246
254
  # budget is unspent). Never sleeps itself. Lock hold time is bounded by
247
255
  # the file IO only.
@@ -261,7 +269,7 @@ module Kettle
261
269
  f.flock(File::LOCK_EX)
262
270
  payload = f.size.zero? ? {} : JSON.parse(f.read)
263
271
  last = payload["next_slot"] || payload["last_request"] || 0.0
264
- now = Time.now.to_f
272
+ now = ci_rate_now
265
273
  # Absurdly future (clock skew) or ancient entries start fresh.
266
274
  last = 0.0 if !last.is_a?(Numeric) || (last - now).abs > 3600
267
275
  slot = [last + CI_RATE_MIN_INTERVAL, now].max
@@ -285,7 +293,7 @@ module Kettle
285
293
  # rubocop:disable ThreadSafety/ClassInstanceVariable -- callers hold @ci_rate_lock, so this state has no concurrent writers; the degradation path is intentionally module-scoped.
286
294
  def ci_rate_claim_in_process
287
295
  @ci_rate_inproc_last = 0.0 unless defined?(@ci_rate_inproc_last)
288
- now = Time.now.to_f
296
+ now = ci_rate_now
289
297
  slot = [@ci_rate_inproc_last + CI_RATE_MIN_INTERVAL, now].max
290
298
  @ci_rate_inproc_last = slot
291
299
  wait = slot - now
@@ -1,4 +1,9 @@
1
1
  require "optparse"
2
+ require "fileutils"
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+ require "yaml"
2
7
 
3
8
  module Kettle
4
9
  module Dev
@@ -14,13 +19,17 @@ module Kettle
14
19
  # --protocol [ssh|https] Use git+ssh or HTTPS URLs (default: ssh)
15
20
  # --gitlab-name NAME Remote name for GitLab (default: gl)
16
21
  # --codeberg-name NAME Remote name for Codeberg (default: cb)
22
+ # --create Create missing mirrors (GitLab via push-to-create,
23
+ # Codeberg via API with CB_TOKEN) when fetch fails
17
24
  # --force Accept defaults; non-interactive
18
25
  #
19
26
  # Behavior:
20
27
  # - Aligns or creates remotes for github, gitlab, and codeberg with consistent org/repo and protocol
21
28
  # - Renames existing remotes to match chosen naming scheme when URLs already match
22
29
  # - Creates an "all" remote that fetches from origin only and pushes to all three forges
23
- # - Attempts to fetch from each forge to determine availability and updates README federation summary
30
+ # - Attempts to fetch from each forge to determine availability and writes the
31
+ # per-forge state to .kettle/forges.yml, which kettle-jem renders into the
32
+ # README forge badges and Federated DVCS table
24
33
  #
25
34
  # Examples:
26
35
  # Non-interactive run with defaults (origin: github, protocol: ssh)
@@ -36,13 +45,16 @@ module Kettle
36
45
  gl_name: "gl",
37
46
  cb_name: "cb",
38
47
  force: false,
39
- status: false
48
+ status: false,
49
+ create: false
40
50
  }.freeze
41
51
  FORGE_MIGRATION_TOOLS = {
42
52
  github: "https://github.com/new/import",
43
53
  gitlab: "https://gitlab.com/projects/new#import_project",
44
54
  codeberg: "https://codeberg.org/repo/migrate"
45
55
  }.freeze
56
+ FORGES = %i[github gitlab codeberg].freeze
57
+ FORGES_STATE_PATH = ".kettle/forges.yml"
46
58
 
47
59
  # Create the CLI with argv-like arguments
48
60
  # @param argv [Array<String>] the command-line arguments (without program name)
@@ -97,7 +109,9 @@ module Kettle
97
109
  say("Remotes normalized. Origin: #{names[:origin]} (#{urls[@opts[:origin].to_sym]})")
98
110
  show_remotes!(git)
99
111
  fetch_results = attempt_fetches!(git, names)
100
- update_readme_federation_status!(org, repo, fetch_results)
112
+ fetch_results = create_missing_mirrors!(git, names, org, repo, fetch_results) if @opts[:create]
113
+ write_forge_state!(fetch_results)
114
+ print_import_links(fetch_results)
101
115
  0
102
116
  end
103
117
 
@@ -182,6 +196,7 @@ module Kettle
182
196
  o.on("--gitlab-name NAME", "Remote name for GitLab (default: gl)") { |v| @opts[:gl_name] = v }
183
197
  o.on("--codeberg-name NAME", "Remote name for Codeberg (default: cb)") { |v| @opts[:cb_name] = v }
184
198
  o.on("--status", "Fetch remotes and show ahead/behind relative to origin/main") { @opts[:status] = true }
199
+ o.on("--create", "Create missing mirrors (GitLab via push-to-create, Codeberg via API) when fetch fails") { @opts[:create] = true }
185
200
  o.on("--force", "Accept defaults; non-interactive") { @opts[:force] = true }
186
201
  o.on("-h", "--help", "Show help") {
187
202
  puts o
@@ -356,41 +371,177 @@ module Kettle
356
371
  results
357
372
  end
358
373
 
359
- # Update README federation disclosure based on fetch results
360
- def update_readme_federation_status!(org, repo, results)
361
- readme_path = File.join(Dir.pwd, "README.md")
362
- return unless File.exist?(readme_path)
363
-
364
- content = File.read(readme_path)
365
- # Determine if all succeeded
366
- forges = [:github, :gitlab, :codeberg]
367
- all_ok = forges.all? { |f| results[f] }
368
- new_content = content.dup
369
- summary_line_with_cs = /<summary>Find this repo on other forges \(Coming soon!\)<\/summary>/
370
- summary_line_no_cs = "<summary>Find this repo on other forges</summary>"
371
- if all_ok
372
- new_content.gsub!(summary_line_with_cs, summary_line_no_cs)
373
- else
374
- # Ensure the line contains (Coming soon!) so readers know it's partial
375
- unless summary_line_with_cs.match?(content)
376
- new_content.gsub!("<summary>Find this repo on other forges</summary>", "<summary>Find this repo on other forges (Coming soon!)</summary>")
377
- end
374
+ # Write per-forge availability to .kettle/forges.yml for kettle-jem,
375
+ # which renders it into the README forge badges and Federated DVCS
376
+ # table. Manually opted-out ("off") forges survive re-runs.
377
+ def write_forge_state!(results)
378
+ states = FORGES.each_with_object({}) { |forge, acc| acc[forge.to_s] = results[forge] ? "live" : "pending" }
379
+ preserve_off_states!(states)
380
+ FileUtils.mkdir_p(File.dirname(FORGES_STATE_PATH))
381
+ File.write(FORGES_STATE_PATH, <<~YAML)
382
+ # Written by kettle-dvcs; consumed by kettle-jem README templating.
383
+ # states: live (verified reachable), pending (not yet), off (opted out manually).
384
+ # Values are quoted: bare `off`/`on` parse as booleans in YAML 1.1.
385
+ origin: #{@opts[:origin]}
386
+ forges:
387
+ github: "#{states.fetch("github")}"
388
+ gitlab: "#{states.fetch("gitlab")}"
389
+ codeberg: "#{states.fetch("codeberg")}"
390
+ YAML
391
+ summary = FORGES.map { |forge| "#{forge}=#{states.fetch(forge.to_s)}" }.join(", ")
392
+ say("Wrote #{FORGES_STATE_PATH} (#{summary})")
393
+ end
394
+
395
+ def preserve_off_states!(states)
396
+ return unless File.file?(FORGES_STATE_PATH)
397
+
398
+ existing = Kettle::Dev.safe_load_yaml_file(FORGES_STATE_PATH)
399
+ return unless existing.is_a?(Hash) && existing["forges"].is_a?(Hash)
400
+
401
+ existing["forges"].each do |name, value|
402
+ state = value.is_a?(Hash) ? value["state"] : value
403
+ state = "off" if state == false # YAML 1.1 parses bare `off` as false
404
+ states[name.to_s] = "off" if state.to_s == "off" && states.key?(name.to_s)
378
405
  end
379
- if new_content != content
380
- File.write(readme_path, new_content)
381
- say("Updated README federation summary to reflect current forge status")
406
+ rescue Psych::Exception
407
+ nil
408
+ end
409
+
410
+ # Print import links for any forge that is still unavailable.
411
+ def print_import_links(results)
412
+ return if FORGES.all? { |forge| results[forge] }
413
+
414
+ say("\nSome forges are not yet available. Use these import links to create mirrors:")
415
+ FORGES.each do |forge|
416
+ next if results[forge]
417
+
418
+ say(" - #{forge.capitalize} import: #{FORGE_MIGRATION_TOOLS[forge]}")
382
419
  end
383
- # Print import links for any failed forge
384
- unless all_ok
385
- say("\nSome forges are not yet available. Use these import links to create mirrors:")
386
- [:github, :gitlab, :codeberg].each do |forge|
387
- next if results[forge]
420
+ end
388
421
 
389
- say(" - #{forge.capitalize} import: #{FORGE_MIGRATION_TOOLS[forge]}")
422
+ # --create: attempt to create mirrors for forges that failed fetch, then
423
+ # re-fetch to verify. GitLab supports push-to-create; Codeberg disables
424
+ # it, so creation goes through the Forgejo API (CB_TOKEN required).
425
+ def create_missing_mirrors!(git, names, org, repo, results)
426
+ branch = detect_default_branch!(git)
427
+ FORGES.each do |forge|
428
+ next if results[forge]
429
+
430
+ remote = names[forge]
431
+ next unless remote
432
+
433
+ created = case forge
434
+ when :gitlab then create_gitlab_mirror!(git, remote, org, repo, branch)
435
+ when :codeberg then create_codeberg_mirror!(git, remote, org, repo, branch)
436
+ else
437
+ say(" - #{forge}: cannot auto-create; use #{FORGE_MIGRATION_TOOLS[forge]}")
438
+ false
390
439
  end
440
+ next unless created
441
+
442
+ verified = git.fetch(remote)
443
+ results[forge] = !!verified
444
+ say(" - #{forge}: mirror created and verified") if results[forge]
445
+ say(" - #{forge}: created, but verification fetch still fails") unless results[forge]
446
+ end
447
+ results
448
+ end
449
+
450
+ # GitLab creates a project when pushing to a nonexistent path in a
451
+ # namespace you can create in (push-to-create). New projects are
452
+ # PRIVATE, so visibility is flipped to public via API when a token is
453
+ # available; otherwise the settings link is printed. Beware: pushing to
454
+ # a previously renamed path silently targets the renamed project
455
+ # instead of creating a new one, so the output is checked for the
456
+ # "was created" notice.
457
+ def create_gitlab_mirror!(git, remote, org, repo, branch)
458
+ say(" - gitlab: attempting push-to-create (git push #{remote} #{branch})...")
459
+ out, ok = git.capture(["push", remote, branch])
460
+ unless ok
461
+ say(" - gitlab: push-to-create failed: #{out}")
462
+ return false
463
+ end
464
+ if out.to_s.match?(/redirect/i)
465
+ say(" - gitlab: push followed a rename redirect; refusing to treat that as mirror creation")
466
+ return false
467
+ end
468
+ if out.to_s.include?("was created")
469
+ token = ENV["GL_TOKEN"] || ENV["GITLAB_TOKEN"]
470
+ if token.to_s.empty?
471
+ say(" - gitlab: project created as PRIVATE. Make it public: https://gitlab.com/#{org}/#{repo}/-/edit (or set GL_TOKEN)")
472
+ else
473
+ make_gitlab_project_public!(org, repo, token)
474
+ end
475
+ else
476
+ say(" - gitlab: pushed to existing project (fetch failure may be auth/visibility related)")
477
+ end
478
+ true
479
+ end
480
+
481
+ def make_gitlab_project_public!(org, repo, token)
482
+ path = URI.encode_www_form_component("#{org}/#{repo}")
483
+ code, = http_json_request(:put, "https://gitlab.com/api/v4/projects/#{path}", headers: {"PRIVATE-TOKEN" => token}, payload: {visibility: "public"})
484
+ if (200..299).cover?(code)
485
+ say(" - gitlab: project visibility set to public")
486
+ else
487
+ say(" - gitlab: could not set visibility via API (#{code}); make it public: https://gitlab.com/#{org}/#{repo}/-/edit")
488
+ end
489
+ end
490
+
491
+ # Codeberg (Forgejo) disables push-to-create, so the repository is
492
+ # created via API (personal namespace vs org chosen from the token's
493
+ # user), then content is mirrored with a normal push.
494
+ def create_codeberg_mirror!(git, remote, org, repo, branch)
495
+ token = ENV["CB_TOKEN"] || ENV["CODEBERG_TOKEN"]
496
+ if token.to_s.empty?
497
+ say(" - codeberg: push-to-create is disabled on Codeberg; set CB_TOKEN to create via API, or use #{FORGE_MIGRATION_TOOLS[:codeberg]}")
498
+ return false
499
+ end
500
+ code, user = http_json_request(:get, "https://codeberg.org/api/v1/user", headers: {"Authorization" => "token #{token}"})
501
+ unless (200..299).cover?(code)
502
+ say(" - codeberg: API authentication failed (#{code}); check CB_TOKEN")
503
+ return false
504
+ end
505
+ endpoint = if user["login"].to_s.casecmp(org).zero?
506
+ "https://codeberg.org/api/v1/user/repos"
507
+ else
508
+ "https://codeberg.org/api/v1/orgs/#{URI.encode_www_form_component(org)}/repos"
509
+ end
510
+ code, body = http_json_request(:post, endpoint, headers: {"Authorization" => "token #{token}"}, payload: {name: repo, private: false})
511
+ unless [201, 409].include?(code) # 409: repo already exists
512
+ say(" - codeberg: repo creation failed (#{code}): #{body["message"]}")
513
+ return false
514
+ end
515
+ out, ok = git.capture(["push", remote, branch])
516
+ say(" - codeberg: push failed: #{out}") unless ok
517
+ ok
518
+ end
519
+
520
+ def http_json_request(method, url, headers:, payload: nil)
521
+ uri = URI(url)
522
+ request = case method
523
+ when :get then Net::HTTP::Get.new(uri)
524
+ when :post then Net::HTTP::Post.new(uri)
525
+ when :put then Net::HTTP::Put.new(uri)
526
+ else
527
+ raise ArgumentError, "unsupported HTTP method: #{method}"
528
+ end
529
+ headers.each { |key, value| request[key] = value }
530
+ request["Accept"] = "application/json"
531
+ if payload
532
+ request["Content-Type"] = "application/json"
533
+ request.body = JSON.generate(payload)
534
+ end
535
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
536
+ body = begin
537
+ JSON.parse(response.body.to_s)
538
+ rescue JSON::ParserError
539
+ {}
391
540
  end
541
+ [response.code.to_i, body]
392
542
  rescue => e
393
- warn("Failed to update README federation status: #{e.message}")
543
+ say(" - HTTP #{method.to_s.upcase} #{url} failed: #{e.class}: #{e.message}")
544
+ [0, {}]
394
545
  end
395
546
 
396
547
  def say(msg)
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Kettle
6
+ module Dev
7
+ # Computes and updates the README KLOC badge from CHANGELOG coverage
8
+ # summaries or SimpleCov JSON coverage reports.
9
+ #
10
+ # Shared by standalone releases (kettle-release) and monorepo family
11
+ # releases (kettle-family). Guards against zero-line counts so a broken
12
+ # coverage run (0/0 lines) never overwrites a real KLOC badge with 0.000.
13
+ module KlocBadge
14
+ BADGE_PATTERN = /(\[🧮kloc-img\]:\s*https?:\/\/img\.shields\.io\/badge\/KLOC-)(\d+(?:\.\d+)?)(-[^\s]*)/
15
+ CHANGELOG_COVERAGE_PATTERN = /-\s*COVERAGE:\s*.+--\s*\d+\/(\d+)\s+lines/i
16
+
17
+ module_function
18
+
19
+ # Format a positive line count as a 3-decimal KLOC string (e.g. "2.175").
20
+ # Returns nil when line_count is nil or <= 0.
21
+ #
22
+ # @param line_count [Integer, nil]
23
+ # @return [String, nil]
24
+ def format_kloc(line_count)
25
+ count = line_count.to_i
26
+ return nil unless count > 0
27
+
28
+ format("%.3f", count.to_f / 1000.0)
29
+ end
30
+
31
+ # Extract a formatted KLOC string from a CHANGELOG version section's
32
+ # COVERAGE line. Returns nil when absent or when the denominator is 0.
33
+ #
34
+ # @param section [String, nil]
35
+ # @return [String, nil]
36
+ def kloc_from_changelog_section(section)
37
+ return nil if section.to_s.empty?
38
+
39
+ match = section.to_s.match(CHANGELOG_COVERAGE_PATTERN)
40
+ return nil unless match
41
+
42
+ format_kloc(match[1].to_i)
43
+ end
44
+
45
+ # Parse a SimpleCov coverage.json file once and return its coverage file
46
+ # map alongside the inferred project root directory, or nil on error.
47
+ #
48
+ # @param coverage_path [String, nil]
49
+ # @return [Array(Hash, String), nil]
50
+ def parse_coverage_json(coverage_path)
51
+ return nil if coverage_path.to_s.empty? || !File.file?(coverage_path)
52
+
53
+ data = JSON.parse(File.read(coverage_path))
54
+ return nil unless data.is_a?(Hash)
55
+
56
+ files = data["coverage"]
57
+ return nil unless files.is_a?(Hash)
58
+
59
+ coverage_root = File.dirname(File.dirname(File.expand_path(coverage_path)))
60
+ [files, coverage_root]
61
+ rescue JSON::ParserError, SystemCallError
62
+ nil
63
+ end
64
+
65
+ # Count total relevant (trackable) lines from an already-parsed coverage
66
+ # file map, optionally restricted to files within scope_root.
67
+ #
68
+ # @param files [Hash]
69
+ # @param scope_root [String, nil]
70
+ # @param coverage_root [String, nil]
71
+ # @return [Integer]
72
+ def lines_from_coverage_data(files, scope_root: nil, coverage_root: nil, **_options)
73
+ scoped_root = scope_root.to_s.empty? ? nil : Paths.canonical(scope_root)
74
+
75
+ total_lines = 0
76
+ files.each do |file_path, entry|
77
+ next unless entry.is_a?(Hash)
78
+ if scoped_root
79
+ next unless Paths.within?(file_path.to_s, scoped_root, base: coverage_root)
80
+ end
81
+
82
+ lines = entry["lines"]
83
+ next unless lines.is_a?(Array)
84
+
85
+ total_lines += lines.count { |value| value.is_a?(Integer) }
86
+ end
87
+ total_lines
88
+ end
89
+
90
+ # Count total relevant (trackable) lines in a SimpleCov coverage.json
91
+ # file, optionally restricted to files within scope_root.
92
+ # Returns nil when coverage_path does not exist or cannot be parsed.
93
+ #
94
+ # @param coverage_path [String, nil]
95
+ # @param scope_root [String, nil]
96
+ # @return [Integer, nil]
97
+ def lines_from_coverage_json(coverage_path, scope_root: nil, **options)
98
+ parsed = parse_coverage_json(coverage_path)
99
+ return nil unless parsed
100
+
101
+ files, coverage_root = parsed
102
+ lines_from_coverage_data(files, scope_root: scope_root, coverage_root: coverage_root, **options)
103
+ end
104
+
105
+ # Compute a formatted KLOC string from a SimpleCov coverage.json file,
106
+ # optionally scoped to files under scope_root. Returns nil when missing,
107
+ # invalid, or 0 lines.
108
+ #
109
+ # @param coverage_path [String, nil]
110
+ # @param scope_root [String, nil]
111
+ # @return [String, nil]
112
+ def kloc_from_coverage_json(coverage_path, scope_root: nil, **options)
113
+ lines = lines_from_coverage_json(coverage_path, scope_root: scope_root, **options)
114
+ return nil unless lines
115
+
116
+ format_kloc(lines)
117
+ end
118
+
119
+ # Rewrite the [🧮kloc-img] badge number in a single file.
120
+ # Returns true when the file was modified, false otherwise.
121
+ #
122
+ # @param path [String, nil]
123
+ # @param kloc_str [String, nil]
124
+ # @return [Boolean]
125
+ def update_file(path, kloc_str)
126
+ return false if path.to_s.empty? || kloc_str.to_s.empty? || !File.file?(path)
127
+
128
+ content = File.read(path)
129
+ new_content = content.gsub(BADGE_PATTERN, "\\1#{kloc_str}\\3")
130
+ return false if new_content == content
131
+
132
+ File.write(path, new_content)
133
+ true
134
+ end
135
+
136
+ # Update README.md (and README.md.example when present) under project_root.
137
+ # Returns the list of modified file paths.
138
+ #
139
+ # @param project_root [String]
140
+ # @param kloc_str [String, nil]
141
+ # @return [Array<String>]
142
+ def update_project_readmes(project_root, kloc_str, **_options)
143
+ return [] if project_root.to_s.empty? || kloc_str.to_s.empty?
144
+
145
+ updated = []
146
+ [
147
+ File.join(project_root, "README.md"),
148
+ File.join(project_root, "README.md.example")
149
+ ].each do |path|
150
+ updated << path if update_file(path, kloc_str)
151
+ end
152
+ updated
153
+ end
154
+
155
+ # Compute member-scoped KLOC from coverage_path and update README files
156
+ # under project_root. Returns the list of modified file paths.
157
+ #
158
+ # @param project_root [String]
159
+ # @param coverage_path [String]
160
+ # @param scope_root [String, nil]
161
+ # @return [Array<String>]
162
+ def update_from_coverage_json(project_root:, coverage_path:, scope_root: project_root, **options)
163
+ kloc_str = kloc_from_coverage_json(coverage_path, scope_root: scope_root, **options)
164
+ return [] unless kloc_str
165
+
166
+ update_project_readmes(project_root, kloc_str, **options)
167
+ end
168
+
169
+ # Parse coverage_path once and update README KLOC badges for each
170
+ # member root in member_roots. Returns the list of modified file paths.
171
+ #
172
+ # @param member_roots [Array<String>]
173
+ # @param coverage_path [String]
174
+ # @return [Array<String>]
175
+ def update_members_from_coverage_json(member_roots:, coverage_path:, **options)
176
+ parsed = parse_coverage_json(coverage_path)
177
+ return [] unless parsed
178
+
179
+ files, coverage_root = parsed
180
+ updated = []
181
+ Array(member_roots).each do |member_root|
182
+ lines = lines_from_coverage_data(files, scope_root: member_root, coverage_root: coverage_root, **options)
183
+ kloc_str = format_kloc(lines)
184
+ next unless kloc_str
185
+
186
+ updated.concat(update_project_readmes(member_root, kloc_str, **options))
187
+ end
188
+ updated
189
+ end
190
+ end
191
+ end
192
+ end
@@ -306,6 +306,8 @@ module Kettle
306
306
  return run_family_member_publish if family_member_publish?
307
307
  return run_family_member_finalize if family_member_finalize?
308
308
 
309
+ sync_upstream_before_release_prep!
310
+
309
311
  # Changelog generation at step 0 runs the target project's test bundle
310
312
  # to collect coverage. Normalize its canonical release lockfile before
311
313
  # that subprocess starts; otherwise a local development PATH lock can
@@ -1367,44 +1369,47 @@ module Kettle
1367
1369
  ENV.fetch("K_CHANGELOG_COVERAGE_HARD", "true").downcase != "false"
1368
1370
  end
1369
1371
 
1370
- # Update the README KLOC badge number based on the denominator in the current version's COVERAGE line in CHANGELOG.md.
1371
- # - Parses the current version section of CHANGELOG.md
1372
- # - Finds a line matching: "- COVERAGE: ... -- <tested>/<total> lines ..."
1373
- # - Computes KLOC = total / 1000.0
1374
- # - Formats with three decimals (e.g., 0.076, 2.175, 10.123)
1375
- # - Rewrites the [🧮kloc-img] badge line in README.md (and README.md.example when present)
1376
- # replacing only the numeric portion after "KLOC-" while preserving other URL params.
1372
+ # Update the README KLOC badge number based on the current version's
1373
+ # COVERAGE line in a project-local CHANGELOG.md, or a member-scoped
1374
+ # SimpleCov coverage.json when sharing a monorepo root CHANGELOG.md.
1375
+ # Never overwrites the badge when the line count is 0.
1377
1376
  def update_readme_kloc_badge!
1378
- version = detect_version
1379
- # Extract only the current version's section
1380
- section, _compare_ref, _tag_ref = extract_changelog_for_version(version)
1381
- return unless section
1377
+ kloc_str = resolved_readme_kloc
1378
+ return unless kloc_str
1382
1379
 
1383
- # Example match: "- COVERAGE: 97.70% -- 2125/2175 lines in 20 files"
1384
- m = section.lines.find { |l| /-\s*COVERAGE:\s*.+--\s*\d+\/(\d+)\s+lines/i.match?(l) }
1385
- return unless m
1380
+ KlocBadge.update_project_readmes(@root, kloc_str)
1381
+ end
1382
+
1383
+ def resolved_readme_kloc
1384
+ changelog_path = resolved_changelog_path
1385
+ if Paths.within?(changelog_path, @root)
1386
+ version = detect_version
1387
+ section, _compare_ref, _tag_ref = extract_changelog_for_version(version)
1388
+ kloc_str = KlocBadge.kloc_from_changelog_section(section)
1389
+ return kloc_str if kloc_str
1390
+ end
1386
1391
 
1387
- denom = m.match(/-\s*COVERAGE:\s*.+--\s*\d+\/(\d+)\s+lines/i)[1].to_i
1388
- kloc = denom.to_f / 1000.0
1389
- kloc_str = format("%.3f", kloc)
1392
+ coverage_json_kloc_candidates(changelog_path).each do |coverage_path|
1393
+ kloc_str = KlocBadge.kloc_from_coverage_json(coverage_path, scope_root: @root)
1394
+ return kloc_str if kloc_str
1395
+ end
1396
+ nil
1397
+ end
1390
1398
 
1391
- update_badge_number_in_file(File.join(@root, "README.md"), kloc_str)
1392
- example_path = File.join(@root, "README.md.example")
1393
- update_badge_number_in_file(example_path, kloc_str) if File.file?(example_path)
1399
+ def coverage_json_kloc_candidates(changelog_path)
1400
+ candidates = [File.join(@root, "coverage", "coverage.json")]
1401
+ coverage_root = ENV["K_CHANGELOG_COVERAGE_ROOT"].to_s.strip
1402
+ candidates << File.join(File.expand_path(coverage_root, @root), "coverage", "coverage.json") unless coverage_root.empty?
1403
+ unless Paths.within?(changelog_path, @root)
1404
+ candidates << File.join(File.dirname(changelog_path), "coverage", "coverage.json")
1405
+ end
1406
+ candidates.uniq
1394
1407
  end
1395
1408
 
1396
1409
  # Helper to update the [🧮kloc-img] badge in the given file path.
1397
1410
  # Replaces only the numeric portion after "KLOC-" keeping other URL parts intact.
1398
1411
  def update_badge_number_in_file(path, kloc_str)
1399
- return unless File.file?(path)
1400
-
1401
- content = File.read(path)
1402
- # Match the specific reference line, capture groups around the number
1403
- # Example: [🧮kloc-img]: https://img.shields.io/badge/KLOC-2.175-FFDD67.svg?style=...
1404
- new_content = content.gsub(/(\[🧮kloc-img\]:\s*https?:\/\/img\.shields\.io\/badge\/KLOC-)(\d+(?:\.\d+)?)(-[^\s]*)/, "\\1#{kloc_str}\\3")
1405
- if new_content != content
1406
- File.write(path, new_content)
1407
- end
1412
+ KlocBadge.update_file(path, kloc_str)
1408
1413
  end
1409
1414
 
1410
1415
  # Update Rakefile.example banner to include current gem version and current date.
@@ -3273,6 +3278,30 @@ module Kettle
3273
3278
  puts "Merged #{feature} into #{trunk} and pushed. The PR (if any) should auto-close."
3274
3279
  end
3275
3280
 
3281
+ # Release prep (changelog, README, docs, lockfiles) is committed at step 6,
3282
+ # but the trunk is only synced at step 8. Upstream changes to those files
3283
+ # then conflict with the prep commit mid-rebase. Sync the checkout to its
3284
+ # upstream up front, while it is still clean, so step 8 has nothing to do.
3285
+ #
3286
+ # Skipped when resuming past the first steps (the prep commit may already
3287
+ # exist), for local CI releases, for branch-stack release branches (they
3288
+ # sync their own lanes), and when nested inside an outer command that
3289
+ # already synced (Kettle::Dev::Rebase honors KETTLE_REBASE_NESTED).
3290
+ def sync_upstream_before_release_prep!
3291
+ return if @start_step > 1 || local_ci?
3292
+ return if local_kettle_family_release_target_branches.include?(current_branch)
3293
+
3294
+ result = Kettle::Dev::Rebase.call(root: @root)
3295
+ return if result.status == :skipped_nested
3296
+
3297
+ puts "Upstream sync: #{result.message}"
3298
+ return if result.ok?
3299
+
3300
+ abort("Aborting before release prep: #{result.message}") if result.status == :conflict
3301
+
3302
+ warn("Upstream sync failed (#{result.message}); continuing with local state.")
3303
+ end
3304
+
3276
3305
  def branch_stack_release_branch?(branch, trunk = nil)
3277
3306
  return false if branch.to_s.empty?
3278
3307
  return false if trunk && branch == trunk
@@ -5,7 +5,7 @@ module Kettle
5
5
  # Version namespace for this gem.
6
6
  module Version
7
7
  # Current gem version.
8
- VERSION = "3.1.34"
8
+ VERSION = "3.1.36"
9
9
  end
10
10
  # Current gem version exposed at the traditional constant location.
11
11
  VERSION = Version::VERSION # Traditional Constant Location
data/lib/kettle/dev.rb CHANGED
@@ -44,6 +44,7 @@ module Kettle
44
44
  autoload :GhaShaPinsCLI, "kettle/dev/gha_sha_pins_cli"
45
45
  autoload :InputAdapter, "kettle/dev/input_adapter"
46
46
  autoload :InteractiveReleaseCommand, "kettle/dev/interactive_release_command"
47
+ autoload :KlocBadge, "kettle/dev/kloc_badge"
47
48
  autoload :LockfileReset, "kettle/dev/lockfile_reset"
48
49
  autoload :MarkdownReferenceValidator, "kettle/dev/markdown_reference_validator"
49
50
  autoload :ReadmeBackers, "kettle/dev/readme_backers"
data/sig/kettle/dev.rbs CHANGED
@@ -362,6 +362,22 @@ module Kettle
362
362
  def self.block_call_to?: (Prism::Node node, Symbol method_name) -> bool
363
363
  end
364
364
 
365
+ module KlocBadge
366
+ BADGE_PATTERN: Regexp
367
+ CHANGELOG_COVERAGE_PATTERN: Regexp
368
+
369
+ def self.format_kloc: (Integer? line_count) -> String?
370
+ def self.kloc_from_changelog_section: (String? section) -> String?
371
+ def self.parse_coverage_json: (String? coverage_path) -> [Hash[String, untyped], String]?
372
+ def self.lines_from_coverage_data: (Hash[String, untyped] files, ?scope_root: String?, ?coverage_root: String?, **untyped) -> Integer
373
+ def self.lines_from_coverage_json: (String? coverage_path, ?scope_root: String?, **untyped) -> Integer?
374
+ def self.kloc_from_coverage_json: (String? coverage_path, ?scope_root: String?, **untyped) -> String?
375
+ def self.update_file: (String? path, String? kloc_str) -> bool
376
+ def self.update_project_readmes: (String project_root, String? kloc_str, **untyped) -> Array[String]
377
+ def self.update_from_coverage_json: (project_root: String, coverage_path: String, ?scope_root: String?, **untyped) -> Array[String]
378
+ def self.update_members_from_coverage_json: (member_roots: Array[String], coverage_path: String, **untyped) -> Array[String]
379
+ end
380
+
365
381
  class ReadmeBackers
366
382
  def initialize: (
367
383
  handle: String?,
@@ -387,7 +403,9 @@ module Kettle
387
403
  private
388
404
 
389
405
  def update_readme_kloc_badge!: () -> void
390
- def update_badge_number_in_file: (String path, String kloc_str) -> void
406
+ def resolved_readme_kloc: () -> String?
407
+ def coverage_json_kloc_candidates: (String changelog_path) -> Array[String]
408
+ def update_badge_number_in_file: (String path, String kloc_str) -> bool
391
409
  def update_rakefile_example_header!: (String version) -> void
392
410
  def validate_copyright_years!: () -> void
393
411
  def extract_years_from_file: (String path) -> ::Set[Integer]
data.tar.gz.sig CHANGED
Binary file
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kettle-dev
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.34
4
+ version: 3.1.36
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter H. Boling
@@ -439,6 +439,7 @@ files:
439
439
  - lib/kettle/dev/git_commit_footer.rb
440
440
  - lib/kettle/dev/input_adapter.rb
441
441
  - lib/kettle/dev/interactive_release_command.rb
442
+ - lib/kettle/dev/kloc_badge.rb
442
443
  - lib/kettle/dev/lockfile_reset.rb
443
444
  - lib/kettle/dev/markdown_reference_validator.rb
444
445
  - lib/kettle/dev/open_collective_config.rb
@@ -476,10 +477,10 @@ licenses:
476
477
  - AGPL-3.0-only
477
478
  metadata:
478
479
  homepage_uri: "https://kettle-dev.galtzo.com"
479
- source_code_uri: "https://github.com/kettle-dev/kettle-dev/tree/v3.1.34"
480
- changelog_uri: "https://github.com/kettle-dev/kettle-dev/blob/v3.1.34/CHANGELOG.md"
480
+ source_code_uri: "https://github.com/kettle-dev/kettle-dev/tree/v3.1.36"
481
+ changelog_uri: "https://github.com/kettle-dev/kettle-dev/blob/v3.1.36/CHANGELOG.md"
481
482
  bug_tracker_uri: "https://github.com/kettle-dev/kettle-dev/issues"
482
- documentation_uri: "https://www.rubydoc.info/gems/kettle-dev/3.1.34"
483
+ documentation_uri: "https://www.rubydoc.info/gems/kettle-dev/3.1.36"
483
484
  funding_uri: "https://github.com/sponsors/pboling"
484
485
  wiki_uri: "https://github.com/kettle-dev/kettle-dev/wiki"
485
486
  news_uri: "https://www.railsbling.com/tags/kettle-dev"
metadata.gz.sig CHANGED
Binary file