208 Commits

Author SHA1 Message Date
3b8dd87c4b Prepare v0.11.0 release notes and adoption guidance 2026-12-06 03:48:03 +00:00
fe346c9036 Remove completed release plans and remediation notes 2026-12-06 03:45:20 +00:00
697cd27cde Keep Go readiness separate from publication file checks 2026-12-06 03:39:11 +00:00
d733298bd9 Stream discarded CI log lines without retaining them 2026-12-06 03:35:18 +00:00
4b515404a8 Limit readiness scans to selected package inputs 2026-12-06 03:33:52 +00:00
3f7dd4b2e5 Index observed CI pipeline identities 2026-12-06 03:31:09 +00:00
c930788bf8 Clarify that implementation needs no published example pin 2026-12-06 03:29:36 +00:00
6c94b1fb85 Keep Go package patterns usable during readiness 2026-12-06 03:26:00 +00:00
d5154cf59d Distinguish production tags from complete diagnostic tags 2026-12-06 03:21:39 +00:00
0205f32f28 Describe selected source and version behavior accurately 2026-12-06 03:17:26 +00:00
76252cb5d0 Accept consistent overlaps in CI pipeline pagination 2026-12-06 03:16:17 +00:00
67a560e3fd Recover rejected rehearsals without remote credentials 2026-12-06 03:15:16 +00:00
b4f984fd5b Retain safe CI diagnostics in rehearsal results 2026-12-06 03:13:42 +00:00
b74c054c02 Route diagnostic delivery through the public facade 2026-12-06 03:10:47 +00:00
2b5032d8c9 Clean known rehearsal pages after their tags are removed 2026-12-06 02:59:33 +00:00
75823d6c82 Distinguish rejected rehearsal pushes from uncertain writes 2026-12-06 02:57:35 +00:00
0906cf7094 Validate module readiness without a synthetic version 2026-12-06 02:51:56 +00:00
4088923a45 Keep required local inputs separate from committed source 2026-12-06 02:50:12 +00:00
c626ee4e27 Validate selected release configuration during readiness 2026-12-06 02:49:22 +00:00
633df7a02b Record algorithmic audit findings 2026-12-06 02:39:19 +00:00
fad1567e54 Record additional integration audit findings 2026-12-06 02:01:19 +00:00
67c836388b Record implementation review findings 2026-12-06 01:38:44 +00:00
dd9e177420 Complete rehearsal guidance and integrated verification 2026-12-05 23:48:37 +00:00
3524d8bbb6 Wire rehearsal commands and tagged workflows 2026-12-05 23:35:52 +00:00
8caeeb3d78 Resume and safely clean recorded rehearsals 2026-12-05 23:26:01 +00:00
a348da32da Coordinate diagnostic attempts and CI observation 2026-12-05 23:14:15 +00:00
5ddb7453ec Verify diagnostic deliveries inside CI 2026-12-05 23:00:04 +00:00
4210552cb8 Observe rehearsal resources and support safe cleanup 2026-12-05 22:52:46 +00:00
181e5a030c Capture diagnostic identities and rehearsal records 2026-12-05 22:45:28 +00:00
6f01e9ef0a Add pinned tools for source-only releases 2026-12-05 22:30:21 +00:00
d185df5fd1 Remove the release dependency from the implementation plan 2026-12-05 22:27:25 +00:00
000e9ef9b9 Add read-only release readiness validation 2026-12-05 22:03:34 +00:00
92b820b234 Select delivery credentials by execution context 2026-12-05 21:41:34 +00:00
697ab32715 Preserve release identity in records and receipts 2026-12-05 21:34:51 +00:00
bbee996f84 Carry source identity through builds and delivery 2026-12-05 21:22:38 +00:00
3b925231d5 Validate and publish source-only candidates 2026-12-05 21:05:56 +00:00
0f9923d230 Resolve source and diagnostic release identities 2026-12-05 20:57:10 +00:00
b0fce88a51 Normalize source and publication selection 2026-12-05 20:47:58 +00:00
8f3b59b5f2 Plan the next release implementation 2026-12-05 19:42:51 +00:00
652dcfc7b1 Draft source-release identity and Woodpecker rehearsal ADRs 2026-12-05 19:24:49 +00:00
87e4305889 Consolidate settled roadmap decisions and planning details 2026-12-05 19:19:33 +00:00
751ce6d54a Clarify when Go module version constraints apply 2026-12-05 19:15:39 +00:00
f4a0064342 Plan source-only repository release support 2026-12-05 19:13:45 +00:00
bde8a830df Record application versioning and module identity decisions 2026-12-05 19:06:57 +00:00
ba73721d51 Record readiness validation decisions 2026-12-05 18:59:51 +00:00
eed068bd22 Plan end-to-end Woodpecker delivery rehearsals 2026-12-05 17:12:12 +00:00
7def1fd840 Clarify planned local and CI credential selection 2026-12-05 17:07:44 +00:00
86723750d3 Outline proposals for the next release 2026-12-03 01:46:08 +00:00
82bac1a3ab Prepare the v0.10.0 release notes 2026-11-17 15:31:10 +00:00
0f0bace29e Upgrade to Go 1.27 and refresh dependencies 2026-11-17 15:26:46 +00:00
2180aa868e Prepare the v0.9.0 release notes and retire completed roadmaps 2026-11-04 01:59:54 +00:00
bf4e2329ec Build delivery retries from clean tagged source 2026-11-04 01:52:26 +00:00
bd1c714935 Invoke the registered ReleaseKit package explicitly 2026-11-04 01:51:36 +00:00
f625674a68 Record follow up launcher review findings 2026-11-04 01:42:03 +00:00
9797f43dc4 Anchor smoke checks to the selected checkout 2026-11-04 01:25:50 +00:00
b5c6638538 Preserve replacement selectors during recovery 2026-11-04 01:25:34 +00:00
ec67496569 Align source and standalone tool instructions 2026-11-04 01:24:16 +00:00
d99fac23e9 Explain target variables in configured checks 2026-11-04 01:23:40 +00:00
a3c74188be Use external Go in recovery commands 2026-11-04 01:23:24 +00:00
7dcc9a37c7 Record that host native launchers are implemented 2026-11-04 01:22:27 +00:00
68ce3e5a3b Verify cross built workflow assets 2026-11-04 01:21:58 +00:00
b00bc41b65 Clarify the recovery command target scope 2026-11-04 01:21:28 +00:00
fcec6357ff Make the adoption smoke command runnable 2026-11-04 01:21:20 +00:00
13e1c21386 Record host launcher algorithm audit findings 2026-11-04 01:20:02 +00:00
80a610a5c2 Record host launcher integration findings 2026-11-04 01:10:34 +00:00
d02b9ffeb8 Record host native launcher review findings 2026-11-04 01:02:39 +00:00
0269648429 Document host-native release launchers 2026-11-04 00:54:44 +00:00
bd693ca31b Run recovery handoffs for the host target 2026-11-04 00:52:04 +00:00
d8ec9389e0 Prepare recovery tools for the host target 2026-11-04 00:50:59 +00:00
10028c4abb Use the host target for source-built release tools 2026-11-04 00:49:59 +00:00
8e897d7b3e Use the host target in consumer delivery workflows 2026-11-04 00:49:10 +00:00
a8ffa89011 Use the host target in the multi-module launcher 2026-11-04 00:47:38 +00:00
bf07bed2ae Plan host native release launchers 2026-11-04 00:43:57 +00:00
373f7a69cd Include recovery handoffs in the host launcher roadmap 2026-11-04 00:39:01 +00:00
b1ce5bf976 Plan host-native consumer launcher fixes 2026-11-03 15:48:37 +00:00
23203f235c Clarify credential redaction and tool registration in release notes 2026-11-03 00:41:40 +00:00
37d6209aec Prepare v0.8.0 notes and retire completed roadmaps 2026-11-03 00:29:51 +00:00
ee72566263 Verify vendored recovery after launcher cleanup 2026-11-03 00:23:06 +00:00
e0019abe31 Validate byte-preserving record fields as base64 strings 2026-11-03 00:18:47 +00:00
2a7bed87db Classify recovery setup failures by their actual cause 2026-11-03 00:15:36 +00:00
dfaa652098 Keep recovery handoffs available after publication cancellation 2026-11-03 00:12:30 +00:00
cd08a2892a Run API-only recovery independently of consumer vendoring 2026-11-03 00:05:32 +00:00
16d1c072e3 Record remaining recovery findings and recommended fixes 2026-11-03 00:00:42 +00:00
363f7cd513 Retain discovered publication records when enumeration fails 2026-11-02 22:41:18 +00:00
cd274512e7 Reject trailing record JSON without decoding a second value 2026-11-02 22:37:12 +00:00
3b8bacf114 Filter publication record names before sorting directory results 2026-11-02 22:36:35 +00:00
781341a0ba Preserve exact evidence bytes in private publication records 2026-11-02 22:35:53 +00:00
109596bc3b Use the source-built CLI in maintainer recovery instructions 2026-11-02 22:34:19 +00:00
6fc140d8dc Verify record storage preserves whitespace in Git paths 2026-11-02 22:33:29 +00:00
993866c1d7 Keep publication recovery usable after cold Go tool runs 2026-11-02 22:32:58 +00:00
19a14bfeb6 Report JSON output failures from recovery commands 2026-11-02 22:23:15 +00:00
648c87bb8a Redact credentials throughout publication recovery displays 2026-11-02 22:22:31 +00:00
04db23705a Honor cancellation throughout publication recovery Git operations 2026-11-02 22:20:53 +00:00
9a7b9b9301 Allow explicit publication stores in Git metadata 2026-11-02 22:18:51 +00:00
d2b1329095 Check the exact publication record filename before writing 2026-11-02 22:17:59 +00:00
0d19a5546f Preserve candidate failures when initializing publication records 2026-11-02 22:17:29 +00:00
da1839c6d2 Record approved recovery remediation decisions 2026-11-02 22:13:04 +00:00
957e75524c Record publication recovery algorithm findings 2026-11-02 21:13:44 +00:00
0ef135bfda Record publication recovery integration findings 2026-11-02 20:53:01 +00:00
3280f734ef Record publication recovery review findings 2026-11-02 20:24:44 +00:00
599ad81bec Finish publication recovery workflow 2026-11-02 19:37:29 +00:00
6915a86132 Add publication recovery handoff to CLI 2026-11-02 19:22:23 +00:00
4afdd9b826 Add CLI publication recovery commands 2026-11-02 19:17:42 +00:00
fb5947ea3a Add local publication attempt discovery 2026-11-02 19:09:26 +00:00
2a04938a96 Record publication evidence before tag pushes 2026-11-02 19:08:07 +00:00
b11c6d1788 Expose publication recovery facade 2026-11-02 19:03:24 +00:00
1ddeb2c6dc Add private publication attempt records 2026-11-02 19:00:51 +00:00
4dff8086ab Extract publication recovery observation 2026-11-02 18:58:48 +00:00
447b42a1cd Plan publication reconciliation implementation 2026-11-02 18:24:44 +00:00
58656dea45 Clarify recovery transport settings and partial discovery 2026-11-02 17:57:05 +00:00
58c20fa863 Add recovery ergonomics to reconciliation roadmap 2026-11-02 17:43:27 +00:00
f73f0c1b6a Clarify publication recording and recovery selection 2026-11-02 17:40:38 +00:00
bff4ed8a8b Resolve publication reconciliation roadmap decisions 2026-11-02 17:17:23 +00:00
e0bf5ca57a Plan read-only publication reconciliation 2026-11-02 16:50:16 +00:00
691926d839 Run consumer release commands through Go tools 2026-11-02 14:46:42 +00:00
6fab30337a Prepare v0.7.0 notes and retire completed roadmaps 2026-11-02 13:54:16 +00:00
e736166a39 Hide credentials in checkout preparation errors 2026-11-02 11:45:42 +00:00
a2d75c462c Preserve child working directory in environment overlays 2026-11-02 11:36:40 +00:00
31f9e48219 Redact quoted credentials in Git diagnostics 2026-11-02 11:32:11 +00:00
473670185c Record release workflow integration gaps 2026-11-02 04:06:35 +00:00
c8fa165dc9 Record the implementation review finding 2026-11-02 03:53:36 +00:00
2f95753d9c Verify the audit remediation changes 2026-11-02 03:41:01 +00:00
9dc87ae996 Record deferred resource assessments 2026-11-02 03:36:53 +00:00
d9c97fd915 Remove unused helpers and incidental assertions 2026-11-02 03:34:59 +00:00
1d40fb7ac0 Extract check and build command workflows 2026-11-02 03:34:06 +00:00
03ee83e8a5 Separate validation commands from tree checks 2026-11-02 03:32:46 +00:00
9cb48a70b7 Bound retained Go command diagnostics 2026-11-02 03:31:59 +00:00
2b23574ece Bound remote asset content verification 2026-11-02 03:29:59 +00:00
76676ee5a6 Limit release asset redirects 2026-11-02 03:28:24 +00:00
23b3a3d340 Preserve delivery outcomes when cleanup fails 2026-11-02 03:27:13 +00:00
ef47356541 Report temporary metadata cleanup failures 2026-11-02 03:24:57 +00:00
0666b68ff6 Share artifact declaration validation 2026-11-02 03:23:15 +00:00
6f2e62bea3 Report only fully hashed build artifacts 2026-11-02 03:22:07 +00:00
aa57fee4de Preserve evidence when local tag inspection fails 2026-11-02 03:20:13 +00:00
92c95ef031 Hide credentials in Git endpoint diagnostics 2026-11-02 03:19:16 +00:00
595745c7b1 Close piped processes on cancellation 2026-11-02 03:16:36 +00:00
9c02ed769b Bound subprocess output teardown 2026-11-02 03:14:59 +00:00
94aedacf05 Verify releases use original Git objects 2026-11-02 03:14:01 +00:00
7e6e0cc7d1 Observe original Git objects consistently 2026-11-02 03:12:05 +00:00
aecab00ff6 Ensure tag pushes ignore submodule push settings 2026-11-02 03:08:58 +00:00
a1dc705be7 Plan the audit remediation sprint 2026-11-02 03:00:05 +00:00
b5b3f09599 Record accepted audit remediation decisions 2026-11-02 02:23:58 +00:00
6f7e43b097 Consolidate audit findings and remediation priorities 2026-11-02 02:16:40 +00:00
91f25c452c Record dead code audit findings 2026-11-02 01:47:21 +00:00
083bc83331 Record shared behavior audit findings 2026-11-02 01:45:54 +00:00
5e6db4de76 Record interface contract audit finding 2026-11-02 01:44:55 +00:00
b345bc0ec4 Record test coverage audit findings 2026-11-02 01:43:27 +00:00
3d7a691338 Record error handling audit finding 2026-11-02 01:41:31 +00:00
3754242969 Record resource management audit findings 2026-11-02 01:40:06 +00:00
9545bb0bfc Record complexity audit findings 2026-11-02 01:39:06 +00:00
620c832477 Record efficiency audit findings 2026-11-02 01:38:01 +00:00
812c24de9e Record security audit findings 2026-11-02 01:27:24 +00:00
1b39e71e81 Record concurrency audit findings 2026-11-02 01:16:22 +00:00
d884ad731d Record functional correctness audit findings 2026-11-02 01:07:48 +00:00
dd0a557ad3 Document local release page delivery after publication 2026-11-01 23:41:51 +00:00
b633ee8b4c Prepare v0.6.0 release notes and retire completed plans 2026-11-01 23:32:57 +00:00
fcd2e57887 Synchronize deadline regression with source inspection 2026-11-01 21:56:13 +00:00
66f5884ab4 Preserve discovery failures for damaged checkouts 2026-11-01 21:53:40 +00:00
5d5653bfc3 Clarify ReleaseKit ownership of remediation work 2026-11-01 21:52:51 +00:00
1ad6ddc198 Record remaining implementation review issues 2026-11-01 21:42:04 +00:00
67963102d9 Complete audit remediation and verification 2026-11-01 21:18:07 +00:00
d368bb32f9 Clarify page-only delivery and artifact verification 2026-11-01 21:15:28 +00:00
9fa440726e Classify missing release IDs when accessing assets 2026-11-01 21:15:08 +00:00
28a4144b49 Preserve cancellation during build source inspection 2026-11-01 21:14:34 +00:00
b91a0d1914 Validate derived candidate tags before checks 2026-11-01 21:13:54 +00:00
abbab3c8ce Verify preparation selects the intended module graph 2026-11-01 21:13:04 +00:00
05f1b472fc Use selected module for dependency downloads 2026-11-01 21:12:22 +00:00
5aba4c6c87 Anchor dependency preparation to checkout root 2026-11-01 21:12:05 +00:00
b47202a2e9 Discover checkout roots for optional preparation 2026-11-01 21:11:39 +00:00
0632aa5901 Treat incomplete remote tag observations as uncertain 2026-11-01 21:11:06 +00:00
730e6380c8 Write the staged audit remediation plan 2026-11-01 21:08:40 +00:00
59bb0745e7 Align preparation roadmap with automatic checkout root resolution 2026-11-01 20:56:15 +00:00
303385a5ee Plan remediation of correctness and interface audit findings 2026-11-01 20:47:53 +00:00
899e7f1bfc Record functional correctness audit findings 2026-11-01 20:38:53 +00:00
31f5327255 Record API and interface contract audit findings 2026-11-01 20:25:21 +00:00
3f00ad2754 Remove completed release delivery plans and audit records 2026-11-01 19:37:40 +00:00
e42cad7b1a Preserve asset inspection error causes through delivery 2026-11-01 19:33:44 +00:00
eb61b40f08 Sort only missing release assets once 2026-11-01 19:29:50 +00:00
b72af69baf Make pending asset bookkeeping linear 2026-11-01 19:29:17 +00:00
078db6cbcb Validate CI module tags before delivery preparation 2026-11-01 19:27:56 +00:00
9376bafaa2 Align completed forge roadmap status records 2026-11-01 19:26:52 +00:00
6bed1cd691 Clarify delivery exit statuses by failure phase 2026-11-01 19:26:30 +00:00
7b5c1285a2 Exclude forge contracts from runtime dependencies 2026-11-01 19:25:15 +00:00
e5512d50b0 Classify invalid delivery destinations during preflight 2026-11-01 19:24:52 +00:00
627d524aa2 Record algorithmic delivery audit findings 2026-11-01 19:22:04 +00:00
370fe3a9f5 Record delivery integration audit findings 2026-11-01 19:11:51 +00:00
72de18744b Record forge delivery review findings 2026-11-01 18:51:43 +00:00
cbdba90014 Document neutral forge delivery and preflight 2026-11-01 18:38:03 +00:00
c3f6eeb6df Complete forge delivery regression coverage 2026-11-01 18:30:52 +00:00
2e617db23c Connect neutral delivery to the Gitea CLI 2026-11-01 18:20:01 +00:00
b350c71246 Move asset reconciliation into shared delivery 2026-11-01 18:07:55 +00:00
88a79c3561 Move release page recovery into shared delivery 2026-11-01 18:04:30 +00:00
ddac9e3c73 Return write evidence from Gitea operations 2026-11-01 18:02:05 +00:00
02bd120aed Preflight Gitea credentials with repository reads 2026-11-01 17:59:43 +00:00
201af83d95 Add Gitea read operations to the forge boundary 2026-11-01 17:57:57 +00:00
61a07bc950 Move asset verification into the artifact package 2026-11-01 17:55:53 +00:00
aa03a78476 Define the internal forge delivery contract 2026-11-01 17:52:38 +00:00
9d6952a772 Plan credential preflight for forge delivery 2026-11-01 17:44:47 +00:00
44823ce323 Plan the neutral forge delivery refactor 2026-11-01 16:37:50 +00:00
71746f437e Require explicit forge selection in the neutral destination plan 2026-11-01 16:25:54 +00:00
2700bd18cb Plan the internal forge delivery boundary 2026-11-01 16:23:58 +00:00
ac78e7db73 Rename the candidate file validator to forbidden files 2026-11-01 16:02:51 +00:00
792bfc4eca Read delivery tokens from files and check selected paths before release 2026-11-01 15:39:36 +00:00
6650b639e1 Prepare v0.5.0 with the current Go toolchain and retire the migration roadmap 2026-11-01 14:44:40 +00:00
a1cac0898e Record completion and verification of the module migration 2026-11-01 14:41:36 +00:00
3b803d558b Migrate ReleaseKit to the vanity module path and new Gitea host 2026-11-01 14:37:41 +00:00
56a86d6d49 Clarify the Gitea hostname migration in the roadmap 2026-11-01 14:28:10 +00:00
f97edeb830 Plan the ReleaseKit vanity module migration 2026-11-01 14:24:43 +00:00
249 changed files with 24401 additions and 3294 deletions

View File

@@ -2,15 +2,20 @@
ReleaseKit is an opinionated Go library and executable for a shared release ReleaseKit is an opinionated Go library and executable for a shared release
process. The Go module, root `releasekit` facade, `buildinfo` runtime package, process. The Go module, root `releasekit` facade, `buildinfo` runtime package,
local candidate check, source-tag publication API, selected-target build API, local candidate check, source-tag publication, selected-target build, tagged
tagged-source delivery API, and the `version`, `check`, `publish`, `build`, delivery, readiness, and rehearsal APIs and commands are implemented. ReleaseKit's source-only
`deliver`, and `ci-deliver` commands are implemented. ReleaseKit's source-only
maintainer procedure and prepared Woodpecker workflow for hosted note-page maintainer procedure and prepared Woodpecker workflow for hosted note-page
delivery are documented. ReleaseKit does not declare binary deliverables. delivery are documented. ReleaseKit does not declare binary deliverables.
Release operations can select one Go module within a repository. The repository The Go module is `go.maximumdirect.net/releasekit`. The
root remains the default; a selected module's declared import path and physical [adoption guide](docs/consumers/adoption.md#migrating-from-the-original-module-path)
directory determine its complete Git tag and module-local release note. See the explains the v0.5.0 migration from the original Gitea module path.
The [v0.6.0 release note](docs/releases/v0.6.0.md) describes the delivery API
and profile migration.
Release operations can select a Go module or a general source directory within a
repository. The repository root remains the default; the selected publication
mode determines the complete Git tag and release-note location. See the
[candidate check](docs/consumers/check.md), [candidate check](docs/consumers/check.md),
[publication](docs/consumers/publish.md), and [publication](docs/consumers/publish.md), and
[multi-module example](examples/multi-module/). [multi-module example](examples/multi-module/).
@@ -25,15 +30,16 @@ Run the offline Go test suite from the repository root with:
go test ./... go test ./...
``` ```
The version command prints ReleaseKit's version: The version command prints ReleaseKit's version. For the `go run` examples
below, [select the Go host target](docs/consumers/adoption.md#select-the-go-host-target)
if your shell is set to cross-compile.
```sh ```sh
go run ./cmd/releasekit version go run ./cmd/releasekit version
``` ```
The local candidate check validates a committed release note, runs the standard The local candidate check validates a committed release note, runs the standard
offline Go suite with any selected shared validation checks, and then runs offline Go suite when Go is selected, and runs selected shared and product checks:
configured product checks:
```sh ```sh
go run ./cmd/releasekit check v1.2.3 go run ./cmd/releasekit check v1.2.3
@@ -54,8 +60,8 @@ failure recovery.
dependencies, upgrades, and CI adoption. dependencies, upgrades, and CI adoption.
- [Contributor guide](docs/development.md): orientation, validation, and selective - [Contributor guide](docs/development.md): orientation, validation, and selective
policy reading. policy reading.
- [CLI contract](docs/cli.md): the `version`, `check`, `publish`, `build`, - [CLI contract](docs/cli.md): candidate, publication, delivery, readiness,
`deliver`, and `ci-deliver` commands. rehearsal, and recovery commands.
- [Configuration](docs/config.md): profile fields and child-command settings. - [Configuration](docs/config.md): profile fields and child-command settings.
- [Runtime version guidance](docs/consumers/runtime-version.md): how applications - [Runtime version guidance](docs/consumers/runtime-version.md): how applications
read their embedded version through `buildinfo`. read their embedded version through `buildinfo`.
@@ -63,6 +69,9 @@ failure recovery.
injected application version. injected application version.
- [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and - [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and
report hosted page and asset status. report hosted page and asset status.
- [Readiness guidance](docs/consumers/readiness.md) and
[rehearsal guidance](docs/consumers/rehearsal.md): inspect setup and exercise
the tagged delivery workflow with temporary resources.
- [Gitea integration](docs/integrations/gitea.md): hosted release-page - [Gitea integration](docs/integrations/gitea.md): hosted release-page
operations and their failure behavior. operations and their failure behavior.
- [Candidate check guidance](docs/consumers/check.md): local candidate validation - [Candidate check guidance](docs/consumers/check.md): local candidate validation
@@ -75,6 +84,8 @@ failure recovery.
components and their responsibilities. components and their responsibilities.
- [Architecture policy](docs/policy/architecture.md): responsibility and dependency - [Architecture policy](docs/policy/architecture.md): responsibility and dependency
boundaries for development. boundaries for development.
- [ADR 0006](docs/adr/0006-neutral-forge-delivery-and-preflight.md): neutral
delivery policy and credential preflight.
- [ADR 0001](docs/adr/0001-public-facade.md): the accepted public facade decision. - [ADR 0001](docs/adr/0001-public-facade.md): the accepted public facade decision.
- [Policy provenance](docs/policy/meta.md): adopted policy sources and update - [Policy provenance](docs/policy/meta.md): adopted policy sources and update
guidance. guidance.

View File

@@ -2,14 +2,15 @@ package releasekit
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact" "go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" internalbuild "go.maximumdirect.net/releasekit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git" "go.maximumdirect.net/releasekit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/releaseidentity"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/versioncontract"
) )
// Target identifies one explicit Go operating-system and architecture pair. // Target identifies one explicit Go operating-system and architecture pair.
@@ -31,7 +32,10 @@ type BuildRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects // ModuleDir selects a repository-relative module directory; empty selects
// the repository root. // the repository root.
ModuleDir string ModuleDir string
Version string // stable vMAJOR.MINOR.PATCH value injected at link time. // Source selects explicit source and publication capabilities. Nil retains
// the ModuleDir Go-module shorthand.
Source *SourceSpec
Version string // selected production identifier injected at link time.
Spec BuildSpec // application package, artifact name, and targets. Spec BuildSpec // application package, artifact name, and targets.
OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist. OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist.
Output io.Writer // optional build progress destination. Output io.Writer // optional build progress destination.
@@ -47,11 +51,19 @@ type BuildArtifact struct {
// BuildResult describes the source and artifacts reached by Build. // BuildResult describes the source and artifacts reached by Build.
type BuildResult struct { type BuildResult struct {
RepositoryDir string // absolute source repository path. RepositoryDir string // absolute source repository path.
ModuleDir string // absolute selected module directory. SourceDir string // absolute selected source directory.
ModulePath string // selected module's declared Go path. SourceSubdir string // repository-relative selected source directory.
Tag string // complete tag derived for this version. GoEnabled bool // whether Go capability was selected.
CandidateCommit string // Git HEAD observed when the build started. Publication PublicationMode // selected publication mode.
VersionFormat VersionFormat // selected production identifier format.
VersionPrefix string // selected production identifier prefix.
IdentityKind string // production or diagnostic identity kind.
NotePath string // repository-relative production note path, when applicable.
ModuleDir string // absolute selected module directory.
ModulePath string // selected module's declared Go path.
Tag string // complete tag derived for this version.
CandidateCommit string // Git HEAD observed when the build started.
// SourceVerified reports clean source and the same HEAD observed before and // SourceVerified reports clean source and the same HEAD observed before and
// after a completed build. It is required for binary delivery, not an attestation. // after a completed build. It is required for binary delivery, not an attestation.
SourceVerified bool SourceVerified bool
@@ -79,7 +91,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets) result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
return publicBuildResult(result), err return publicBuildResult(result), err
} }
if !versioncontract.ValidStableVersion(request.Version) { if request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)) return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
} }
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir) repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
@@ -87,9 +99,13 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
return failure(err) return failure(err)
} }
result.RepositoryDir = repositoryDir result.RepositoryDir = repositoryDir
identity, err := releaseidentity.FromWorkingTree(ctx, repositoryDir, request.ModuleDir, request.Version) identity, err := releaseidentity.FromWorkingSource(ctx, repositoryDir, request.ModuleDir, request.Version, internalSourceSpec(request.Source))
result.Identity = identity
result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag
if err != nil { if err != nil {
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
}
return failure(err) return failure(err)
} }
result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{ result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{
@@ -104,6 +120,14 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
func publicBuildResult(result internalbuild.Result) BuildResult { func publicBuildResult(result internalbuild.Result) BuildResult {
public := BuildResult{ public := BuildResult{
RepositoryDir: result.RepositoryDir, RepositoryDir: result.RepositoryDir,
SourceDir: result.Identity.SourceDir,
SourceSubdir: result.Identity.SourceSubdir,
GoEnabled: result.Identity.GoEnabled,
Publication: PublicationMode(result.Identity.Publication),
VersionFormat: VersionFormat(result.Identity.VersionFormat),
VersionPrefix: result.Identity.VersionPrefix,
IdentityKind: result.Identity.Kind,
NotePath: result.Identity.NotePath,
ModuleDir: result.ModuleDir, ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath, ModulePath: result.ModulePath,
Tag: result.Tag, Tag: result.Tag,
@@ -145,10 +169,8 @@ func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
func internalBuildResult(result BuildResult) *internalbuild.Result { func internalBuildResult(result BuildResult) *internalbuild.Result {
input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets}) input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets) settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, MainPackage: settings.MainPackage, BinaryName: settings.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler} converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, OutputDir: result.OutputDir, Compiler: result.Compiler}
for _, target := range settings.Targets { converted.Identity = releaseidentity.Identity{Kind: result.IdentityKind, SourceDir: result.SourceDir, SourceSubdir: result.SourceSubdir, GoEnabled: result.GoEnabled, Publication: string(result.Publication), VersionFormat: string(result.VersionFormat), VersionPrefix: result.VersionPrefix, NotePath: result.NotePath}
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
}
for _, artifact := range result.Artifacts { for _, artifact := range result.Artifacts {
converted.Artifacts = append(converted.Artifacts, internalbuild.Artifact{Path: artifact.Path, Filename: artifact.Filename, Target: internalbuild.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256}) converted.Artifacts = append(converted.Artifacts, internalbuild.Artifact{Path: artifact.Path, Filename: artifact.Filename, Target: internalbuild.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256})
} }

View File

@@ -0,0 +1,150 @@
package releasekit_test
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
releasekit "go.maximumdirect.net/releasekit"
)
// inspectionDeadlineContext models deadline expiration at the readiness signal,
// so unrelated setup time cannot consume the source-inspection test's deadline.
type inspectionDeadlineContext struct{ context.Context }
func (ctx inspectionDeadlineContext) Err() error {
return context.Cause(ctx.Context)
}
func TestBuildSourceInspectionCancellation(t *testing.T) {
const source = `package main
import("fmt";"os";"go.maximumdirect.net/releasekit/buildinfo")
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
`
for _, tc := range []struct {
name string
status int
deadline bool
binary bool
}{
{"initial", 1, false, false}, {"deadline", 1, true, false}, {"final", 2, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
repo := newBuildConsumer(t, source)
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
count := filepath.Join(t.TempDir(), "count")
ready := filepath.Join(t.TempDir(), "ready")
script := `#!/bin/sh
for arg in "$@"; do
if [ "$arg" = status ]; then
count=0
if [ -f "$INSPECT_COUNT" ]; then count=$(/bin/cat "$INSPECT_COUNT"); fi
count=$((count+1)); printf '%s' "$count" > "$INSPECT_COUNT"
if [ "$count" = "$INSPECT_BLOCK" ]; then : > "$INSPECT_READY"; exec /bin/sleep 60; fi
fi
done
exec "$INSPECT_GIT" "$@"
`
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("INSPECT_GIT", realGit)
t.Setenv("INSPECT_COUNT", count)
t.Setenv("INSPECT_READY", ready)
t.Setenv("INSPECT_BLOCK", fmt.Sprint(tc.status))
var ctx context.Context
var cancel context.CancelFunc
if tc.deadline {
parent, expire := context.WithCancelCause(context.Background())
ctx = inspectionDeadlineContext{parent}
cancel = func() { expire(context.DeadlineExceeded) }
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel()
request := releasekit.BuildRequest{RepositoryDir: repo, Version: "v1.2.3", OutputDir: t.TempDir()}
if tc.binary {
request.Spec = releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}
}
type outcome struct {
result releasekit.BuildResult
err error
}
done := make(chan outcome, 1)
go func() { result, err := releasekit.Build(ctx, request); done <- outcome{result, err} }()
timer := time.NewTimer(45 * time.Second)
defer timer.Stop()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
waiting := true
for waiting {
if _, err := os.Stat(ready); err == nil {
waiting = false
break
}
select {
case result := <-done:
t.Fatalf("build ended before inspection: %#v, %v", result.result, result.err)
case <-timer.C:
cancel()
result := <-done
t.Fatalf("inspection did not start: %#v, %v", result.result, result.err)
case <-ticker.C:
}
}
cancel()
var result outcome
select {
case result = <-done:
case <-timer.C:
t.Fatal("build did not stop after source inspection interruption")
}
want := context.Canceled
if tc.deadline {
want = context.DeadlineExceeded
}
if !errors.Is(result.err, want) || result.result.SourceVerified {
t.Fatalf("result = %#v, error = %v", result.result, result.err)
}
if tc.binary {
if len(result.result.Artifacts) != 1 || result.result.Artifacts[0].SHA256 == "" {
t.Fatalf("completed artifact missing: %#v", result.result.Artifacts)
}
if _, err := os.Stat(result.result.Artifacts[0].Path); err != nil {
t.Fatal(err)
}
}
})
}
}
func TestBuildSourceInspectionPreservesGitFailure(t *testing.T) {
repo := newBuildConsumer(t, "package main\nfunc main() {}\n")
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
script := "#!/bin/sh\nfor arg do if [ \"$arg\" = status ]; then exit 37; fi; done\nexec \"$INSPECT_GIT\" \"$@\"\n"
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("INSPECT_GIT", realGit)
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{RepositoryDir: repo, Version: "v1.2.3"})
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 37 || result.SourceVerified {
t.Fatalf("result = %#v, error = %v", result, err)
}
}

View File

@@ -15,9 +15,44 @@ import (
"testing" "testing"
"time" "time"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit" releasekit "go.maximumdirect.net/releasekit"
) )
func TestBuildReplacementDerivedSourceIsNotEligibleForDelivery(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
original := buildGit(t, repository, "rev-parse", "HEAD")
mainPath := filepath.Join(repository, "cmd/app/main.go")
main, err := os.ReadFile(mainPath)
if err != nil {
t.Fatal(err)
}
writeBuildFixture(t, repository, "cmd/app/main.go", string(main)+"\n// replacement source\n")
buildGit(t, repository, "add", "cmd/app/main.go")
buildGit(t, repository, "commit", "-m", "Replacement source")
replacement := buildGit(t, repository, "rev-parse", "HEAD")
buildGit(t, repository, "reset", "--hard", original)
buildGit(t, repository, "replace", original, replacement)
buildGit(t, repository, "reset", "--hard", original)
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
})
if err != nil || result.SourceVerified || len(result.Artifacts) != 1 || result.CandidateCommit != original {
t.Fatalf("replacement build = %#v, error = %v", result, err)
}
buildGit(t, repository, "replace", "-d", original)
buildGit(t, repository, "reset", "--hard", original)
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
delivery, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &result,
})
if err == nil || delivery.State != releasekit.DeliveryNotAttempted || remote.snapshot().writes != 0 {
t.Fatalf("delivery of replacement build = %#v, error = %v", delivery, err)
}
}
func TestBuildPreservesInvalidVersionAndDeclarationFailureEvidence(t *testing.T) { func TestBuildPreservesInvalidVersionAndDeclarationFailureEvidence(t *testing.T) {
spec := releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "widget", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "amd64"}}} spec := releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "widget", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "amd64"}}}
invalid, err := releasekit.Build(context.Background(), releasekit.BuildRequest{ invalid, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
@@ -48,7 +83,7 @@ import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {
@@ -127,7 +162,7 @@ func TestBuildUsesGoHostDespiteAmbientTargetEnvironment(t *testing.T) {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {
@@ -159,7 +194,7 @@ func TestBuildIgnoresAmbientAndPersistentArchitectureTuning(t *testing.T) {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } } func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
`) `)
@@ -272,7 +307,7 @@ func TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput(t *testing.T) {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {
if len(os.Args) == 2 && os.Args[1] == "version" { if len(os.Args) == 2 && os.Args[1] == "version" {
@@ -406,7 +441,7 @@ func TestBuildResolvesDirtyWorkingTreeDeclaration(t *testing.T) {
func TestBuildRegeneratesOwnedOutputsAndPreservesUnrelatedFiles(t *testing.T) { func TestBuildRegeneratesOwnedOutputsAndPreservesUnrelatedFiles(t *testing.T) {
const source = `package main const source = `package main
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo") import("fmt";"go.maximumdirect.net/releasekit/buildinfo")
func main(){fmt.Println("fixture",buildinfo.Version())} func main(){fmt.Println("fixture",buildinfo.Version())}
` `
repository := newBuildConsumer(t, source) repository := newBuildConsumer(t, source)
@@ -486,6 +521,61 @@ func TestBuildReportsMissingMainPackage(t *testing.T) {
} }
} }
func TestBuildRetainsOnlyHashedArtifactsAfterReadFailure(t *testing.T) {
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
realGo, err := exec.LookPath("go")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
count := filepath.Join(t.TempDir(), "count")
script := `#!/bin/sh
if [ "$1" != build ]; then exec "$RELEASEKIT_REAL_GO" "$@"; fi
output=
previous=
for arg in "$@"; do
if [ "$previous" = -o ]; then output=$arg; fi
previous=$arg
done
"$RELEASEKIT_REAL_GO" "$@" || exit $?
if [ -f "$RELEASEKIT_BUILD_COUNT" ]; then
rm "$output"
mkdir "$output"
else
: > "$RELEASEKIT_BUILD_COUNT"
fi
`
if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("RELEASEKIT_REAL_GO", realGo)
t.Setenv("RELEASEKIT_BUILD_COUNT", count)
secondArch := "arm64"
if runtime.GOARCH == secondArch {
secondArch = "amd64"
}
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}, {OS: runtime.GOOS, Arch: secondArch}}},
})
var pathErr *os.PathError
if !errors.As(err, &pathErr) || !strings.Contains(err.Error(), "hash build output") || len(result.Artifacts) != 1 || len(result.Targets) != 2 || result.MainPackage != "./cmd/app" || result.BinaryName != "fixture" || result.CandidateCommit == "" || result.SourceVerified {
t.Fatalf("partial build = %#v, error = %v", result, err)
}
contents, readErr := os.ReadFile(result.Artifacts[0].Path)
if readErr != nil {
t.Fatal(readErr)
}
digest := sha256.Sum256(contents)
if result.Artifacts[0].SHA256 != hex.EncodeToString(digest[:]) {
t.Fatalf("completed artifact digest = %q", result.Artifacts[0].SHA256)
}
if info, statErr := os.Stat(pathErr.Path); statErr != nil || !info.IsDir() {
t.Fatalf("failed output was not retained: %v", statErr)
}
}
func TestBuildReportsIncorrectVersionOutputAndRetainsBinary(t *testing.T) { func TestBuildReportsIncorrectVersionOutputAndRetainsBinary(t *testing.T) {
repository := newBuildConsumer(t, `package main repository := newBuildConsumer(t, `package main
import ( import (
@@ -616,7 +706,7 @@ func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } } func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
`) `)
@@ -713,7 +803,7 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
writeBuildFixture(t, repository, "go.mod", module) writeBuildFixture(t, repository, "go.mod", module)
writeBuildFixture(t, repository, "cmd/app/main.go", mainSource) writeBuildFixture(t, repository, "cmd/app/main.go", mainSource)
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n") writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
@@ -731,7 +821,7 @@ func writeNestedBuildConsumer(t *testing.T, repository, moduleDir, modulePath, m
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module %s\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", modulePath, filepath.ToSlash(root)) module := fmt.Sprintf("module %s\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", modulePath, filepath.ToSlash(root))
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "go.mod")), module) writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "go.mod")), module)
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "cmd/app/main.go")), mainSource) writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "cmd/app/main.go")), mainSource)
return filepath.Join(repository, filepath.FromSlash(moduleDir)) return filepath.Join(repository, filepath.FromSlash(moduleDir))
@@ -743,7 +833,7 @@ func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
writeFile(t, repository, "go.mod", module) writeFile(t, repository, "go.mod", module)
writeFile(t, repository, ".gitignore", "dist/\n") writeFile(t, repository, ".gitignore", "dist/\n")
writeFile(t, repository, "cmd/app/main.go", mainSource) writeFile(t, repository, "cmd/app/main.go", mainSource)
@@ -777,7 +867,7 @@ func buildGit(t *testing.T, directory string, args ...string) string {
func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) { func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) {
const source = `package main const source = `package main
import("fmt";"os";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo") import("fmt";"os";"go.maximumdirect.net/releasekit/buildinfo")
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} } func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
` `
for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} { for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} {
@@ -815,7 +905,7 @@ func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",b
} }
buildGit(t, repository, "restore", "cmd/app/main.go") buildGit(t, repository, "restore", "cmd/app/main.go")
buildGit(t, repository, "checkout", "--detach", "v1.2.3") buildGit(t, repository, "checkout", "--detach", "v1.2.3")
delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Prebuilt: &result}) delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea}, Prebuilt: &result})
if err == nil || !strings.Contains(err.Error(), "build source") || delivered.State != releasekit.DeliveryNotAttempted { if err == nil || !strings.Contains(err.Error(), "build source") || delivered.State != releasekit.DeliveryNotAttempted {
t.Fatalf("dirty source delivered: %#v %v", delivered, err) t.Fatalf("dirty source delivered: %#v %v", delivered, err)
} }
@@ -838,7 +928,7 @@ func TestCandidateBuildDoesNotRequireWritableRepositoryParent(t *testing.T) {
t.Skip("requires ordinary Unix permission checks") t.Skip("requires ordinary Unix permission checks")
} }
repository := newBuildConsumer(t, `package main repository := newBuildConsumer(t, `package main
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo") import("fmt";"go.maximumdirect.net/releasekit/buildinfo")
func main(){fmt.Println("fixture",buildinfo.Version())} func main(){fmt.Println("fixture",buildinfo.Version())}
`) `)
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n") writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")

View File

@@ -2,7 +2,7 @@
// built with ReleaseKit. // built with ReleaseKit.
package buildinfo package buildinfo
import "gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo" import "go.maximumdirect.net/releasekit/internal/runtimeinfo"
// Version returns the injected release identifier when available. Otherwise, // Version returns the injected release identifier when available. Otherwise,
// it returns the executable's main module version, or "dev" when that metadata // it returns the executable's main module version, or "dev" when that metadata

View File

@@ -7,7 +7,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/versioncontract"
) )
func TestVersionInConsumerExecutable(t *testing.T) { func TestVersionInConsumerExecutable(t *testing.T) {
@@ -19,11 +19,11 @@ func TestVersionInConsumerExecutable(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
module := fmt.Sprintf(`module example.com/versionfixture module := fmt.Sprintf(`module example.com/versionfixture
go 1.26.0 go 1.27.0
require gitea.maximumdirect.net/eric/ReleaseKit v0.0.0 require go.maximumdirect.net/releasekit v0.0.0
replace gitea.maximumdirect.net/eric/ReleaseKit => %s replace go.maximumdirect.net/releasekit => %s
`, filepath.ToSlash(repo)) `, filepath.ToSlash(repo))
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil { if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -32,7 +32,7 @@ replace gitea.maximumdirect.net/eric/ReleaseKit => %s
import ( import (
"fmt" "fmt"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { fmt.Print(buildinfo.Version()) } func main() { fmt.Print(buildinfo.Version()) }

112
check.go
View File

@@ -4,13 +4,13 @@ import (
"context" "context"
"io" "io"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" internalbuild "go.maximumdirect.net/releasekit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate" "go.maximumdirect.net/releasekit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish" "go.maximumdirect.net/releasekit/internal/publish"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation" "go.maximumdirect.net/releasekit/internal/validation"
) )
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH. // ErrInvalidVersion reports an identifier that does not match its selected format.
var ErrInvalidVersion = candidate.ErrInvalidVersion var ErrInvalidVersion = candidate.ErrInvalidVersion
// ErrUnexpectedPushURL reports that the effective publication push URL does // ErrUnexpectedPushURL reports that the effective publication push URL does
@@ -18,15 +18,22 @@ var ErrInvalidVersion = candidate.ErrInvalidVersion
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
// Candidate identifies one committed local source revision selected for // Candidate identifies one committed local source revision selected for
// validation. ModuleDir is the absolute selected module directory, ModulePath // validation. SourceDir is the absolute selected source directory. ModuleDir
// is its declared Go import path, and Tag is the complete derived Git tag. // and ModulePath identify a selected Go module and are empty for source-only
// releases. Tag is the complete derived Git tag.
type Candidate struct { type Candidate struct {
RepositoryDir string RepositoryDir string
SourceDir string
SourceSubdir string
GoEnabled bool
Publication PublicationMode
VersionFormat VersionFormat
VersionPrefix string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
Tag string Tag string
Commit string Commit string
Version string // selected stable semantic version. Version string // selected production identifier.
} }
// ReleaseRequest contains the inputs used to validate and optionally build one // ReleaseRequest contains the inputs used to validate and optionally build one
@@ -39,13 +46,21 @@ type ReleaseRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects // ModuleDir selects a repository-relative module directory; empty selects
// the repository root. // the repository root.
ModuleDir string ModuleDir string
Product string // Source selects explicit source and publication capabilities. Nil retains
Version string // stable semantic version, independent of the derived Git tag. // the ModuleDir Go-module shorthand.
Remote string Source *SourceSpec
Product string
Version string // production identifier, independent of the derived Git tag.
Remote string
// ExpectedPushURL optionally requires Publish's resolved push URL to match // ExpectedPushURL optionally requires Publish's resolved push URL to match
// this string exactly before validation or tag creation. Check ignores this // this string exactly before validation or tag creation. Check ignores this
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL. // publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
ExpectedPushURL string ExpectedPushURL string
// PublicationRecordDir optionally overrides Publish's private attempt-record
// directory. Relative paths are resolved from the source repository root;
// Check ignores this publication-only setting. Recording failure is returned
// separately on PublicationResult and does not change publication status.
PublicationRecordDir string
// Validation selects optional checks run against the captured candidate. // Validation selects optional checks run against the captured candidate.
Validation ValidationSpec Validation ValidationSpec
// AdditionalChecks optionally runs product checks after shared validation. // AdditionalChecks optionally runs product checks after shared validation.
@@ -59,6 +74,8 @@ type ReleaseRequest struct {
// module and shared-file inputs. Independent nested modules form automatic // module and shared-file inputs. Independent nested modules form automatic
// input boundaries; vendored files remain included. Referenced destinations // input boundaries; vendored files remain included. Referenced destinations
// remain available for targeted inspection without expanding the input set. // remain available for targeted inspection without expanding the input set.
// ForbiddenFiles checks explicitly selected repository paths independently of
// those file inputs.
type ValidationSpec struct { type ValidationSpec struct {
// SharedFiles adds repository-relative committed files to optional file // SharedFiles adds repository-relative committed files to optional file
// checks. Nil selects the optional root COPYRIGHT, LICENSE, and // checks. Nil selects the optional root COPYRIGHT, LICENSE, and
@@ -66,7 +83,11 @@ type ValidationSpec struct {
// Explicit files replace the defaults and must exist even when file checks // Explicit files replace the defaults and must exist even when file checks
// are off. // are off.
SharedFiles []string SharedFiles []string
Go GoValidationSpec // ForbiddenFiles lists literal repository-relative file paths that must be
// absent from the captured commit, independently of module/shared inputs.
// An empty list disables the check. File contents and history are not read.
ForbiddenFiles []string
Go GoValidationSpec
// GoFormat checks the formatting of committed regular Go source files. It // GoFormat checks the formatting of committed regular Go source files. It
// does not modify repository contents and is disabled when false. // does not modify repository contents and is disabled when false.
GoFormat bool GoFormat bool
@@ -126,17 +147,17 @@ type GoValidationSpec struct {
} }
// Check validates one local, committed release candidate. It requires a clean // Check validates one local, committed release candidate. It requires a clean
// worktree and index on main, a selected module declaration and module-local // worktree and index on main, a committed source-local note matching Product
// committed note matching Product and Version, and an unused local tag. An // and Version, and an unused local tag. A Go selection also requires a module
// empty ModuleDir selects the repository root. The module declaration // declaration. Nil Source retains the ModuleDir Go-module shorthand. Check
// determines the full Git tag for the semantic Version. It always runs the // runs the offline Go test suite when Go is enabled, then calls
// offline Go test suite with the available compatible local Go toolchain and
// Go host target, then calls
// AdditionalChecks when supplied. Validation.Go.Race runs that one suite with // AdditionalChecks when supplied. Validation.Go.Race runs that one suite with
// the race detector, Validation.Go.FullVet runs go vet after the suite instead // the race detector, Validation.Go.FullVet runs go vet after the suite instead
// of test-time vet, and Validation.Go.CompileTargets compiles all packages for // of test-time vet, and Validation.Go.CompileTargets compiles all packages for
// each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package // each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package
// compilation produces no artifacts and does not execute target binaries. // compilation produces no artifacts and does not execute target binaries.
// Validation.ForbiddenFiles checks that selected repository-relative files are
// absent from the captured commit after Go checks and before other file checks.
// Validation.GoFormat checks regular committed Go source after those selected // Validation.GoFormat checks regular committed Go source after those selected
// Go checks and before AdditionalChecks. Its zero value disables formatting. // Go checks and before AdditionalChecks. Its zero value disables formatting.
// Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace // Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace
@@ -153,7 +174,7 @@ type GoValidationSpec struct {
// Nil disables the check; an empty object enables it. Outside-checkout // Nil disables the check; an empty object enables it. Outside-checkout
// destinations are reported as out of scope unless the selected specification // destinations are reported as out of scope unless the selected specification
// enforces the checkout boundary. Submodule contents remain out of scope. // enforces the checkout boundary. Submodule contents remain out of scope.
// The zero values of all selections preserve the ordinary suite. If // The zero values of the legacy module selections preserve the ordinary suite. If
// Build selects targets, Check builds them after validation in temporary // Build selects targets, Check builds them after validation in temporary
// storage outside the worktree, then rechecks // storage outside the worktree, then rechecks
// branch, HEAD, worktree, index, and local tag state. Success establishes local // branch, HEAD, worktree, index, and local tag state. Success establishes local
@@ -169,6 +190,12 @@ func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
func publicCandidate(checked candidate.Candidate) Candidate { func publicCandidate(checked candidate.Candidate) Candidate {
return Candidate{ return Candidate{
RepositoryDir: checked.RepositoryDir, RepositoryDir: checked.RepositoryDir,
SourceDir: checked.Identity.SourceDir,
SourceSubdir: checked.Identity.SourceSubdir,
GoEnabled: checked.Identity.GoEnabled,
Publication: PublicationMode(checked.Identity.Publication),
VersionFormat: VersionFormat(checked.Identity.VersionFormat),
VersionPrefix: checked.Identity.VersionPrefix,
ModuleDir: checked.ModuleDir, ModuleDir: checked.ModuleDir,
ModulePath: checked.ModulePath, ModulePath: checked.ModulePath,
Tag: checked.Tag, Tag: checked.Tag,
@@ -178,31 +205,38 @@ func publicCandidate(checked candidate.Candidate) Candidate {
} }
func candidateRequest(request ReleaseRequest) candidate.Request { func candidateRequest(request ReleaseRequest) candidate.Request {
fileSize := internalFileSizeSettings(request.Validation.FileSize)
result := candidate.Request{ result := candidate.Request{
RepositoryDir: request.RepositoryDir, RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir, ModuleDir: request.ModuleDir,
Product: request.Product, Source: internalSourceSpec(request.Source),
Version: request.Version, BuildTargets: request.Build != nil && len(request.Build.Targets) != 0,
Validation: validation.Settings{ Product: request.Product,
Race: request.Validation.Go.Race, Version: request.Version,
FullVet: request.Validation.Go.FullVet, Validation: internalValidationSpec(request.Validation),
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
GoFormat: request.Validation.GoFormat,
Markdown: internalMarkdownSettings(request.Validation.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
WorkspaceFiles: request.Validation.ModuleDistribution.WorkspaceFiles,
LocalReplacements: request.Validation.ModuleDistribution.LocalReplacements,
},
FileSize: fileSize,
},
AdditionalChecks: candidateChecks(request.AdditionalChecks), AdditionalChecks: candidateChecks(request.AdditionalChecks),
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output), AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
Output: request.Output, Output: request.Output,
} }
for index, target := range request.Validation.Go.CompileTargets { return result
result.Validation.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch} }
func internalValidationSpec(spec ValidationSpec) validation.Settings {
result := validation.Settings{
Race: spec.Go.Race,
FullVet: spec.Go.FullVet,
CompileTargets: make([]validation.Target, len(spec.Go.CompileTargets)),
SharedFiles: copyStringSlice(spec.SharedFiles),
ForbiddenFiles: copyStringSlice(spec.ForbiddenFiles),
GoFormat: spec.GoFormat,
Markdown: internalMarkdownSettings(spec.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
WorkspaceFiles: spec.ModuleDistribution.WorkspaceFiles,
LocalReplacements: spec.ModuleDistribution.LocalReplacements,
},
FileSize: internalFileSizeSettings(spec.FileSize),
}
for index, target := range spec.Go.CompileTargets {
result.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch}
} }
return result return result
} }

View File

@@ -0,0 +1,381 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
)
type assembledPage struct {
id int64
tag, commit, title, body string
assets map[string][]byte
}
type assembledForge struct {
mu sync.Mutex
remote string
pages map[string]*assembledPage
nextID int64
}
func (f *assembledForge) serve(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "token fixture-token" {
http.Error(w, "forbidden", 403)
return
}
const root = "/api/v1/repos/owner/example"
path := r.URL.EscapedPath()
if path == root || path == "/api/v1/repositories/1" {
json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
return
}
if strings.HasPrefix(path, root+"/tags/") {
tag, err := url.PathUnescape(strings.TrimPrefix(path, root+"/tags/"))
if err != nil {
http.Error(w, "bad tag", 400)
return
}
out, err := exec.Command("git", "--git-dir", f.remote, "rev-parse", "--verify", "refs/tags/"+tag+"^{commit}").Output()
if err != nil {
http.NotFound(w, r)
return
}
json.NewEncoder(w).Encode(map[string]any{"commit": map[string]string{"sha": strings.TrimSpace(string(out))}})
return
}
f.mu.Lock()
defer f.mu.Unlock()
encode := func(p *assembledPage) {
json.NewEncoder(w).Encode(map[string]any{"id": p.id, "tag_name": p.tag, "target_commitish": p.commit, "name": p.title, "body": p.body, "html_url": "http://" + r.Host + "/release", "draft": false, "prerelease": false})
}
if strings.HasPrefix(path, root+"/releases/tags/") {
tag, _ := url.PathUnescape(strings.TrimPrefix(path, root+"/releases/tags/"))
p := f.pages[tag]
if p == nil {
http.NotFound(w, r)
return
}
encode(p)
return
}
if path == root+"/releases" && r.Method == http.MethodPost {
var request struct {
Tag string `json:"tag_name"`
Commit string `json:"target_commitish"`
Title string `json:"name"`
Body string `json:"body"`
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, "bad request", 400)
return
}
f.nextID++
p := &assembledPage{id: f.nextID, tag: request.Tag, commit: request.Commit, title: request.Title, body: request.Body, assets: map[string][]byte{}}
f.pages[p.tag] = p
encode(p)
return
}
if strings.HasPrefix(path, root+"/releases/") {
remainder := strings.TrimPrefix(path, root+"/releases/")
parts := strings.Split(remainder, "/")
id, _ := strconv.ParseInt(parts[0], 10, 64)
var page *assembledPage
for _, candidate := range f.pages {
if candidate.id == id {
page = candidate
break
}
}
if page == nil {
http.NotFound(w, r)
return
}
if len(parts) == 1 {
if r.Method == http.MethodDelete {
delete(f.pages, page.tag)
w.WriteHeader(204)
return
}
encode(page)
return
}
if len(parts) == 2 && parts[1] == "assets" {
if r.Method == http.MethodGet {
list := []map[string]any{}
for name, data := range page.assets {
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(data), "browser_download_url": fmt.Sprintf("http://%s/files/%d/%s", r.Host, page.id, url.PathEscape(name))})
}
json.NewEncoder(w).Encode(list)
return
}
file, _, err := r.FormFile("attachment")
if err != nil {
http.Error(w, "bad upload", 400)
return
}
data, err := io.ReadAll(file)
file.Close()
if err != nil {
http.Error(w, "read upload", 500)
return
}
name := r.URL.Query().Get("name")
page.assets[name] = data
json.NewEncoder(w).Encode(map[string]any{"id": len(page.assets), "name": name, "size": len(data)})
return
}
}
if strings.HasPrefix(path, "/files/") {
parts := strings.SplitN(strings.TrimPrefix(path, "/files/"), "/", 2)
if len(parts) != 2 {
http.NotFound(w, r)
return
}
id, _ := strconv.ParseInt(parts[0], 10, 64)
name, _ := url.PathUnescape(parts[1])
for _, p := range f.pages {
if p.id == id {
if content, ok := p.assets[name]; ok {
w.Write(content)
return
}
}
}
http.NotFound(w, r)
return
}
http.NotFound(w, r)
}
type assembledCI struct {
mu sync.Mutex
t *testing.T
remote, binary, tag, commit string
log []byte
jobErr error
executed bool
}
func (ci *assembledCI) serve(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer wood-token" {
http.Error(w, "forbidden", 403)
return
}
switch r.URL.Path {
case "/api/repos/42":
fmt.Fprint(w, `{"id":42}`)
return
case "/api/repos/42/pipelines":
if r.URL.Query().Get("page") != "1" {
fmt.Fprint(w, `[]`)
return
}
ref := r.URL.Query().Get("ref")
if !strings.HasPrefix(ref, "refs/tags/releasekit-test/") {
fmt.Fprint(w, `[]`)
return
}
ci.mu.Lock()
defer ci.mu.Unlock()
if !ci.executed {
ci.tag = strings.TrimPrefix(ref, "refs/tags/")
ci.runJob()
}
status := "success"
if ci.jobErr != nil {
status = "failure"
}
json.NewEncoder(w).Encode([]map[string]any{{"id": 10, "number": 11, "event": "tag", "ref": ref, "commit": ci.commit, "status": status}})
return
case "/api/repos/42/pipelines/11":
ci.mu.Lock()
defer ci.mu.Unlock()
status := "success"
if ci.jobErr != nil {
status = "failure"
}
json.NewEncoder(w).Encode(map[string]any{"id": 10, "number": 11, "event": "tag", "ref": "refs/tags/" + ci.tag, "commit": ci.commit, "status": status, "workflows": []any{map[string]any{"id": 12, "name": "delivery", "state": status, "children": []any{map[string]any{"id": 13, "name": "deliver", "state": status}}}}})
return
case "/api/repos/42/logs/11/13/download":
ci.mu.Lock()
defer ci.mu.Unlock()
w.Write(ci.log)
return
default:
http.NotFound(w, r)
}
}
func (ci *assembledCI) runJob() {
ci.executed = true
command := exec.Command("git", "--git-dir", ci.remote, "rev-parse", "--verify", "refs/tags/"+ci.tag+"^{commit}")
commit, err := command.Output()
if err != nil {
ci.jobErr = err
return
}
ci.commit = strings.TrimSpace(string(commit))
checkout := filepath.Join(ci.t.TempDir(), "job")
command = exec.Command("git", "clone", "--no-checkout", "--local", ci.remote, checkout)
if out, err := command.CombinedOutput(); err != nil {
ci.jobErr = fmt.Errorf("clone job checkout: %w: %s", err, out)
return
}
command = exec.Command("git", "checkout", "--detach", ci.commit)
command.Dir = checkout
if out, err := command.CombinedOutput(); err != nil {
ci.jobErr = fmt.Errorf("checkout job: %w: %s", err, out)
return
}
command = exec.Command(ci.binary, "ci-deliver", "--repo", checkout, "--prepared", "--commit", ci.commit, ci.tag)
command.Dir = checkout
command.Env = append(os.Environ(), "RELEASEKIT_GITEA_TOKEN=fixture-token", "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
ci.log, ci.jobErr = command.CombinedOutput()
}
func TestAssembledPublicationAndRehearsalWorkflows(t *testing.T) {
root := cliRepositoryRoot(t)
binary := buildWorkflowCLI(t, root)
for _, test := range []struct {
name, version string
goEnabled, explicit, binary bool
}{
{name: "legacy-module", version: "v1.2.3", goEnabled: true},
{name: "go-application-source", version: "v2.0.0", goEnabled: true, explicit: true},
{name: "calendar-binary", version: "2026-12-05", goEnabled: true, explicit: true, binary: true},
{name: "configuration", version: "2026-12-05", explicit: true},
} {
t.Run(test.name, func(t *testing.T) {
repo := filepath.Join(t.TempDir(), "product")
if err := os.Mkdir(repo, 0700); err != nil {
t.Fatal(err)
}
cliGitRun(t, repo, "init", "--initial-branch=main")
cliGitRun(t, repo, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repo, "config", "user.email", "releasekit@example.test")
cliGitRun(t, repo, "config", "commit.gpgsign", "false")
remote := filepath.Join(t.TempDir(), "origin.git")
cliGitRun(t, repo, "init", "--bare", remote)
cliGitRun(t, repo, "remote", "add", "origin", remote)
state := &assembledForge{remote: remote, pages: map[string]*assembledPage{}}
forgeServer := httptest.NewServer(http.HandlerFunc(state.serve))
defer forgeServer.Close()
runner := &assembledCI{t: t, remote: remote, binary: binary}
ciServer := httptest.NewServer(http.HandlerFunc(runner.serve))
defer ciServer.Close()
writeRepositoryFile(t, repo, ".gitignore", ".releasekit/\n")
writeRepositoryFile(t, repo, "docs/releases/"+test.version+".md", "# Example "+test.version+"\n\nRelease note.\n")
if test.goEnabled {
module := "module example.com/fixture\n\ngo 1.27.0\n"
main := "package fixture\n"
if test.binary {
module += "\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => " + strconv.Quote(root) + "\n"
main = `package main
import ("fmt"; "os"; "go.maximumdirect.net/releasekit/buildinfo")
func main() { if len(os.Args)==2 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
`
}
writeRepositoryFile(t, repo, "go.mod", module)
writeRepositoryFile(t, repo, "main.go", main)
if test.binary {
command := exec.Command("go", "mod", "tidy")
command.Dir = repo
command.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off", "GOWORK=off")
if out, err := command.CombinedOutput(); err != nil {
t.Fatalf("prepare binary module: %v: %s", err, out)
}
}
} else {
writeRepositoryFile(t, repo, "config.yaml", "enabled: true\n")
writeRepositoryFile(t, repo, "config.json", `{"enabled":true}`)
}
profile := map[string]any{"product": "Example", "delivery": map[string]any{"forge": "gitea", "base_url": forgeServer.URL, "owner": "owner", "repository": "example", "credentials": map[string]any{"local": map[string]any{"token_file": ".releasekit/forge-token"}, "ci": map[string]any{"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}}}, "rehearsal": map[string]any{"woodpecker": map[string]any{"base_url": ciServer.URL, "repository_id": 42, "workflow": "delivery", "step": "deliver", "token_file": ".releasekit/ci-token"}}}
if test.explicit {
profile["source"] = map[string]any{}
if test.goEnabled {
profile["go"] = map[string]any{}
}
}
if strings.HasPrefix(test.version, "2026-") {
profile["version"] = map[string]any{"format": "date"}
}
if test.binary {
profile["build"] = map[string]any{"main_package": ".", "binary_name": "fixture", "targets": []string{runtime.GOOS + "/" + runtime.GOARCH}}
}
encoded, err := json.Marshal(profile)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "releasekit.json", string(encoded))
cliGitRun(t, repo, "add", "--all")
cliGitRun(t, repo, "commit", "-m", "prepare release")
cliGitRun(t, repo, "push", "origin", "HEAD:refs/heads/main")
writeRepositoryFile(t, repo, ".releasekit/forge-token", "fixture-token\n")
writeRepositoryFile(t, repo, ".releasekit/ci-token", "wood-token\n")
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
call := func(args ...string) (int, string, string) {
t.Helper()
var output, diagnostics bytes.Buffer
code := run(t.Context(), args, &output, &diagnostics)
return code, output.String(), diagnostics.String()
}
if code, out, diag := call("validate", "--repo", repo, "--operation", "rehearsal", "--json"); code != 0 {
t.Fatalf("readiness status=%d output=%s diagnostics=%s", code, out, diag)
}
if code, out, diag := call("check", "--repo", repo, test.version); code != 0 {
t.Fatalf("check status=%d output=%s diagnostics=%s", code, out, diag)
}
if code, out, diag := call("publish", "--repo", repo, test.version); code != 0 {
t.Fatalf("publish status=%d output=%s diagnostics=%s", code, out, diag)
}
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
if code, out, diag := call("ci-deliver", "--repo", repo, "--prepared", "--commit", commit, test.version); code != 0 {
t.Fatalf("production delivery status=%d output=%s diagnostics=%s", code, out, diag)
}
code, out, diag := call("test", "--repo", repo, "--timeout", "30s", "--cleanup-timeout", "10s", "--json")
if code != 0 {
runner.mu.Lock()
jobErr, log := runner.jobErr, string(runner.log)
runner.mu.Unlock()
t.Fatalf("rehearsal status=%d output=%s diagnostics=%s job error=%v job log=%s", code, out, diag, jobErr, log)
}
var report rehearsalDocument
if err := json.Unmarshal([]byte(out), &report); err != nil || report.Verification != "complete" || report.Cleanup != "complete" || report.RecordPath == "" {
t.Fatalf("report=%+v error=%v output=%s", report, err, out)
}
if test.binary && (report.Scope != "page-and-assets" || len(report.Artifacts) != 2) {
t.Fatalf("binary report=%+v", report)
}
if !test.binary && (report.Scope != "page" || len(report.Artifacts) != 0) {
t.Fatalf("page report=%+v", report)
}
if code, out, diag = call("test-resume", "--record", report.RecordPath, "--json"); code != 0 {
t.Fatalf("saved recovery status=%d output=%s diagnostics=%s", code, out, diag)
}
state.mu.Lock()
_, productionExists := state.pages[test.version]
_, diagnosticExists := state.pages[report.Tag]
state.mu.Unlock()
if !productionExists || diagnosticExists {
t.Fatalf("production page present=%t diagnostic page present=%t", productionExists, diagnosticExists)
}
if output, err := exec.Command("git", "--git-dir", remote, "rev-parse", "--verify", "refs/tags/"+report.Tag).CombinedOutput(); err == nil {
t.Fatalf("diagnostic tag remains: %s", output)
}
if output, err := exec.Command("git", "--git-dir", remote, "rev-parse", "--verify", "refs/tags/"+test.version).CombinedOutput(); err != nil {
t.Fatalf("production tag missing: %v: %s", err, output)
}
})
}
}

View File

@@ -7,7 +7,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) { func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
@@ -42,7 +42,7 @@ func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
defer server.Close() defer server.Close()
settings := cli.Settings{Product: "Example Product", ModuleDir: tt.module, settings := cli.Settings{Product: "Example Product", ModuleDir: tt.module,
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
} }
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
cliGitRun(t, repository, "add", ".") cliGitRun(t, repository, "add", ".")
@@ -94,9 +94,9 @@ func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
if err := os.WriteFile(receipt.Artifacts[0].Path, []byte("changed"), 0o600); err != nil { if err := os.WriteFile(receipt.Artifacts[0].Path, []byte("changed"), 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
requestsBefore := state.snapshot().apiRequests writesBefore := state.snapshot().writes
if status := run(context.Background(), args, &stdout, &stderr); status != 1 || state.snapshot().apiRequests != requestsBefore { if status := run(context.Background(), args, &stdout, &stderr); status != 1 || state.snapshot().writes != writesBefore {
t.Fatalf("changed content status=%d, requests=%d->%d, stderr=%s", status, requestsBefore, state.snapshot().apiRequests, stderr.String()) t.Fatalf("changed content status=%d, writes=%d->%d, stderr=%s", status, writesBefore, state.snapshot().writes, stderr.String())
} }
}) })
} }

View File

@@ -0,0 +1,60 @@
package main
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestCIDeliveryRejectsModuleTagMismatchBeforePreparation(t *testing.T) {
for _, binary := range []bool{false, true} {
name := "page-only"
if binary {
name = "binary"
}
t.Run(name, func(t *testing.T) {
repository := newDeliveryBuildRepository(t)
writeRepositoryFile(t, repository, "child/go.mod", "module example.com/tagged-app/child\n\ngo 1.26.0\n")
writeRepositoryFile(t, repository, "child/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nChild release.\n")
cliGitRun(t, repository, "add", "child")
cliGitRun(t, repository, "commit", "-m", "add child module")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("mismatched module tag reached forge: %s", r.URL.Path)
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
settings := cli.Settings{
Product: "Example Product", ModuleDir: "child",
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}
if binary {
settings.Build = &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
}
writeDeliveryProfile(t, repository, settings)
commit := pushTaggedCLIRepository(t, repository)
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
shimDir := t.TempDir()
marker := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", marker)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--prepared", "--commit", commit, "--expected-module", "child", "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected source tag "child/v1.2.3"`) {
t.Fatalf("status=%d stderr=%q, want module tag mismatch", status, stderr.String())
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("dependency/build work ran before tag comparison: %v", err)
}
})
}
}

View File

@@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestCandidateCheckUsesCommittedDeclarationSymlink(t *testing.T) { func TestCandidateCheckUsesCommittedDeclarationSymlink(t *testing.T) {
@@ -40,7 +40,7 @@ func TestPageOnlyDeliveryUsesCommittedModuleInSparseCheckout(t *testing.T) {
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", ModuleDir: module, writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", ModuleDir: module,
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", state.snapshot().tag) cliGitRun(t, repository, "tag", state.snapshot().tag)

View File

@@ -0,0 +1,71 @@
package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestDeliveryFailureStatusesRespectPhase(t *testing.T) {
for _, test := range []struct {
name, rejectedPath, state string
cancelWrite bool
status int
}{
{name: "preflight authorization", rejectedPath: "/api/v1/repos/owner/example", state: "not_attempted", status: 2},
{name: "later authorization", rejectedPath: "/api/v1/repos/owner/example/tags/v1.2.3", state: "not_attempted", status: 1},
{name: "canceled unresolved write", cancelWrite: true, state: "unknown", status: 3},
} {
t.Run(test.name, func(t *testing.T) {
repository := newCLIRepository(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var commit string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == test.rejectedPath {
http.Error(w, "rejected credential", http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
case "/api/v1/repos/owner/example/tags/v1.2.3":
_ = json.NewEncoder(w).Encode(map[string]any{"commit": map[string]string{"sha": commit}})
case "/api/v1/repos/owner/example/releases/tags/v1.2.3":
http.NotFound(w, r)
case "/api/v1/repos/owner/example/releases":
if r.Method != http.MethodPost || !test.cancelWrite {
t.Errorf("unexpected release write: %s", r.Method)
}
cancel()
http.Error(w, "unacknowledged write", http.StatusServiceUnavailable)
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
})
commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
cliGitRun(t, repository, "tag", "v1.2.3")
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
var stdout, stderr bytes.Buffer
status := run(ctx, []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != test.status || !strings.Contains(stderr.String(), "state="+test.state) {
t.Fatalf("status=%d stderr=%q, want status %d and state %s", status, stderr.String(), test.status, test.state)
}
if test.cancelWrite && !strings.Contains(stderr.String(), context.Canceled.Error()) {
t.Fatalf("cancellation cause missing: %s", stderr.String())
}
})
}
}

View File

@@ -0,0 +1,64 @@
package main
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestInvalidDeliveryDestinationStopsBeforePreparation(t *testing.T) {
for _, command := range []string{"deliver", "ci-deliver"} {
for _, setting := range []string{"URL", "owner", "repository"} {
t.Run(command+"/"+setting, func(t *testing.T) {
repository := newDeliveryBuildRepository(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("invalid destination made a hosted request: %s", r.URL.Path)
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}}
switch setting {
case "URL":
destination.BaseURL = "ssh://forge.example"
case "owner":
destination.Owner = "owner/child"
case "repository":
destination.Repository = "repo/child"
}
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Delivery: destination,
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
})
commit := pushTaggedCLIRepository(t, repository)
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "fixture-token")
shimDir := t.TempDir()
marker := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", marker)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
args := []string{command, "--repo", repository}
if command == "ci-deliver" {
args = append(args, "--prepared", "--commit", commit)
}
args = append(args, "v1.2.3")
var stdout, stderr bytes.Buffer
status := run(context.Background(), args, &stdout, &stderr)
if status != 2 || !strings.Contains(stderr.String(), "invalid_destination") {
t.Fatalf("status=%d stderr=%q, want destination configuration error", status, stderr.String())
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("preparation/build ran for invalid destination: %v", err)
}
})
}
}
}

View File

@@ -0,0 +1,97 @@
package main
import (
"context"
"fmt"
"io"
"strings"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
// verifyDiagnosticTag binds dispatch to the tag's captured profile and source.
func verifyDiagnosticTag(ctx context.Context, repository, tag, commit, selector, profilePath string) (rehearsal.VerifiedTag, cli.Settings, error) {
var settings cli.Settings
verified, err := rehearsal.VerifyTag(ctx, repository, tag, commit, selector, profilePath, func(ctx context.Context, capturedCommit string, profile []byte) (releaseidentity.ResolvedSource, error) {
var err error
settings, err = cli.DecodeSettings(profile, profilePath)
if err != nil {
return releaseidentity.ResolvedSource{}, err
}
if settings.Rehearsal == nil || settings.Rehearsal.RehearsalSelector() != selector {
return releaseidentity.ResolvedSource{}, fmt.Errorf("captured profile does not select diagnostic selector %q", selector)
}
return releaseidentity.LoadCommittedSource(ctx, repository, settings.ModuleDir, capturedCommit, settings.SourceSpec())
})
return verified, settings, err
}
func runDiagnosticDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) (status int) {
parts := strings.Split(invocation.ExpectedTag, "/")
if len(parts) != 3 || parts[0] != "releasekit-test" {
fmt.Fprintln(stderr, "invalid diagnostic tag")
return 2
}
captured, err := cli.CaptureCommittedProfile(ctx, invocation.Repository, invocation.Commit, invocation.ConfigPath)
if err != nil {
fmt.Fprintf(stderr, "capture diagnostic profile: %v\n", err)
return 1
}
verified, settings, err := verifyDiagnosticTag(ctx, invocation.Repository, invocation.ExpectedTag, invocation.Commit, parts[1], captured.Path)
if err != nil {
fmt.Fprintf(stderr, "verify diagnostic tag: %v\n", err)
return 1
}
result := rehearsal.JobResult{Manifest: verified.Manifest, Scope: "page", Build: "not_requested", Delivery: "not_attempted", Verification: "not_attempted", Artifacts: []rehearsal.ArtifactEvidence{}}
defer func() {
frame, err := rehearsal.EncodeResult(result)
if err != nil {
fmt.Fprintf(stderr, "encode diagnostic result: %v\n", err)
status = 1
return
}
if _, err = stdout.Write(frame); err != nil {
fmt.Fprintf(stderr, "write diagnostic result: %v\n", err)
status = 1
}
}()
fail := func(message string, err error, code int) int {
result.Diagnostics = append(result.Diagnostics, message)
if err != nil {
fmt.Fprintf(stderr, "%s: %v\n", message, git.DisplayError(err))
} else {
fmt.Fprintln(stderr, message)
}
return code
}
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
return fail("diagnostic source selection failed", err, 2)
}
if settings.Build != nil && len(settings.Build.Targets) != 0 && !verified.Source.GoEnabled {
result.Scope, result.Build = "page-and-assets", "not_attempted"
return fail("build targets require Go capability", nil, 2)
}
destination, code := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr)
if code != 0 {
result.Diagnostics = append(result.Diagnostics, "delivery credential unavailable")
return code
}
delivered, err := releasekit.DeliverRehearsal(ctx, releasekit.RehearsalDeliveryRequest{RepositoryDir: invocation.Repository, ModuleDir: settings.ModuleDir, Source: sourceSpec(settings), Product: settings.Product, Tag: invocation.ExpectedTag, Commit: invocation.Commit, ProfilePath: captured.Path, Selector: verified.Manifest.Selector, Destination: destination, Build: configuredBuildSpec(settings.Build), Output: stderr})
result.Scope, result.Build, result.Verification = delivered.Scope, delivered.Build, delivered.Verification
result.Delivery, result.PageID = string(delivered.Delivery.State), delivered.PageID
result.Diagnostics = append(result.Diagnostics, delivered.Diagnostics...)
for _, item := range delivered.Artifacts {
result.Artifacts = append(result.Artifacts, rehearsal.ArtifactEvidence{Name: item.Name, Size: item.Size, SHA256: item.SHA256})
}
if err != nil {
return reportDeliveryFailure(stderr, delivered.Delivery, err)
}
return 0
}

View File

@@ -0,0 +1,256 @@
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"strings"
"sync/atomic"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func TestVerifyDiagnosticTagUsesCapturedProfileAndSelector(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Captured","source":{},"rehearsal":{"selector":"root"}}`)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture diagnostic profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "releasekit.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attempt, "root", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Working tree"}`)
verified, settings, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, captured.Commit, "root", captured.Path)
if err != nil || settings.Product != "Captured" || verified.Manifest.AttemptID != attempt {
t.Fatalf("verified=%+v settings=%+v error=%v", verified, settings, err)
}
if _, _, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, captured.Commit, "other", captured.Path); err == nil {
t.Fatal("accepted wrong selector")
}
if _, _, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, "0000000000000000000000000000000000000000", "root", captured.Path); err == nil {
t.Fatal("accepted wrong event commit")
}
}
func TestCIDiagnosticDeliveryVerifiesPageAndEmitsEvidence(t *testing.T) {
repo := newCLIRepository(t)
state := &deliveryServerState{data: deliveryServerData{product: "Example diagnostic"}}
server := newDeliveryServer(t, state)
defer server.Close()
profile := fmt.Sprintf(`{"product":"Example","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}},"rehearsal":{"selector":"root"}}`, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attempt, "root", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
state.update(func(data *deliveryServerData) { data.tag = identity.Tag; data.commit = identity.Commit })
args := []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", identity.Commit, identity.Tag}
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "")
var output, diagnostics bytes.Buffer
if status := run(t.Context(), args, &output, &diagnostics); status != 2 {
t.Fatalf("missing credential status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
failed, err := rehearsal.ReadResult(bytes.NewReader(output.Bytes()), manifest)
if err != nil || failed.Delivery != "not_attempted" || state.snapshot().releaseCreates != 0 {
t.Fatalf("failed=%+v err=%v", failed, err)
}
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
output.Reset()
diagnostics.Reset()
if status := run(t.Context(), args, &output, &diagnostics); status != 0 {
t.Fatalf("status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
result, err := rehearsal.ReadResult(bytes.NewReader(output.Bytes()), manifest)
if err != nil || result.Scope != "page" || result.Verification != "complete" || result.PageID != 10 || len(result.Artifacts) != 0 || state.snapshot().releaseCreates != 1 {
t.Fatalf("result=%+v error=%v", result, err)
}
}
func TestCIDiagnosticDeliveryBuildsAndReadsBackAssets(t *testing.T) {
repo := newCLIBuildRepository(t, `package main
import ("fmt"; "os"; "go.maximumdirect.net/releasekit/buildinfo")
func main(){ if len(os.Args)==2 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
`)
state := &deliveryServerState{data: deliveryServerData{product: "Example diagnostic"}}
server := newDeliveryServer(t, state)
defer server.Close()
profile := fmt.Sprintf(`{"product":"Example","go":{},"build":{"main_package":"./cmd/app","binary_name":"fixture","targets":[%q]},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}},"rehearsal":{"selector":"root"}}`, runtime.GOOS+"/"+runtime.GOARCH, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "configure diagnostic delivery")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attempt, "root", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
state.update(func(data *deliveryServerData) { data.tag = identity.Tag; data.commit = identity.Commit })
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
var output, diagnostics bytes.Buffer
args := []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", identity.Commit, identity.Tag}
state.update(func(data *deliveryServerData) { data.failAssetDownloads = true })
status := run(t.Context(), args, &output, &diagnostics)
failed, readErr := rehearsal.ReadResult(bytes.NewReader(output.Bytes()), manifest)
if status == 0 || readErr != nil || failed.Build != "complete" || failed.Verification != "failed" || failed.PageID != 10 || state.snapshot().assetUploads != 2 {
t.Fatalf("read-back failure status=%d result=%+v error=%v diagnostics=%s", status, failed, readErr, &diagnostics)
}
state.update(func(data *deliveryServerData) { data.failAssetDownloads = false })
output.Reset()
diagnostics.Reset()
status = run(t.Context(), args, &output, &diagnostics)
if status != 0 {
t.Fatalf("status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
result, err := rehearsal.ReadResult(bytes.NewReader(output.Bytes()), manifest)
if err != nil || result.Scope != "page-and-assets" || result.Build != "complete" || result.Verification != "complete" || len(result.Artifacts) != 2 || state.snapshot().assetUploads != 2 {
t.Fatalf("result=%+v error=%v", result, err)
}
}
func TestCIDiagnosticRejectsProfileSelectorMismatch(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{},"rehearsal":{"selector":"root"}}`)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "other", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, id, "other", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
var output, diagnostics bytes.Buffer
status := run(t.Context(), []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", identity.Commit, identity.Tag}, &output, &diagnostics)
if status == 0 || !strings.Contains(diagnostics.String(), "does not select diagnostic selector") {
t.Fatalf("status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
}
func TestCIDiagnosticUsesProductionDeliveryExitClasses(t *testing.T) {
for _, test := range []struct {
name string
denied bool
want int
}{{"credential rejection", true, 2}, {"uncertain write", false, 3}} {
for _, diagnostic := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/diagnostic=%t", test.name, diagnostic), func(t *testing.T) {
repo := newCLIBuildRepository(t, `package main
import ("fmt"; "os"; "go.maximumdirect.net/releasekit/buildinfo")
func main(){ if len(os.Args)==2 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
`)
product := "Example"
if diagnostic {
product += " diagnostic"
}
state := &deliveryServerState{data: deliveryServerData{product: product}}
base := newDeliveryServer(t, state)
defer base.Close()
var attempted atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if test.denied {
http.Error(w, "denied", http.StatusUnauthorized)
return
}
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/releases") {
attempted.Store(true)
http.Error(w, "lost acknowledgment", http.StatusServiceUnavailable)
return
}
if attempted.Load() && strings.Contains(r.URL.Path, "/releases/tags/") {
http.Error(w, "observation unavailable", http.StatusServiceUnavailable)
return
}
base.Config.Handler.ServeHTTP(w, r)
}))
defer server.Close()
build := ""
if test.denied {
build = fmt.Sprintf(`,"build":{"main_package":"./cmd/app","binary_name":"fixture","targets":[%q]}`, runtime.GOOS+"/"+runtime.GOARCH)
}
profile := fmt.Sprintf(`{"product":"Example","go":{}%s,"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}},"rehearsal":{"selector":"root"}}`, build, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
writeRepositoryFile(t, repo, "docs/releases/v1.2.3.md", "# Example v1.2.3\n")
cliGitRun(t, repo, "add", "releasekit.json", "docs")
cliGitRun(t, repo, "commit", "-m", "capture delivery profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
tag := "v1.2.3"
if diagnostic {
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, id, "root", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
tag = identity.Tag
} else {
cliGitRun(t, repo, "tag", "-a", "-m", "# Example v1.2.3", tag)
}
state.update(func(data *deliveryServerData) { data.tag, data.commit = tag, captured.Commit })
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
var output, diagnostics bytes.Buffer
if code := run(t.Context(), []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", captured.Commit, tag}, &output, &diagnostics); code != test.want {
t.Fatalf("code=%d want=%d output=%s diagnostics=%s", code, test.want, &output, &diagnostics)
}
})
}
}
}

View File

@@ -12,7 +12,7 @@ func TestMultiModuleExampleSetupUsesCurrentSourceTool(t *testing.T) {
root := cliRepositoryRoot(t) root := cliRepositoryRoot(t)
repository := newCLIRepository(t) repository := newCLIRepository(t)
copyExampleTree(t, filepath.Join(root, "examples", "multi-module"), repository) copyExampleTree(t, filepath.Join(root, "examples", "multi-module"), repository)
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
environment := append(os.Environ(), "GOTOOLCHAIN=local", "GOWORK=off", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=") environment := append(os.Environ(), "GOTOOLCHAIN=local", "GOWORK=off", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=")
goCommand := func(directory string, args ...string) string { goCommand := func(directory string, args ...string) string {
t.Helper() t.Helper()

View File

@@ -0,0 +1,62 @@
package cli
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
// CommittedProfile captures the exact profile used by a rehearsal.
type CommittedProfile struct {
RepositoryDir string
Commit string
Path string
SHA256 string
Settings Settings
Bytes []byte
}
// CaptureCommittedProfile reads the chosen profile from a resolved commit,
// independent of the working checkout and index.
func CaptureCommittedProfile(ctx context.Context, repositoryDir, revision, configPath string) (CommittedProfile, error) {
var result CommittedProfile
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return result, err
}
result.RepositoryDir = root
result.Commit, err = git.ResolveCommit(ctx, root, revision)
if err != nil {
return result, err
}
if configPath == "" {
configPath = "releasekit.json"
}
if filepath.IsAbs(configPath) {
configPath, err = filepath.Rel(root, filepath.Clean(configPath))
if err != nil {
return result, fmt.Errorf("relate profile to checkout: %w", err)
}
}
configPath = filepath.Clean(configPath)
if configPath == "." || configPath == ".." || strings.HasPrefix(configPath, ".."+string(filepath.Separator)) || filepath.IsAbs(configPath) {
return result, fmt.Errorf("rehearsal profile must be committed within the checkout")
}
result.Path = filepath.ToSlash(configPath)
result.Bytes, err = git.ReadCommitFile(ctx, root, result.Commit, result.Path)
if err != nil {
return result, fmt.Errorf("rehearsal profile %q must exist in the selected commit: %w", result.Path, err)
}
result.Settings, err = DecodeSettings(result.Bytes, result.Path)
if err != nil {
return result, err
}
digest := sha256.Sum256(result.Bytes)
result.SHA256 = hex.EncodeToString(digest[:])
return result, nil
}

View File

@@ -0,0 +1,84 @@
package cli
import (
"crypto/sha256"
"encoding/hex"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestCaptureCommittedProfileIgnoresWorkingChanges(t *testing.T) {
repo := t.TempDir()
run := func(args ...string) string {
t.Helper()
command := exec.Command("git", args...)
command.Dir = repo
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v: %s", args, err, output)
}
return strings.TrimSpace(string(output))
}
run("init", "--initial-branch=main")
run("config", "user.name", "ReleaseKit Test")
run("config", "user.email", "releasekit@example.test")
run("config", "commit.gpgsign", "false")
name := filepath.Join(repo, "releasekit.json")
first := []byte(`{"product":"Original","source":{},"rehearsal":{"woodpecker":{"base_url":"https://ci.example","repository_id":42,"workflow":"delivery","step":"publish","token_file":".releasekit/ci-token"}}}`)
if err := os.WriteFile(name, first, 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "first profile")
firstCommit := run("rev-parse", "HEAD")
if err := os.WriteFile(name, []byte(`{"product":"Second"}`), 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "second profile")
if err := os.WriteFile(name, []byte(`{"product":"Dirty"}`), 0600); err != nil {
t.Fatal(err)
}
before := run("status", "--porcelain")
captured, err := CaptureCommittedProfile(t.Context(), repo, firstCommit, name)
digest := sha256.Sum256(first)
if err != nil || captured.Commit != firstCommit || captured.Path != "releasekit.json" || captured.Settings.Product != "Original" || captured.Settings.Rehearsal == nil || captured.Settings.Rehearsal.RehearsalSelector() != "root" || captured.Settings.Rehearsal.Woodpecker.RepositoryID != 42 || captured.SHA256 != hex.EncodeToString(digest[:]) || string(captured.Bytes) != string(first) {
t.Fatalf("captured=%+v error=%v", captured, err)
}
latest, err := CaptureCommittedProfile(t.Context(), repo, "", "")
if err != nil || latest.Settings.Product != "Second" {
t.Fatalf("HEAD profile=%+v error=%v", latest, err)
}
if _, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", filepath.Join(t.TempDir(), "outside.json")); err == nil || !strings.Contains(err.Error(), "within the checkout") {
t.Fatalf("external profile error=%v", err)
}
if _, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", "missing.json"); err == nil || !strings.Contains(err.Error(), "selected commit") {
t.Fatalf("missing profile error=%v", err)
}
if after := run("status", "--porcelain"); after != before {
t.Fatalf("capture changed checkout: %q != %q", after, before)
}
}
func TestResolveWoodpeckerCredentialUsesSelectedFile(t *testing.T) {
repo := t.TempDir()
if err := os.WriteFile(filepath.Join(repo, "token"), []byte(" ci-secret \n"), 0600); err != nil {
t.Fatal(err)
}
token, source, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{TokenFile: "token"})
if err != nil || token != "ci-secret" || source.Context != LocalCredentials || source.Source != filepath.Join(repo, "token") {
t.Fatalf("token matches=%t source=%+v error=%v", token == "ci-secret", source, err)
}
if _, _, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{}); err == nil || !strings.Contains(err.Error(), "rehearsal.woodpecker.token_file") {
t.Fatalf("missing selection error=%v", err)
}
if err := os.WriteFile(filepath.Join(repo, "token"), []byte(" \n"), 0600); err != nil {
t.Fatal(err)
}
if _, _, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{TokenFile: "token"}); err == nil || strings.Contains(err.Error(), "ci-secret") {
t.Fatalf("blank token error=%v", err)
}
}

View File

@@ -3,6 +3,7 @@
package cli package cli
import ( import (
"bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -12,37 +13,74 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process" "go.maximumdirect.net/releasekit/internal/process"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/releaseidentity"
) )
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG" const Usage = "usage: releasekit version\n releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--record-dir DIR] [--expected-module DIR] [--expected-source DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG\n releasekit test [--repo DIR] [--config FILE] [--ref REF] [--record-dir DIR] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-resume --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]\n releasekit test-cleanup --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--cleanup-timeout DURATION] [--json]\n releasekit reconcile --record FILE [--json]\n releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]"
type Command string type Command string
const ( const (
VersionCommand Command = "version" VersionCommand Command = "version"
CheckAction Command = "check" ValidateAction Command = "validate"
PublishAction Command = "publish" CheckAction Command = "check"
BuildAction Command = "build" PublishAction Command = "publish"
DeliveryAction Command = "deliver" BuildAction Command = "build"
CIDeliveryAction Command = "ci-deliver" DeliveryAction Command = "deliver"
CIDeliveryAction Command = "ci-deliver"
ReconcileAction Command = "reconcile"
PublicationAttemptsAction Command = "publication-attempts"
TestAction Command = "test"
TestResumeAction Command = "test-resume"
TestCleanupAction Command = "test-cleanup"
) )
// Invocation contains parsed command settings owned by the CLI adapter. // Invocation contains parsed command settings owned by the CLI adapter.
type Invocation struct { type Invocation struct {
Command Command Command Command
Repository string Repository string
ConfigPath string ConfigPath string
OutputDir string OutputDir string
AssetsDir string AssetsDir string
Remote string Remote string
Commit string Commit string
Version string Version string
ExpectedModule string ExpectedModule string
ExpectedTag string ExpectedSource string
Prepared bool ExpectedTag string
Prepared bool
RecordPath string
RecordDir string
JSON bool
Context string
Operations []string
Offline bool
Ref string
TokenFile string
WoodpeckerTokenFile string
Timeout time.Duration
CleanupTimeout time.Duration
}
type operationFlags []string
func (values *operationFlags) String() string { return strings.Join(*values, ",") }
func (values *operationFlags) Set(value string) error {
switch value {
case "publication", "go", "build", "delivery", "rehearsal":
default:
return fmt.Errorf("unknown validation operation %q", value)
}
for _, existing := range *values {
if existing == value {
return nil
}
}
*values = append(*values, value)
return nil
} }
// Parse accepts only commands that have been implemented by the executable. // Parse accepts only commands that have been implemented by the executable.
@@ -51,6 +89,87 @@ func Parse(args []string) (Invocation, error) {
return Invocation{}, errors.New("a command is required") return Invocation{}, errors.New("a command is required")
} }
switch args[0] { switch args[0] {
case string(TestAction), string(TestResumeAction), string(TestCleanupAction):
action := Command(args[0])
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
flags.SetOutput(io.Discard)
invocation := Invocation{Command: action, Timeout: 30 * time.Minute, CleanupTimeout: 2 * time.Minute}
if action == TestAction {
flags.StringVar(&invocation.Repository, "repo", ".", "repository directory")
flags.StringVar(&invocation.ConfigPath, "config", "", "committed profile path")
flags.StringVar(&invocation.Ref, "ref", "", "source commit")
flags.StringVar(&invocation.RecordDir, "record-dir", "", "attempt record directory")
} else {
flags.StringVar(&invocation.RecordPath, "record", "", "attempt record file")
flags.StringVar(&invocation.TokenFile, "token-file", "", "delivery token file override")
flags.StringVar(&invocation.WoodpeckerTokenFile, "woodpecker-token-file", "", "Woodpecker token file override")
}
if action != TestCleanupAction {
flags.DurationVar(&invocation.Timeout, "timeout", 30*time.Minute, "CI observation timeout")
}
flags.DurationVar(&invocation.CleanupTimeout, "cleanup-timeout", 2*time.Minute, "cleanup timeout")
flags.BoolVar(&invocation.JSON, "json", false, "write structured JSON")
if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err
}
if flags.NArg() != 0 {
return Invocation{}, fmt.Errorf("%s takes no positional arguments", action)
}
if action != TestAction && strings.TrimSpace(invocation.RecordPath) == "" {
return Invocation{}, fmt.Errorf("%s requires --record FILE", action)
}
if invocation.Timeout < 0 {
return Invocation{}, errors.New("--timeout must not be negative")
}
if invocation.CleanupTimeout <= 0 {
return Invocation{}, errors.New("--cleanup-timeout must be positive")
}
return invocation, nil
case string(ValidateAction):
flags := flag.NewFlagSet(string(ValidateAction), flag.ContinueOnError)
flags.SetOutput(io.Discard)
repository := flags.String("repo", ".", "repository directory")
configPath := flags.String("config", "", "profile path")
credentialContext := flags.String("context", "local", "credential context")
var operations operationFlags
flags.Var(&operations, "operation", "selected readiness operation")
offline := flags.Bool("offline", false, "omit remote observations")
assets := flags.String("assets", "", "existing build assets directory")
structured := flags.Bool("json", false, "write structured JSON")
if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err
}
if flags.NArg() != 0 {
return Invocation{}, errors.New("validate takes no positional arguments")
}
if *credentialContext != "local" && *credentialContext != "ci" {
return Invocation{}, errors.New("validate --context must be local or ci")
}
return Invocation{Command: ValidateAction, Repository: *repository, ConfigPath: *configPath, Context: *credentialContext, Operations: operations, Offline: *offline, AssetsDir: *assets, JSON: *structured}, nil
case string(ReconcileAction), string(PublicationAttemptsAction):
action := Command(args[0])
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
flags.SetOutput(io.Discard)
record := ""
recordDir := ""
repository := "."
if action == ReconcileAction {
flags.StringVar(&record, "record", "", "attempt record file")
} else {
flags.StringVar(&repository, "repo", ".", "repository directory")
flags.StringVar(&recordDir, "record-dir", "", "attempt-record directory")
}
structured := flags.Bool("json", false, "write structured JSON")
if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err
}
if flags.NArg() != 0 {
return Invocation{}, fmt.Errorf("%s takes no positional arguments", action)
}
if action == ReconcileAction && record == "" {
return Invocation{}, errors.New("reconcile requires --record FILE")
}
return Invocation{Command: action, Repository: repository, RecordPath: record, RecordDir: recordDir, JSON: *structured}, nil
case string(VersionCommand): case string(VersionCommand):
if len(args) != 1 { if len(args) != 1 {
return Invocation{}, errors.New("version takes no arguments") return Invocation{}, errors.New("version takes no arguments")
@@ -72,8 +191,14 @@ func Parse(args []string) (Invocation, error) {
} }
var remote *string var remote *string
expectedModule := "" expectedModule := ""
expectedSource := ""
if action == PublishAction || action == CIDeliveryAction { if action == PublishAction || action == CIDeliveryAction {
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping") flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
flags.StringVar(&expectedSource, "expected-source", "", "expected source directory from a launcher mapping")
}
recordDir := ""
if action == PublishAction {
flags.StringVar(&recordDir, "record-dir", "", "publication attempt-record directory")
} }
expectedCommit := "" expectedCommit := ""
prepared := false prepared := false
@@ -101,18 +226,12 @@ func Parse(args []string) (Invocation, error) {
if slash := strings.LastIndex(version, "/"); slash >= 0 { if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:] version = version[slash+1:]
} }
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("ci-deliver TAG must end in a stable vMAJOR.MINOR.PATCH version")
}
}
if !versioncontract.ValidStableVersion(version) {
return Invocation{}, errors.New("VERSION must be a stable vMAJOR.MINOR.PATCH version")
} }
parsedRemote := "" parsedRemote := ""
if remote != nil { if remote != nil {
parsedRemote = *remote parsedRemote = *remote
} }
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedTag: expectedTag, Prepared: prepared}, nil return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedSource: expectedSource, ExpectedTag: expectedTag, Prepared: prepared, RecordDir: recordDir}, nil
default: default:
return Invocation{}, fmt.Errorf("unknown command %q", args[0]) return Invocation{}, fmt.Errorf("unknown command %q", args[0])
} }
@@ -139,22 +258,89 @@ type CheckCommand struct {
// Settings contains the product, remote, publication expectation, shared // Settings contains the product, remote, publication expectation, shared
// validation selections, and check commands read from a releasekit.json profile. // validation selections, and check commands read from a releasekit.json profile.
type Settings struct { type Settings struct {
Product string `json:"product"` Product string `json:"product"`
ModuleDir string `json:"module_dir,omitempty"` ModuleDir string `json:"module_dir,omitempty"`
Remote string `json:"remote,omitempty"` Source *SourceSettings `json:"source,omitempty"`
ExpectedPushURL string `json:"expected_push_url,omitempty"` Go *struct{} `json:"go,omitempty"`
Checks []CheckCommand `json:"checks,omitempty"` Publication *PublicationSettings `json:"publication,omitempty"`
Validation *ValidationSettings `json:"validation,omitempty"` Version *VersionSettings `json:"version,omitempty"`
Build *BuildSettings `json:"build,omitempty"` Remote string `json:"remote,omitempty"`
Delivery *DeliverySettings `json:"delivery,omitempty"` ExpectedPushURL string `json:"expected_push_url,omitempty"`
Checks []CheckCommand `json:"checks,omitempty"`
Validation *ValidationSettings `json:"validation,omitempty"`
Build *BuildSettings `json:"build,omitempty"`
Delivery *DeliverySettings `json:"delivery,omitempty"`
Readiness *ReadinessSettings `json:"readiness,omitempty"`
Rehearsal *RehearsalSettings `json:"rehearsal,omitempty"`
}
// RehearsalSettings selects a diagnostic dispatch selector and CI observer.
type RehearsalSettings struct {
Selector string `json:"selector,omitempty"`
Woodpecker *WoodpeckerSettings `json:"woodpecker,omitempty"`
}
// WoodpeckerSettings identifies the exact repository and delivery job.
type WoodpeckerSettings struct {
BaseURL string `json:"base_url"`
RepositoryID int64 `json:"repository_id"`
Workflow string `json:"workflow"`
Step string `json:"step"`
TokenFile string `json:"token_file"`
}
// RehearsalSelector returns the configured selector or the default root row.
func (s RehearsalSettings) RehearsalSelector() string {
if s.Selector == "" {
return "root"
}
return s.Selector
}
// ReadinessSettings lists files deliberately required for setup diagnostics.
type ReadinessSettings struct {
RequiredFiles []string `json:"required_files,omitempty"`
}
type SourceSettings struct {
Dir string `json:"dir,omitempty"`
TagPrefix *string `json:"tag_prefix,omitempty"`
}
type PublicationSettings struct {
Mode string `json:"mode,omitempty"`
}
type VersionSettings struct {
Format string `json:"format,omitempty"`
Prefix *string `json:"prefix,omitempty"`
}
// SourceSpec maps the optional profile selection to the internal selection.
func (s Settings) SourceSpec() *releaseidentity.SourceSpec {
if s.Source == nil && s.Go == nil && s.Publication == nil && s.Version == nil {
return nil
}
result := &releaseidentity.SourceSpec{GoEnabled: s.Go != nil}
if s.Source != nil {
result.Dir, result.TagPrefix = s.Source.Dir, s.Source.TagPrefix
}
if s.Publication != nil {
result.Publication = s.Publication.Mode
}
if s.Version != nil {
result.VersionFormat, result.VersionPrefix = s.Version.Format, s.Version.Prefix
}
return result
} }
// ValidationSettings selects shared candidate checks in a release profile. // ValidationSettings selects shared candidate checks in a release profile.
type ValidationSettings struct { type ValidationSettings struct {
// SharedFiles selects committed files relative to the repository root. // SharedFiles selects committed files relative to the repository root.
// Nil uses optional defaults; a non-nil empty slice selects no shared files. // Nil uses optional defaults; a non-nil empty slice selects no shared files.
SharedFiles []string `json:"shared_files"` SharedFiles []string `json:"shared_files"`
Go GoValidationSettings `json:"go,omitempty"` ForbiddenFiles []string `json:"forbidden_files,omitempty"`
Go GoValidationSettings `json:"go,omitempty"`
// GoFormat checks the formatting of committed regular Go source files. // GoFormat checks the formatting of committed regular Go source files.
// Omitted or false disables the check. // Omitted or false disables the check.
GoFormat bool `json:"go_format,omitempty"` GoFormat bool `json:"go_format,omitempty"`
@@ -195,12 +381,28 @@ type GoValidationSettings struct {
CompileTargets []string `json:"compile_targets,omitempty"` CompileTargets []string `json:"compile_targets,omitempty"`
} }
// DeliverySettings selects the hosted Gitea release destination. // DeliverySettings selects the hosted forge release destination.
type DeliverySettings struct { type DeliverySettings struct {
BaseURL string `json:"base_url"` Forge string `json:"forge,omitempty"`
Owner string `json:"owner"` BaseURL string `json:"base_url"`
Repository string `json:"repository"` Owner string `json:"owner"`
TokenEnv string `json:"token_env,omitempty"` Repository string `json:"repository"`
Credentials *DeliveryCredentials `json:"credentials,omitempty"`
LegacyTokenEnv json.RawMessage `json:"token_env,omitempty"`
LegacyTokenFile json.RawMessage `json:"token_file,omitempty"`
}
type DeliveryCredentials struct {
Local *LocalCredential `json:"local,omitempty"`
CI *CICredential `json:"ci,omitempty"`
}
type LocalCredential struct {
TokenFile string `json:"token_file"`
}
type CICredential struct {
TokenEnvironmentVariable string `json:"token_environment_variable,omitempty"`
} }
// BuildSettings selects the Go application package, artifact name, and targets. // BuildSettings selects the Go application package, artifact name, and targets.
@@ -229,9 +431,17 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err) return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err)
} }
defer file.Close() defer file.Close()
return decodeSettings(file, configPath)
}
// DecodeSettings applies the same strict profile rules to captured bytes.
func DecodeSettings(data []byte, label string) (Settings, error) {
return decodeSettings(bytes.NewReader(data), label)
}
func decodeSettings(input io.Reader, configPath string) (Settings, error) {
var settings Settings var settings Settings
decoder := json.NewDecoder(file) decoder := json.NewDecoder(input)
decoder.DisallowUnknownFields() decoder.DisallowUnknownFields()
if err := decoder.Decode(&settings); err != nil { if err := decoder.Decode(&settings); err != nil {
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err) return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
@@ -247,6 +457,20 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
if strings.TrimSpace(settings.Product) == "" { if strings.TrimSpace(settings.Product) == "" {
return Settings{}, fmt.Errorf("profile %q: product is required", configPath) return Settings{}, fmt.Errorf("profile %q: product is required", configPath)
} }
if delivery := settings.Delivery; delivery != nil {
if delivery.LegacyTokenFile != nil {
return Settings{}, fmt.Errorf("profile %q: delivery.token_file has moved to delivery.credentials.local.token_file", configPath)
}
if delivery.LegacyTokenEnv != nil {
return Settings{}, fmt.Errorf("profile %q: delivery.token_env has moved to delivery.credentials.ci.token_environment_variable", configPath)
}
}
if source := settings.SourceSpec(); source != nil {
_, err := releaseidentity.NormalizeSource(settings.ModuleDir, source)
if err != nil {
return Settings{}, fmt.Errorf("profile %q: source selection: %w", configPath, err)
}
}
if settings.Remote == "" { if settings.Remote == "" {
settings.Remote = "origin" settings.Remote = "origin"
} }

View File

@@ -19,6 +19,33 @@ func TestParse(t *testing.T) {
if invocation.Command != VersionCommand { if invocation.Command != VersionCommand {
t.Fatalf("Parse() command = %q, want %q", invocation.Command, VersionCommand) t.Fatalf("Parse() command = %q, want %q", invocation.Command, VersionCommand)
} }
reconcile, err := Parse([]string{"reconcile", "--record", "records/release record's.json", "--json"})
if err != nil {
t.Fatal(err)
}
if reconcile.Command != ReconcileAction || reconcile.RecordPath != "records/release record's.json" || !reconcile.JSON {
t.Fatalf("Parse(reconcile) = %#v", reconcile)
}
attempts, err := Parse([]string{"publication-attempts", "--repo", "repository with spaces", "--record-dir", "records with spaces", "--json"})
if err != nil {
t.Fatal(err)
}
if attempts.Command != PublicationAttemptsAction || attempts.Repository != "repository with spaces" || attempts.RecordDir != "records with spaces" || !attempts.JSON {
t.Fatalf("Parse(publication-attempts) = %#v", attempts)
}
for _, args := range [][]string{
{"reconcile"},
{"reconcile", "record.json"},
{"reconcile", "--record", "record.json", "--repo", "."},
{"reconcile", "--record", "record.json", "--record-dir", "records"},
{"reconcile", "--record", "record.json", "VERSION"},
{"publication-attempts", "--record", "record.json"},
{"publication-attempts", "VERSION"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%q) succeeded, want a usage error", args)
}
}
check, err := Parse([]string{"check", "--repo", "repository with spaces", "--config", "profiles/release config.json", "v1.2.3"}) check, err := Parse([]string{"check", "--repo", "repository with spaces", "--config", "profiles/release config.json", "v1.2.3"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -26,17 +53,24 @@ func TestParse(t *testing.T) {
if check.Command != CheckAction || check.Repository != "repository with spaces" || check.ConfigPath != "profiles/release config.json" || check.Version != "v1.2.3" { if check.Command != CheckAction || check.Repository != "repository with spaces" || check.ConfigPath != "profiles/release config.json" || check.Version != "v1.2.3" {
t.Fatalf("Parse(check) = %#v", check) t.Fatalf("Parse(check) = %#v", check)
} }
publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "v1.2.4"}) publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "--record-dir", "attempt records", "v1.2.4"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.Version != "v1.2.4" { if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.RecordDir != "attempt records" || publish.Version != "v1.2.4" {
t.Fatalf("Parse(publish) = %#v", publish) t.Fatalf("Parse(publish) = %#v", publish)
} }
if _, err := Parse([]string{"check", "--record-dir", "attempt records", "v1.2.4"}); err == nil {
t.Fatal("Parse(check) accepted the publication-only record directory")
}
publishMapped, err := Parse([]string{"publish", "--repo", "candidate", "--expected-module", "integrations/ckconfig", "v1.2.4"}) publishMapped, err := Parse([]string{"publish", "--repo", "candidate", "--expected-module", "integrations/ckconfig", "v1.2.4"})
if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" { if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" {
t.Fatalf("Parse(publish --expected-module) = %#v, error = %v", publishMapped, err) t.Fatalf("Parse(publish --expected-module) = %#v, error = %v", publishMapped, err)
} }
publishSource, err := Parse([]string{"publish", "--expected-source", "config", "2026-12-01"})
if err != nil || publishSource.ExpectedSource != "config" || publishSource.Version != "2026-12-01" {
t.Fatalf("Parse(publish --expected-source) = %#v, error = %v", publishSource, err)
}
build, err := Parse([]string{"build", "--repo", "candidate", "--config", "releasekit.json", "--output", "output with spaces", "v1.2.5"}) build, err := Parse([]string{"build", "--repo", "candidate", "--config", "releasekit.json", "--output", "output with spaces", "v1.2.5"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -68,8 +102,9 @@ func TestParse(t *testing.T) {
if _, err := Parse([]string{"ci-deliver", "--commit", "abc123", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "full Git object ID") { if _, err := Parse([]string{"ci-deliver", "--commit", "abc123", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "full Git object ID") {
t.Fatalf("Parse(ci-deliver with abbreviated commit) error = %v, want full object ID error", err) t.Fatalf("Parse(ci-deliver with abbreviated commit) error = %v, want full object ID error", err)
} }
if _, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/latest"}); err == nil || !strings.Contains(err.Error(), "stable vMAJOR.MINOR.PATCH") { calendar, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "config/2026-12-01"})
t.Fatalf("Parse(ci-deliver unstable terminal tag) error = %v", err) if err != nil || calendar.Version != "2026-12-01" || calendar.ExpectedTag != "config/2026-12-01" {
t.Fatalf("Parse(ci-deliver calendar tag) = %#v, error = %v", calendar, err)
} }
if _, err := Parse([]string{"check", "v1.2.3", "--repo", "repository"}); err == nil { if _, err := Parse([]string{"check", "v1.2.3", "--repo", "repository"}); err == nil {
t.Fatal("Parse accepted a flag after the version") t.Fatal("Parse accepted a flag after the version")
@@ -122,6 +157,36 @@ func TestLoadSettingsResolvesPathsAndPreservesArguments(t *testing.T) {
} }
} }
func TestParseValidateSelectsAndDeduplicatesOperations(t *testing.T) {
invocation, err := Parse([]string{"validate", "--context", "ci", "--operation", "delivery", "--operation", "go", "--operation", "delivery", "--offline", "--assets", "dist", "--json"})
if err != nil || invocation.Command != ValidateAction || invocation.Context != "ci" || !invocation.Offline || !invocation.JSON || invocation.AssetsDir != "dist" || len(invocation.Operations) != 2 || invocation.Operations[0] != "delivery" || invocation.Operations[1] != "go" {
t.Fatalf("invocation = %+v, error = %v", invocation, err)
}
for _, args := range [][]string{{"validate", "v1.0.0"}, {"validate", "--context", "other"}, {"validate", "--operation", "other"}} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%q) accepted invalid arguments", args)
}
}
}
func TestLoadSettingsReportsObsoleteDeliveryCredentials(t *testing.T) {
for _, test := range []struct{ field, replacement string }{
{"token_file", "delivery.credentials.local.token_file"},
{"token_env", "delivery.credentials.ci.token_environment_variable"},
} {
t.Run(test.field, func(t *testing.T) {
repo := t.TempDir()
profile := `{"product":"Example","delivery":{"` + test.field + `":null}}`
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(profile), 0600); err != nil {
t.Fatal(err)
}
if _, err := LoadSettings(repo, ""); err == nil || !strings.Contains(err.Error(), test.replacement) {
t.Fatalf("legacy field error = %v, want migration to %s", err, test.replacement)
}
})
}
}
func TestLoadSettingsDefaultsRemoteAndConfigPath(t *testing.T) { func TestLoadSettingsDefaultsRemoteAndConfigPath(t *testing.T) {
repoDir := t.TempDir() repoDir := t.TempDir()
contents := `{"product":"Example"}` contents := `{"product":"Example"}`

View File

@@ -0,0 +1,81 @@
package cli
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
type CredentialContext string
const (
LocalCredentials CredentialContext = "local"
CICredentials CredentialContext = "ci"
)
// CredentialSource identifies the selected source without exposing its token.
type CredentialSource struct {
Context CredentialContext
Source string
}
// ResolveDeliveryCredential reads only the credential selected by context.
func ResolveDeliveryCredential(repositoryDir string, credentials *DeliveryCredentials, context CredentialContext) (string, CredentialSource, error) {
source := CredentialSource{Context: context}
switch context {
case LocalCredentials:
if credentials == nil || credentials.Local == nil || strings.TrimSpace(credentials.Local.TokenFile) == "" {
return "", source, errors.New("local delivery requires delivery.credentials.local.token_file")
}
token, name, err := readTokenFile(repositoryDir, credentials.Local.TokenFile, "local delivery")
source.Source = name
return token, source, err
case CICredentials:
if credentials == nil || credentials.CI == nil {
return "", source, errors.New("CI delivery requires delivery.credentials.ci")
}
name := credentials.CI.TokenEnvironmentVariable
if strings.TrimSpace(name) == "" {
name = "RELEASEKIT_DELIVERY_TOKEN"
}
source.Source = name
token, ok := os.LookupEnv(name)
if !ok || strings.TrimSpace(token) == "" {
return "", source, fmt.Errorf("CI delivery requires a non-empty token in environment variable %s", git.DisplayDiagnostic(name))
}
return strings.TrimSpace(token), source, nil
default:
return "", source, errors.New("unknown delivery credential context")
}
}
// ResolveWoodpeckerCredential reads only the explicitly selected local CI token.
func ResolveWoodpeckerCredential(repositoryDir string, settings *WoodpeckerSettings) (string, CredentialSource, error) {
source := CredentialSource{Context: LocalCredentials}
if settings == nil || strings.TrimSpace(settings.TokenFile) == "" {
return "", source, errors.New("rehearsal requires rehearsal.woodpecker.token_file")
}
token, name, err := readTokenFile(repositoryDir, settings.TokenFile, "Woodpecker")
source.Source = name
return token, source, err
}
func readTokenFile(repositoryDir, name, label string) (string, string, error) {
if !filepath.IsAbs(name) {
name = filepath.Join(repositoryDir, name)
}
safeName := git.DisplayDiagnostic(name)
contents, err := os.ReadFile(name)
if err != nil {
return "", safeName, fmt.Errorf("read %s token file: %s", label, git.DisplayDiagnostic(err.Error()))
}
token := strings.TrimSpace(string(contents))
if token == "" {
return "", safeName, fmt.Errorf("%s token file %q is empty or blank", label, safeName)
}
return token, safeName, nil
}

View File

@@ -2,21 +2,24 @@ package cli
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact" "go.maximumdirect.net/releasekit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/releaseidentity"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/versioncontract"
"golang.org/x/mod/module"
) )
const BuildReceiptName = ".releasekit-build.json" const BuildReceiptName = ".releasekit-build.json"
const BuildReceiptSchemaVersion = 1 const BuildReceiptSchemaVersion = 2
type ReceiptTarget struct { type ReceiptTarget struct {
OS string `json:"os"` OS string `json:"os"`
@@ -34,6 +37,14 @@ type ReceiptArtifact struct {
type BuildReceipt struct { type BuildReceipt struct {
SchemaVersion int `json:"schema_version"` SchemaVersion int `json:"schema_version"`
RepositoryDir string `json:"repository_dir"` RepositoryDir string `json:"repository_dir"`
SourceDir string `json:"source_dir"`
SourceSubdir string `json:"source_subdir"`
GoEnabled bool `json:"go_enabled"`
Publication string `json:"publication_mode"`
VersionFormat string `json:"version_format"`
VersionPrefix string `json:"version_prefix"`
IdentityKind string `json:"identity_kind"`
NotePath string `json:"note_path,omitempty"`
ModuleDir string `json:"module_dir"` ModuleDir string `json:"module_dir"`
ModulePath string `json:"module_path"` ModulePath string `json:"module_path"`
Tag string `json:"tag"` Tag string `json:"tag"`
@@ -49,6 +60,10 @@ type BuildReceipt struct {
} }
func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) { func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
return writeBuildReceipt(outputDir, receipt, os.Remove)
}
func writeBuildReceipt(outputDir string, receipt BuildReceipt, remove func(string) error) (resultPath string, resultErr error) {
resolvedDir, err := filepath.Abs(outputDir) resolvedDir, err := filepath.Abs(outputDir)
if err != nil { if err != nil {
return "", fmt.Errorf("resolve build receipt directory: %w", err) return "", fmt.Errorf("resolve build receipt directory: %w", err)
@@ -67,7 +82,11 @@ func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
return "", fmt.Errorf("create temporary build receipt: %w", err) return "", fmt.Errorf("create temporary build receipt: %w", err)
} }
temporaryPath := temporary.Name() temporaryPath := temporary.Name()
defer os.Remove(temporaryPath) defer func() {
if err := remove(temporaryPath); err != nil && !errors.Is(err, os.ErrNotExist) {
resultErr = errors.Join(resultErr, fmt.Errorf("remove temporary build receipt %q: %w", temporaryPath, err))
}
}()
if _, err := temporary.Write(contents); err != nil { if _, err := temporary.Write(contents); err != nil {
_ = temporary.Close() _ = temporary.Close()
return "", fmt.Errorf("write build receipt: %w", err) return "", fmt.Errorf("write build receipt: %w", err)
@@ -105,7 +124,6 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
defer file.Close() defer file.Close()
var receipt BuildReceipt var receipt BuildReceipt
decoder := json.NewDecoder(file) decoder := json.NewDecoder(file)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&receipt); err != nil { if err := decoder.Decode(&receipt); err != nil {
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err) return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
} }
@@ -161,11 +179,8 @@ func validateBuildReceipt(receipt BuildReceipt) error {
if receipt.SchemaVersion != BuildReceiptSchemaVersion { if receipt.SchemaVersion != BuildReceiptSchemaVersion {
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion) return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
} }
if !versioncontract.ValidStableVersion(receipt.Version) { if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.SourceDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return fmt.Errorf("build receipt has invalid version %q", receipt.Version) return errors.New("build receipt repository, source, module, and output directories must be absolute")
}
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository, module, and output directories must be absolute")
} }
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" { if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
return errors.New("build receipt is missing module path or full tag") return errors.New("build receipt is missing module path or full tag")
@@ -182,32 +197,15 @@ func validateBuildReceipt(receipt BuildReceipt) error {
if len(receipt.Targets) == 0 || len(receipt.Artifacts) != len(receipt.Targets) { if len(receipt.Targets) == 0 || len(receipt.Artifacts) != len(receipt.Targets) {
return errors.New("build receipt target and artifact counts do not match") return errors.New("build receipt target and artifact counts do not match")
} }
seenTargets := make(map[ReceiptTarget]bool, len(receipt.Targets)) declarations := make([]artifact.Declaration, 0, len(receipt.Artifacts))
seenArtifacts := make(map[ReceiptTarget]bool, len(receipt.Artifacts)) for _, item := range receipt.Artifacts {
targets := make([]artifact.Target, 0, len(receipt.Targets)) declarations = append(declarations, artifact.Declaration{Target: artifact.Target{OS: item.Target.OS, Arch: item.Target.Arch}, Filename: item.Filename})
for _, target := range receipt.Targets {
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
return fmt.Errorf("build receipt has unsafe target %q/%q", target.OS, target.Arch)
}
if seenTargets[target] {
return fmt.Errorf("build receipt repeats target %s/%s", target.OS, target.Arch)
}
seenTargets[target] = true
targets = append(targets, artifact.Target{OS: target.OS, Arch: target.Arch})
} }
declarations := artifact.ExpectedBuild(receipt.BinaryName, receipt.Version, targets) if err := artifact.ValidateDeclarations(receipt.BinaryName, receipt.Version, parseStoredTargets(receipt.Targets), declarations); err != nil {
wantByTarget := make(map[ReceiptTarget]string, len(declarations)) return fmt.Errorf("build receipt: %w", err)
for _, declaration := range declarations {
target := ReceiptTarget{OS: declaration.Target.OS, Arch: declaration.Target.Arch}
wantByTarget[target] = declaration.Filename
} }
for _, artifact := range receipt.Artifacts { for _, artifact := range receipt.Artifacts {
if !seenTargets[artifact.Target] || seenArtifacts[artifact.Target] { if filepath.Base(artifact.Filename) != artifact.Filename {
return fmt.Errorf("build receipt has an unexpected artifact target %s/%s", artifact.Target.OS, artifact.Target.Arch)
}
seenArtifacts[artifact.Target] = true
wantName := wantByTarget[artifact.Target]
if artifact.Filename != wantName || filepath.Base(artifact.Filename) != artifact.Filename {
return fmt.Errorf("build receipt has invalid artifact filename %q", artifact.Filename) return fmt.Errorf("build receipt has invalid artifact filename %q", artifact.Filename)
} }
wantPath := filepath.Join(receipt.OutputDir, artifact.Filename) wantPath := filepath.Join(receipt.OutputDir, artifact.Filename)
@@ -224,16 +222,65 @@ func validateBuildReceipt(receipt BuildReceipt) error {
func validateRecordedIdentity(receipt BuildReceipt) error { func validateRecordedIdentity(receipt BuildReceipt) error {
repositoryDir := filepath.Clean(receipt.RepositoryDir) repositoryDir := filepath.Clean(receipt.RepositoryDir)
moduleDir := filepath.Clean(receipt.ModuleDir) moduleDir := filepath.Clean(receipt.ModuleDir)
relative, err := filepath.Rel(repositoryDir, moduleDir) sourceDir := filepath.Clean(receipt.SourceDir)
relative, err := filepath.Rel(repositoryDir, sourceDir)
if err != nil { if err != nil {
return fmt.Errorf("relate module directory to repository: %w", err) return fmt.Errorf("relate module directory to repository: %w", err)
} }
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
return errors.New("module directory is outside repository") return errors.New("source directory is outside repository")
} }
if relative == "" { if relative == "" {
relative = "." relative = "."
} }
if filepath.ToSlash(relative) != receipt.SourceSubdir || sourceDir != moduleDir || !receipt.GoEnabled {
return errors.New("source and module selections do not match")
}
if err := module.CheckImportPath(receipt.ModulePath); err != nil {
return fmt.Errorf("invalid module path: %w", err)
}
if _, _, ok := module.SplitPathVersion(receipt.ModulePath); !ok {
return errors.New("invalid module path major")
}
if receipt.Publication != "source" && receipt.Publication != "go-module" {
return errors.New("invalid publication mode")
}
if receipt.VersionFormat == "" {
return errors.New("missing version format")
}
_, err = releaseidentity.NormalizeSource("", &releaseidentity.SourceSpec{
Dir: receipt.SourceSubdir, GoEnabled: receipt.GoEnabled, Publication: receipt.Publication,
VersionFormat: receipt.VersionFormat, VersionPrefix: &receipt.VersionPrefix,
})
if err != nil {
return fmt.Errorf("invalid source selection: %w", err)
}
if receipt.Publication == "go-module" && (receipt.VersionFormat != "semver" || receipt.VersionPrefix != "v") {
return errors.New("Go module publication requires prefixed semantic versions")
}
if receipt.IdentityKind == "diagnostic" {
attempt := strings.TrimPrefix(receipt.Version, "releasekit-test-")
if !strings.HasPrefix(receipt.Version, "releasekit-test-") || len(attempt) != 32 || strings.ToLower(attempt) != attempt {
return errors.New("invalid diagnostic version")
}
selector := strings.TrimSuffix(strings.TrimPrefix(receipt.Tag, "releasekit-test/"), "/"+attempt)
if _, err := hex.DecodeString(attempt); err != nil || !strings.HasPrefix(receipt.Tag, "releasekit-test/") || !strings.HasSuffix(receipt.Tag, "/"+attempt) || selector == "" || strings.Contains(selector, "/") {
return errors.New("invalid diagnostic tag")
}
return nil
}
if receipt.IdentityKind != "production" || !versioncontract.ValidIdentifier(receipt.Version, receipt.VersionFormat, receipt.VersionPrefix) {
return errors.New("invalid production identity or version")
}
if receipt.NotePath != path.Join(receipt.SourceSubdir, "docs", "releases", receipt.Version+".md") {
return errors.New("release note path does not match source and version")
}
if receipt.Publication == "source" {
if receipt.Tag != receipt.Version && !strings.HasSuffix(receipt.Tag, "/"+receipt.Version) {
return errors.New("full tag does not match source version")
}
return nil
}
identity, err := releaseidentity.Derive(releaseidentity.Selection{ identity, err := releaseidentity.Derive(releaseidentity.Selection{
RepositoryDir: repositoryDir, RepositoryDir: repositoryDir,
ModuleDir: moduleDir, ModuleDir: moduleDir,

View File

@@ -4,12 +4,70 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
) )
func TestWriteBuildReceiptReportsTemporaryCleanup(t *testing.T) {
for _, mode := range []string{"renamed", "cleanup failure", "install and cleanup failure"} {
t.Run(mode, func(t *testing.T) {
repository := t.TempDir()
output := t.TempDir()
name := "app-v1.2.3-linux-amd64"
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repository, ModuleDir: repository,
SourceDir: repository, SourceSubdir: ".", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
ModulePath: "example.com/receipt", Tag: "v1.2.3", CandidateCommit: strings.Repeat("a", 40),
Version: "v1.2.3", MainPackage: ".", BinaryName: "app", Compiler: "go fixture",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
Artifacts: []ReceiptArtifact{{Path: filepath.Join(output, name), Filename: name, Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64)}},
}
if mode == "install and cleanup failure" {
blocked := filepath.Join(output, BuildReceiptName)
if err := os.Mkdir(blocked, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(blocked, "keep"), nil, 0o600); err != nil {
t.Fatal(err)
}
}
cleanupErr := errors.New("cleanup failed")
var temporaryPath string
remove := func(path string) error {
temporaryPath = path
err := os.Remove(path)
if mode == "renamed" {
return err
}
return cleanupErr
}
path, err := writeBuildReceipt(output, receipt, remove)
if mode == "renamed" {
if err != nil || path != filepath.Join(output, BuildReceiptName) {
t.Fatalf("renamed receipt = %q, %v", path, err)
}
return
}
if !errors.Is(err, cleanupErr) || temporaryPath == "" || !strings.Contains(err.Error(), temporaryPath) {
t.Fatalf("cleanup path = %q, error = %v", temporaryPath, err)
}
if mode == "cleanup failure" && path != filepath.Join(output, BuildReceiptName) {
t.Fatalf("installed receipt path = %q", path)
}
if mode == "install and cleanup failure" {
var pathErr *os.PathError
if !errors.As(err, &pathErr) {
t.Fatalf("install cause missing: %v", err)
}
}
})
}
}
func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) { func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
name string name string
@@ -40,6 +98,14 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
RepositoryDir: repositoryDir, RepositoryDir: repositoryDir,
SourceDir: moduleDir,
SourceSubdir: test.moduleDir,
GoEnabled: true,
Publication: "go-module",
VersionFormat: "semver",
VersionPrefix: "v",
IdentityKind: "production",
NotePath: path.Join(test.moduleDir, "docs/releases/v1.2.3.md"),
ModuleDir: moduleDir, ModuleDir: moduleDir,
ModulePath: test.modulePath, ModulePath: test.modulePath,
Tag: test.tag, Tag: test.tag,
@@ -58,6 +124,22 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
fields["future_field"] = true
data, err = json.Marshal(fields)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
loaded, err := LoadBuildReceipt(path) loaded, err := LoadBuildReceipt(path)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -103,15 +185,15 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
} }
} }
func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) { func TestLoadBuildReceiptRejectsOldSchemasAndMultipleValues(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
name string name string
body string body string
want string want string
}{ }{
{name: "unknown field", body: `{"schema_version":1,"unexpected":true}`, want: "unknown field"}, {name: "old receipt", body: `{"schema_version":1,"unexpected":true}`, want: "regenerate it with the updated build command"},
{name: "unversioned receipt", body: `{}`, want: "regenerate it with the updated build command"}, {name: "unversioned receipt", body: `{}`, want: "regenerate it with the updated build command"},
{name: "unknown schema", body: `{"schema_version":2}`, want: "regenerate it with the updated build command"}, {name: "unknown schema", body: `{"schema_version":3}`, want: "regenerate it with the updated build command"},
{name: "multiple values", body: `{} {}`, want: "multiple JSON values"}, {name: "multiple values", body: `{} {}`, want: "multiple JSON values"},
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
@@ -135,6 +217,7 @@ func TestWriteBuildReceiptRejectsInconsistentRecordedIdentity(t *testing.T) {
outputDir := t.TempDir() outputDir := t.TempDir()
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
SourceDir: moduleDir, SourceSubdir: "integrations/ckconfig", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "integrations/ckconfig/docs/releases/v1.2.3.md",
RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3", RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper", CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture", OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
@@ -159,6 +242,7 @@ func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
digest := sha256.Sum256(contents) digest := sha256.Sum256(contents)
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
SourceDir: repositoryDir, SourceSubdir: ".", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3", RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper", CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture", OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
@@ -188,3 +272,26 @@ func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err) t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err)
} }
} }
func TestDiagnosticBuildReceiptRoundTrip(t *testing.T) {
repo, output := t.TempDir(), t.TempDir()
attempt := strings.Repeat("a", 32)
version := "releasekit-test-" + attempt
name := "helper-" + version + "-linux-amd64"
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repo, SourceDir: repo, SourceSubdir: ".",
GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "diagnostic",
ModuleDir: repo, ModulePath: "example.com/receipt", Tag: "releasekit-test/root/" + attempt,
CandidateCommit: strings.Repeat("b", 40), Version: version, MainPackage: ".", BinaryName: "helper", Compiler: "go version fixture",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
Artifacts: []ReceiptArtifact{{Path: filepath.Join(output, name), Filename: name, Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64)}},
}
path, err := WriteBuildReceipt(output, receipt)
if err != nil {
t.Fatal(err)
}
loaded, err := LoadBuildReceipt(path)
if err != nil || loaded.IdentityKind != "diagnostic" || loaded.Version != version || loaded.Tag != receipt.Tag {
t.Fatalf("diagnostic receipt = %+v, error = %v", loaded, err)
}
}

View File

@@ -0,0 +1,45 @@
package cli
import (
"context"
"errors"
"fmt"
"strings"
)
// ResolveRehearsalRecoveryCredentials selects local credentials from the
// captured profile, or explicit file overrides without loading that profile.
func ResolveRehearsalRecoveryCredentials(ctx context.Context, repository, commit, profilePath, profileSHA256, deliveryOverride, woodpeckerOverride string) (string, string, error) {
var delivery *DeliveryCredentials
var woodpecker *WoodpeckerSettings
if strings.TrimSpace(deliveryOverride) == "" || strings.TrimSpace(woodpeckerOverride) == "" {
captured, err := CaptureCommittedProfile(ctx, repository, commit, profilePath)
if err != nil {
return "", "", fmt.Errorf("load recorded rehearsal profile: %w", err)
}
if captured.Commit != commit || captured.Path != profilePath || captured.SHA256 != profileSHA256 {
return "", "", errors.New("recorded rehearsal profile identity does not match")
}
if captured.Settings.Delivery != nil {
delivery = captured.Settings.Delivery.Credentials
}
if captured.Settings.Rehearsal != nil {
woodpecker = captured.Settings.Rehearsal.Woodpecker
}
}
if strings.TrimSpace(deliveryOverride) != "" {
delivery = &DeliveryCredentials{Local: &LocalCredential{TokenFile: deliveryOverride}}
}
if strings.TrimSpace(woodpeckerOverride) != "" {
woodpecker = &WoodpeckerSettings{TokenFile: woodpeckerOverride}
}
deliveryToken, _, err := ResolveDeliveryCredential(repository, delivery, LocalCredentials)
if err != nil {
return "", "", err
}
woodpeckerToken, _, err := ResolveWoodpeckerCredential(repository, woodpecker)
if err != nil {
return "", "", err
}
return deliveryToken, woodpeckerToken, nil
}

View File

@@ -0,0 +1,56 @@
package cli
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestRecoveryCredentialsUseCapturedProfileOrExplicitOverrides(t *testing.T) {
repo := t.TempDir()
run := func(args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v: %s", args, err, out)
}
}
run("init", "--initial-branch=main")
run("config", "user.name", "ReleaseKit Test")
run("config", "user.email", "releasekit@example.test")
profile := `{"product":"Example","source":{},"delivery":{"credentials":{"local":{"token_file":"forge-token"}}},"rehearsal":{"woodpecker":{"token_file":"ci-token"}}}`
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(profile), 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "captured profile")
captured, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(`{"product":"Different"}`), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "forge-token"), []byte(" forge-secret \n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "ci-token"), []byte(" ci-secret \n"), 0600); err != nil {
t.Fatal(err)
}
forge, wood, err := ResolveRehearsalRecoveryCredentials(t.Context(), repo, captured.Commit, captured.Path, captured.SHA256, "", "")
if err != nil || forge != "forge-secret" || wood != "ci-secret" {
t.Fatalf("credentials selected=%t/%t error=%v", forge == "forge-secret", wood == "ci-secret", err)
}
if _, _, err := ResolveRehearsalRecoveryCredentials(t.Context(), repo, captured.Commit, captured.Path, strings.Repeat("0", 64), "", ""); err == nil {
t.Fatal("accepted a different captured profile digest")
}
forgePath := filepath.Join(repo, "forge-token")
woodPath := filepath.Join(repo, "ci-token")
forge, wood, err = ResolveRehearsalRecoveryCredentials(t.Context(), filepath.Join(t.TempDir(), "missing"), captured.Commit, captured.Path, captured.SHA256, forgePath, woodPath)
if err != nil || forge != "forge-secret" || wood != "ci-secret" {
t.Fatalf("override selection=%t/%t error=%v", forge == "forge-secret", wood == "ci-secret", err)
}
}

View File

@@ -0,0 +1,51 @@
package cli
import (
"os"
"path/filepath"
"testing"
)
func TestProfileSourceSelection(t *testing.T) {
tests := []struct {
name, fields string
explicit, goEnabled bool
mode, format string
emptyPrefix, invalid bool
}{
{name: "legacy"},
{name: "null is omitted", fields: `,"source":null,"go":null,"publication":null,"version":null`},
{name: "source root", fields: `,"source":{}`, explicit: true},
{name: "explicit unprefixed tag", fields: `,"source":{"tag_prefix":""}`, explicit: true},
{name: "Go application", fields: `,"go":{}`, explicit: true, goEnabled: true},
{name: "Go module", fields: `,"go":{},"publication":{"mode":"go-module"}`, explicit: true, goEnabled: true, mode: "go-module"},
{name: "calendar with explicit empty prefix", fields: `,"version":{"format":"date","prefix":""}`, explicit: true, format: "date", emptyPrefix: true},
{name: "unknown source field", fields: `,"source":{"unknown":true}`, invalid: true},
{name: "module publication without Go", fields: `,"publication":{"mode":"go-module"}`, invalid: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "releasekit.json"), []byte(`{"product":"test"`+tt.fields+`}`), 0600); err != nil {
t.Fatal(err)
}
settings, err := LoadSettings(dir, "")
if (err != nil) != tt.invalid {
t.Fatalf("LoadSettings error = %v", err)
}
if tt.invalid {
return
}
source := settings.SourceSpec()
if (source != nil) != tt.explicit {
t.Fatalf("source = %+v", source)
}
if source != nil && (source.GoEnabled != tt.goEnabled || string(source.Publication) != tt.mode || string(source.VersionFormat) != tt.format || (source.VersionPrefix != nil && *source.VersionPrefix == "") != tt.emptyPrefix) {
t.Fatalf("source = %+v", source)
}
if tt.name == "explicit unprefixed tag" && (source.TagPrefix == nil || *source.TagPrefix != "") {
t.Fatalf("tag prefix was not preserved: %+v", source)
}
})
}
}

View File

@@ -7,7 +7,7 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T) { func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T) {
@@ -20,7 +20,7 @@ func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T)
defer server.Close() defer server.Close()
settings := cli.Settings{Product: "Example Product", settings := cli.Settings{Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
} }
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
for _, args := range [][]string{ for _, args := range [][]string{

View File

@@ -10,13 +10,16 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"syscall" "syscall"
"time"
"gitea.maximumdirect.net/eric/ReleaseKit" "go.maximumdirect.net/releasekit"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact" "go.maximumdirect.net/releasekit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git" "go.maximumdirect.net/releasekit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
func main() { func main() {
@@ -32,6 +35,15 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage) fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage)
return 2 return 2
} }
if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction {
return runRecovery(ctx, invocation, stdout, stderr)
}
if invocation.Command == cli.TestAction || invocation.Command == cli.TestResumeAction || invocation.Command == cli.TestCleanupAction {
return runRehearsal(ctx, invocation, stdout, stderr)
}
if invocation.Command == cli.ValidateAction {
return runValidate(ctx, invocation, stdout)
}
if invocation.Command != cli.VersionCommand { if invocation.Command != cli.VersionCommand {
invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository) invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository)
if err != nil { if err != nil {
@@ -45,102 +57,9 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stdout, "releasekit %s\n", buildinfo.Version()) fmt.Fprintf(stdout, "releasekit %s\n", buildinfo.Version())
return 0 return 0
case cli.CheckAction, cli.PublishAction: case cli.CheckAction, cli.PublishAction:
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath) return runCheckOrPublish(ctx, invocation, stdout, stderr)
if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2
}
request := candidateRequest(invocation, settings, stderr)
if invocation.Command == cli.PublishAction {
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
return 2
}
request.ExpectedPushURL = settings.ExpectedPushURL
fmt.Fprintf(stderr, "validating and publishing module %s version %s\n", selectedModuleLabel(settings.ModuleDir), invocation.Version)
result, err := releasekit.Publish(ctx, request)
if err != nil {
fmt.Fprintf(stderr, "publication state=%s phase=%s module=%s module-dir=%s version=%s tag=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.TagObject, result.Endpoint, candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
if result.State == releasekit.PublicationUnknown {
return 3
}
return 1
}
fmt.Fprintf(stdout, "published %s as %s at %s (tag object %s)\n", result.Version, result.Tag, result.CandidateCommit, result.TagObject)
return 0
}
candidate, err := releasekit.Check(ctx, request)
if err != nil {
fmt.Fprintf(stderr, "check failed module=%s module-dir=%s version=%s tag=%s commit=%s: %s\n", candidate.ModulePath, candidate.ModuleDir, candidate.Version, candidate.Tag, candidate.Commit, candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
return 1
}
fmt.Fprintf(stdout, "local candidate module %s version %s tag %s at %s is valid\n", candidate.ModulePath, candidate.Version, candidate.Tag, candidate.Commit)
return 0
case cli.BuildAction: case cli.BuildAction:
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath) return runBuild(ctx, invocation, stdout, stderr)
if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2
}
if settings.Build == nil {
fmt.Fprintln(stderr, "build requires build settings in the profile")
return 2
}
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
Version: invocation.Version,
Spec: *configuredBuildSpec(settings.Build),
OutputDir: invocation.OutputDir,
Output: stderr,
})
if result.OutputDir != "" && len(result.Targets) != 0 {
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
fmt.Fprintf(stderr, "%v\n", receiptErr)
return 1
}
}
if err != nil {
fmt.Fprintf(stderr, "build failed module=%s module-dir=%s version=%s tag=%s commit=%s: %v\n", result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, err)
for _, artifact := range result.Artifacts {
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
}
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
return 1
}
if len(result.Targets) == 0 {
fmt.Fprintf(stdout, "no build targets selected for module %s version %s tag %s at %s\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit)
return 0
}
receipt := receiptFromBuild(result)
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
if err != nil {
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
return 1
}
stored, err := cli.LoadBuildReceipt(receiptPath)
if err != nil {
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
return 1
}
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
return 1
}
fmt.Fprintf(stdout, "built %d artifacts for module %s version %s tag %s at %s with %s\n", len(result.Artifacts), result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.Compiler)
for _, artifact := range result.Artifacts {
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
}
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
return 0
case cli.DeliveryAction: case cli.DeliveryAction:
return runDelivery(ctx, invocation, stdout, stderr) return runDelivery(ctx, invocation, stdout, stderr)
case cli.CIDeliveryAction: case cli.CIDeliveryAction:
@@ -149,10 +68,218 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
return 2 return 2
} }
func runCheckOrPublish(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2
}
request := candidateRequest(invocation, settings, stderr)
if invocation.Command == cli.PublishAction {
if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2
}
request.ExpectedPushURL = settings.ExpectedPushURL
request.PublicationRecordDir = invocation.RecordDir
fmt.Fprintf(stderr, "validating and publishing module %s version %s\n", selectedModuleLabel(settings.ModuleDir), invocation.Version)
result, err := releasekit.Publish(ctx, request)
reportPublicationRecord(ctx, result, err, stderr)
if err != nil {
fmt.Fprintf(stderr, "publication state=%s phase=%s module=%s module-dir=%s version=%s tag=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.TagObject, git.DisplayURL(result.Endpoint), candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
if result.State == releasekit.PublicationUnknown {
return 3
}
return 1
}
fmt.Fprintf(stdout, "published %s as %s at %s (tag object %s)\n", result.Version, result.Tag, result.CandidateCommit, result.TagObject)
return 0
}
candidate, err := releasekit.Check(ctx, request)
if err != nil {
fmt.Fprintf(stderr, "check failed module=%s module-dir=%s version=%s tag=%s commit=%s: %s\n", candidate.ModulePath, candidate.ModuleDir, candidate.Version, candidate.Tag, candidate.Commit, candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
return 1
}
fmt.Fprintf(stdout, "local candidate module %s version %s tag %s at %s is valid\n", candidate.ModulePath, candidate.Version, candidate.Tag, candidate.Commit)
return 0
}
func reportPublicationRecord(ctx context.Context, result releasekit.PublicationResult, publicationErr error, stderr io.Writer) {
if result.RecordError != nil {
fmt.Fprintf(stderr, "publication record warning: %s\n", git.DisplayError(result.RecordError))
}
if result.RecordPath == "" {
return
}
fmt.Fprintf(stderr, "publication record saved: %s\n", git.DisplayDiagnostic(result.RecordPath))
if publicationErr == nil || !publicationOffersRecovery(result.Phase) {
return
}
// Handoff preparation follows the failed publication and has its own bounded
// lifetime, including when publication's context was canceled.
handoffContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
command, err := selectedPublicationRecoveryCommand(handoffContext, result)
if err != nil {
fmt.Fprintf(stderr, "recovery tool preparation warning: %s\n", git.DisplayError(err))
command, err = publicationRecoveryCommand(result.RecordPath)
if err != nil {
fmt.Fprintf(stderr, "recovery command unavailable: %s\n", git.DisplayError(err))
fmt.Fprintln(stderr, "Use your selected supported ReleaseKit CLI with this record if the original executable is unavailable.")
return
}
}
fmt.Fprintf(stderr, "recovery command: %s\n", git.DisplayDiagnostic(command))
fmt.Fprintln(stderr, "If this entry point is unavailable, use your selected supported ReleaseKit CLI with the same record.")
}
func selectedPublicationRecoveryCommand(ctx context.Context, result releasekit.PublicationResult) (string, error) {
if result.Evidence.ModuleDir != "" {
common, err := git.CommonDirectory(ctx, result.RepositoryDir)
if err != nil {
return "", err
}
args, err := gotool.RecoveryTool(ctx, result.Evidence.ModuleDir, filepath.Join(common, "releasekit", "publication-recovery"))
if err != nil {
return "", err
}
if args != nil {
prefix := "env go -C " + shellQuote(git.DisplayDiagnostic(args.Directory))
command := "(export GOWORK=off GOTOOLCHAIN=local && releasekit_host_os=$(" + prefix + " env GOHOSTOS) && releasekit_host_arch=$(" + prefix + " env GOHOSTARCH) && GOOS=\"$releasekit_host_os\" GOARCH=\"$releasekit_host_arch\" " + prefix
for _, arg := range args.Args {
command += " " + shellQuote(git.DisplayDiagnostic(arg))
}
path, err := filepath.Abs(git.DisplayDiagnostic(result.RecordPath))
if err != nil {
return "", err
}
return command + " reconcile --record " + shellQuote(path) + ")", nil
}
}
return publicationRecoveryCommand(result.RecordPath)
}
func publicationOffersRecovery(phase releasekit.PublicationPhase) bool {
switch phase {
case releasekit.PublicationTagCreation, releasekit.PublicationPush, releasekit.PublicationReconciliation:
return true
default:
return false
}
}
func publicationRecoveryCommand(recordPath string) (string, error) {
return executableRecoveryCommand(recordPath, "reconcile")
}
func executableRecoveryCommand(recordPath, command string) (string, error) {
executable, err := os.Executable()
if err != nil {
return "", fmt.Errorf("find current executable: %w", err)
}
executable, err = filepath.Abs(executable)
if err != nil {
return "", fmt.Errorf("resolve current executable path: %w", err)
}
if gotool.TemporaryExecutable(executable) {
return "", fmt.Errorf("current executable belongs to a temporary Go build; select a supported ReleaseKit CLI for the saved record")
}
// Redact before path cleaning can change a pasted URL's recognizable syntax.
recordPath, err = filepath.Abs(git.DisplayDiagnostic(recordPath))
if err != nil {
return "", fmt.Errorf("resolve publication record path: %w", err)
}
return shellQuote(executable) + " " + command + " --record " + shellQuote(recordPath), nil
}
func shellQuote(argument string) string {
return "'" + strings.ReplaceAll(argument, "'", "'\"'\"'") + "'"
}
func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2
}
if settings.Build == nil {
fmt.Fprintln(stderr, "build requires build settings in the profile")
return 2
}
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Version: invocation.Version,
Spec: *configuredBuildSpec(settings.Build),
OutputDir: invocation.OutputDir,
Output: stderr,
})
if result.OutputDir != "" && len(result.Targets) != 0 {
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
fmt.Fprintf(stderr, "%v\n", receiptErr)
return 1
}
}
if err != nil {
fmt.Fprintf(stderr, "build failed module=%s module-dir=%s version=%s tag=%s commit=%s: %v\n", result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, err)
for _, artifact := range result.Artifacts {
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
}
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
return 1
}
if len(result.Targets) == 0 {
fmt.Fprintf(stdout, "no build targets selected for module %s version %s tag %s at %s\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit)
return 0
}
receipt := receiptFromBuild(result)
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
if err != nil {
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
return 1
}
stored, err := cli.LoadBuildReceipt(receiptPath)
if err != nil {
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
return 1
}
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
return 1
}
fmt.Fprintf(stdout, "built %d artifacts for module %s version %s tag %s at %s with %s\n", len(result.Artifacts), result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.Compiler)
for _, artifact := range result.Artifacts {
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
}
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
return 0
}
func sourceSpec(settings cli.Settings) *releasekit.SourceSpec {
source := settings.SourceSpec()
if source == nil {
return nil
}
return &releasekit.SourceSpec{
Dir: source.Dir, GoEnabled: source.GoEnabled, Publication: releasekit.PublicationMode(source.Publication),
VersionFormat: releasekit.VersionFormat(source.VersionFormat), VersionPrefix: source.VersionPrefix, TagPrefix: source.TagPrefix,
}
}
func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest { func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
request := releasekit.ReleaseRequest{ request := releasekit.ReleaseRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
Remote: settings.Remote, Remote: settings.Remote,
@@ -163,10 +290,11 @@ func candidateRequest(invocation cli.Invocation, settings cli.Settings, output i
if len(settings.Checks) != 0 { if len(settings.Checks) != 0 {
checks := settings.Checks checks := settings.Checks
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error { request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
return cli.RunChecks(ctx, candidate.ModuleDir, checks, map[string]string{ return cli.RunChecks(ctx, candidate.SourceDir, checks, map[string]string{
"RELEASEKIT_VERSION": candidate.Version, "RELEASEKIT_VERSION": candidate.Version,
"RELEASEKIT_CANDIDATE": candidate.Commit, "RELEASEKIT_CANDIDATE": candidate.Commit,
"RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir, "RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir,
"RELEASEKIT_SOURCE_DIR": candidate.SourceDir,
"RELEASEKIT_MODULE_DIR": candidate.ModuleDir, "RELEASEKIT_MODULE_DIR": candidate.ModuleDir,
"RELEASEKIT_MODULE_PATH": candidate.ModulePath, "RELEASEKIT_MODULE_PATH": candidate.ModulePath,
"RELEASEKIT_TAG": candidate.Tag, "RELEASEKIT_TAG": candidate.Tag,
@@ -181,8 +309,9 @@ func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec
return releasekit.ValidationSpec{} return releasekit.ValidationSpec{}
} }
result := releasekit.ValidationSpec{ result := releasekit.ValidationSpec{
SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles), SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles),
GoFormat: settings.GoFormat, ForbiddenFiles: copyStringsPreservingEmpty(settings.ForbiddenFiles),
GoFormat: settings.GoFormat,
ModuleDistribution: releasekit.ModuleDistributionValidationSpec{ ModuleDistribution: releasekit.ModuleDistributionValidationSpec{
WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles, WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles,
LocalReplacements: settings.ModuleDistribution.LocalReplacements, LocalReplacements: settings.ModuleDistribution.LocalReplacements,
@@ -220,28 +349,40 @@ func candidateFailureText(err error) string {
return err.Error() return err.Error()
} }
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error { func checkExpectedSelection(ctx context.Context, repositoryDir, expectedModule, expectedSource string, settings cli.Settings) error {
if expectedModule == "" { if expectedModule == "" && expectedSource == "" {
return nil return nil
} }
commit, err := git.CaptureHead(ctx, repositoryDir) commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil { if err != nil {
return err return err
} }
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit) selected, err := releaseidentity.ResolveCommittedSource(ctx, repositoryDir, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil { if err != nil {
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err) return fmt.Errorf("normalize profile source: %w", err)
} }
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit) for _, expectation := range []struct{ kind, dir string }{{"module", expectedModule}, {"source", expectedSource}} {
if err != nil { if expectation.dir == "" {
return fmt.Errorf("normalize profile module %q: %w", profileModule, err) continue
} }
if expected.ModuleSubdir != selected.ModuleSubdir { expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectation.dir, commit)
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir) if err != nil {
return fmt.Errorf("normalize expected %s %q: %w", expectation.kind, expectation.dir, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected %s %q resolves to %q, but the profile selects %q", expectation.kind, expectation.dir, expected.ModuleSubdir, selected.ModuleSubdir)
}
} }
return nil return nil
} }
func selectionErrorLabel(expectedSource string) string {
if expectedSource != "" {
return "profile source selection"
}
return "profile module selection"
}
func selectedModuleLabel(moduleDir string) string { func selectedModuleLabel(moduleDir string) string {
if moduleDir == "" { if moduleDir == "" {
return "." return "."
@@ -281,23 +422,47 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
return 1 return 1
} }
if releaseidentity.IsDiagnosticTag(invocation.ExpectedTag) {
return runDiagnosticDelivery(ctx, invocation, stdout, stderr)
}
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath) settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil { if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err) fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2 return 2
} }
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil { if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err) fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2 return 2
} }
destination, status := deliveryDestination(settings, stderr) identity, err := releaseidentity.FromCommittedSource(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit, settings.SourceSpec())
if err != nil {
fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err)
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return 2
}
return 1
}
if invocation.ExpectedTag != identity.Tag {
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected source tag %q\n", invocation.ExpectedTag, identity.Tag)
return 1
}
if !identity.GoEnabled && settings.Build != nil && len(settings.Build.Targets) != 0 {
fmt.Fprintln(stderr, "build targets require Go capability")
return 2
}
destination, status := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr)
if status != 0 { if status != 0 {
return status return status
} }
if settings.Build != nil && len(settings.Build.Targets) != 0 { if settings.Build != nil && len(settings.Build.Targets) != 0 {
if err := releasekit.PreflightDelivery(ctx, destination); err != nil {
fmt.Fprintf(stderr, "delivery credential preflight: %v\n", err)
return deliveryPreflightExitStatus(err)
}
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{ if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: identity.ModuleSubdir,
}); err != nil { }); err != nil {
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err) fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
return 1 return 1
@@ -309,32 +474,41 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
// deliverWithSettings adapts prepared CLI state to the public delivery facade. // deliverWithSettings adapts prepared CLI state to the public delivery facade.
// CI entry points can reuse it after preparing the checkout and loading its profile. // CI entry points can reuse it after preparing the checkout and loading its profile.
func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int { func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int {
destination, status := deliveryDestination(settings, stderr) destination, status := deliveryDestination(invocation.Repository, settings, cli.LocalCredentials, stderr)
if status != 0 { if status != 0 {
return status return status
} }
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr) return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
} }
func deliveryDestination(settings cli.Settings, stderr io.Writer) (releasekit.GiteaDestination, int) { func deliveryDestination(repositoryDir string, settings cli.Settings, context cli.CredentialContext, stderr io.Writer) (releasekit.DeliveryDestination, int) {
delivery := settings.Delivery delivery := settings.Delivery
if delivery == nil || strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" { if delivery == nil {
fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile")
return releasekit.DeliveryDestination{}, 2
}
switch strings.TrimSpace(delivery.Forge) {
case "":
fmt.Fprintln(stderr, "deliver requires delivery.forge in the profile")
return releasekit.DeliveryDestination{}, 2
case string(releasekit.ForgeGitea):
default:
fmt.Fprintf(stderr, "unsupported delivery forge %q\n", delivery.Forge)
return releasekit.DeliveryDestination{}, 2
}
if strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" {
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings") fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
return releasekit.GiteaDestination{}, 2 return releasekit.DeliveryDestination{}, 2
} }
tokenEnv := delivery.TokenEnv token, _, err := cli.ResolveDeliveryCredential(repositoryDir, delivery.Credentials, context)
if strings.TrimSpace(tokenEnv) == "" { if err != nil {
tokenEnv = "RELEASEKIT_GITEA_TOKEN" fmt.Fprintln(stderr, err)
return releasekit.DeliveryDestination{}, 2
} }
token, ok := os.LookupEnv(tokenEnv) return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
if !ok || strings.TrimSpace(token) == "" {
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
return releasekit.GiteaDestination{}, 2
}
return releasekit.GiteaDestination{BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
} }
func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.GiteaDestination, stdout, stderr io.Writer) int { func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.DeliveryDestination, stdout, stderr io.Writer) int {
hasTargets := settings.Build != nil && len(settings.Build.Targets) != 0 hasTargets := settings.Build != nil && len(settings.Build.Targets) != 0
if invocation.AssetsDir != "" && !hasTargets { if invocation.AssetsDir != "" && !hasTargets {
fmt.Fprintln(stderr, "--assets requires build targets in the profile") fmt.Fprintln(stderr, "--assets requires build targets in the profile")
@@ -352,7 +526,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err) fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
return 1 return 1
} }
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit) selection, err := releaseidentity.ResolveCommittedSource(ctx, invocation.Repository, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil { if err != nil {
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err) fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
return 1 return 1
@@ -374,6 +548,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{ result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
ExpectedTag: invocation.ExpectedTag, ExpectedTag: invocation.ExpectedTag,
@@ -383,16 +558,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
Output: stderr, Output: stderr,
}) })
if err != nil { if err != nil {
fmt.Fprintf(stderr, "delivery state=%s module=%s module-dir=%s version=%s tag=%s commit=%s url=%s: %v\n", result.State, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.ReleaseURL, err) return reportDeliveryFailure(stderr, result, err)
writeDeliveryAssets(stderr, result)
writeDeliveryRecovery(stderr, result)
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
if result.State == releasekit.DeliveryUnknown {
return 3
}
return 1
} }
fmt.Fprintf(stdout, "delivered module %s version %s tag %s at %s (state %s)\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.State) fmt.Fprintf(stdout, "delivered module %s version %s tag %s at %s (state %s)\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.State)
if result.ReleaseURL != "" { if result.ReleaseURL != "" {
@@ -402,6 +568,46 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
return 0 return 0
} }
func reportDeliveryFailure(output io.Writer, result releasekit.DeliveryResult, err error) int {
if result.State == releasekit.DeliveryComplete {
fmt.Fprintln(output, "hosted delivery completed; local cleanup failed")
}
fmt.Fprintf(output, "delivery state=%s module=%s module-dir=%s version=%s tag=%s commit=%s url=%s: %v\n", result.State, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.ReleaseURL, err)
writeDeliveryAssets(output, result)
writeDeliveryRecovery(output, result)
if result.State == releasekit.DeliveryComplete {
return 1
}
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
var preflightErr *releasekit.DeliveryPreflightError
if errors.As(err, &preflightErr) {
return deliveryPreflightExitStatus(preflightErr)
}
if result.State == releasekit.DeliveryUnknown {
return 3
}
return 1
}
func deliveryPreflightExitStatus(err error) int {
var preflightErr *releasekit.DeliveryPreflightError
if !errors.As(err, &preflightErr) {
return 1
}
switch preflightErr.Kind {
case releasekit.DeliveryPreflightInvalidDestination,
releasekit.DeliveryPreflightMissingCredential,
releasekit.DeliveryPreflightInvalidCredential,
releasekit.DeliveryPreflightInsufficientPermissions,
releasekit.DeliveryPreflightInaccessibleDestination:
return 2
default:
return 1
}
}
func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) { func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
for _, group := range []struct { for _, group := range []struct {
label string label string
@@ -434,6 +640,9 @@ func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult { func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
result := &releasekit.BuildResult{ result := &releasekit.BuildResult{
RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag, RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag,
SourceDir: receipt.SourceDir, SourceSubdir: receipt.SourceSubdir, GoEnabled: receipt.GoEnabled,
Publication: releasekit.PublicationMode(receipt.Publication), VersionFormat: releasekit.VersionFormat(receipt.VersionFormat),
VersionPrefix: receipt.VersionPrefix, IdentityKind: receipt.IdentityKind, NotePath: receipt.NotePath,
CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified, CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified,
Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName, Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName,
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler, OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
@@ -470,6 +679,14 @@ func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
receipt := cli.BuildReceipt{ receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion, SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: result.RepositoryDir, RepositoryDir: result.RepositoryDir,
SourceDir: result.SourceDir,
SourceSubdir: result.SourceSubdir,
GoEnabled: result.GoEnabled,
Publication: string(result.Publication),
VersionFormat: string(result.VersionFormat),
VersionPrefix: result.VersionPrefix,
IdentityKind: result.IdentityKind,
NotePath: result.NotePath,
ModuleDir: result.ModuleDir, ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath, ModulePath: result.ModulePath,
Tag: result.Tag, Tag: result.Tag,

View File

@@ -6,6 +6,7 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -18,9 +19,9 @@ import (
"sync" "sync"
"testing" "testing"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit" releasekit "go.maximumdirect.net/releasekit"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestVersionCommand(t *testing.T) { func TestVersionCommand(t *testing.T) {
@@ -36,6 +37,87 @@ func TestVersionCommand(t *testing.T) {
} }
} }
func TestCIDeliverRedactsRemoteCredentialsOnPreparationFailure(t *testing.T) {
t.Setenv("NO_PROXY", "*")
t.Setenv("no_proxy", "*")
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("GIT_TERMINAL_PROMPT", "0")
repository := newCLIRepository(t)
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer server.Close()
remote := strings.Replace(server.URL, "http://", "http://review-user:review-password@", 1) + "/repo.git"
var stdout, stderr bytes.Buffer
status := run(t.Context(), []string{"ci-deliver", "--repo", repository, "--remote", remote, "--commit", commit, "v1.2.3"}, &stdout, &stderr)
if status != 1 || stdout.Len() != 0 || !strings.Contains(stderr.String(), "prepare tagged checkout") || !strings.Contains(stderr.String(), "repo.git") {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
if strings.Contains(stderr.String(), "review-user") || strings.Contains(stderr.String(), "review-password") {
t.Fatalf("CLI preparation diagnostic exposes credentials: %q", stderr.String())
}
}
func TestPublishCommandReportsUnknownForPeeledOnlyRecovery(t *testing.T) {
repository := newCLIRepository(t)
writeRepositoryFile(t, repository, "docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nRelease note.\n")
profile, err := json.Marshal(cli.Settings{Product: "Example Product", Remote: "origin"})
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, "releasekit.json", string(profile))
cliGitRun(t, repository, "add", "docs/releases/v1.2.3.md", "releasekit.json")
cliGitRun(t, repository, "commit", "-m", "configure release")
remote := filepath.Join(t.TempDir(), "origin.git")
cliGitRun(t, repository, "init", "--bare", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "push", "--set-upstream", "origin", "main")
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
marker := filepath.Join(t.TempDir(), "pushed")
script := `#!/bin/sh
is_push=0
is_ls=0
for arg in "$@"; do
[ "$arg" = push ] && is_push=1
[ "$arg" = ls-remote ] && is_ls=1
done
if [ "$is_ls" = 1 ] && [ -f "$PUSH_MARKER" ]; then
case " $* " in *refs/tags/v1.2.3*)
object=$("$REAL_GIT" rev-parse 'refs/tags/v1.2.3^{}')
printf '%s\trefs/tags/v1.2.3^{}\n' "$object"
exit 0;; esac
fi
if [ "$is_push" = 1 ]; then
"$REAL_GIT" "$@" || exit $?
: > "$PUSH_MARKER"
echo 'lost acknowledgment' >&2
exit 77
fi
exec "$REAL_GIT" "$@"
`
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("REAL_GIT", realGit)
t.Setenv("PUSH_MARKER", marker)
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"publish", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 3 || !strings.Contains(stderr.String(), "unknown") || strings.Contains(stdout.String(), "published") {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
local := cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")
if got := cliGitOutput(t, remote, "rev-parse", "refs/tags/v1.2.3"); got != local {
t.Fatalf("remote tag = %s, want %s", got, local)
}
}
func TestUnknownCommand(t *testing.T) { func TestUnknownCommand(t *testing.T) {
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
if status := run(context.Background(), []string{"unknown"}, &stdout, &stderr); status != 2 { if status := run(context.Background(), []string{"unknown"}, &stdout, &stderr); status != 2 {
@@ -345,6 +427,30 @@ func TestCandidateFailurePresentationRetainsCallbackContext(t *testing.T) {
} }
} }
func TestPublishCommandRedactsCredentialsInEndpointMismatch(t *testing.T) {
repository := newCLIRepository(t)
writeRepositoryFile(t, repository, "docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nRelease note.\n")
settings := cli.Settings{Product: "Example Product", Remote: "origin", ExpectedPushURL: "https://expected-token@example.invalid/project.git"}
profile, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, "releasekit.json", string(profile))
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "configure release")
cliGitRun(t, repository, "remote", "add", "origin", "https://actual-user:actual-secret@example.invalid/project.git")
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"publish", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), "unexpected publication push URL") || !strings.Contains(stderr.String(), "example.invalid/project.git") {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
for _, secret := range []string{"expected-token", "actual-user", "actual-secret"} {
if strings.Contains(stderr.String(), secret) || strings.Contains(stdout.String(), secret) {
t.Fatalf("CLI output exposes %q: %q %q", secret, stdout.String(), stderr.String())
}
}
}
func TestPublishCommandPublishesConfiguredCandidate(t *testing.T) { func TestPublishCommandPublishesConfiguredCandidate(t *testing.T) {
raceSelected := racePrerequisitesAvailable() raceSelected := racePrerequisitesAvailable()
repository := newCLIRepository(t) repository := newCLIRepository(t)
@@ -407,6 +513,26 @@ printf '%s %s\n' "$version" "$candidate" >> "$RELEASEKIT_COMPATIBILITY_LOG"
if !bytes.Contains(stderr.Bytes(), []byte("validating and publishing module . version v1.2.3")) || !bytes.Contains(stderr.Bytes(), []byte("example.com/cli-candidate")) { if !bytes.Contains(stderr.Bytes(), []byte("validating and publishing module . version v1.2.3")) || !bytes.Contains(stderr.Bytes(), []byte("example.com/cli-candidate")) {
t.Fatalf("stderr does not show publication progress and validation: %q", stderr.String()) t.Fatalf("stderr does not show publication progress and validation: %q", stderr.String())
} }
const recordPrefix = "publication record saved: "
var recordPath string
for _, line := range strings.Split(stderr.String(), "\n") {
if strings.HasPrefix(line, recordPrefix) {
recordPath = strings.TrimPrefix(line, recordPrefix)
}
}
if !filepath.IsAbs(recordPath) {
t.Fatalf("default publication record path = %q, stderr = %q", recordPath, stderr.String())
}
recorded, err := releasekit.LoadPublicationEvidence(recordPath)
if err != nil {
t.Fatalf("load default publication record: %v", err)
}
if recorded.Tag != "v1.2.3" || recorded.CandidateCommit != commit || recorded.TagObject != tagObject || recorded.Endpoint != remote {
t.Fatalf("default publication evidence = %#v", recorded)
}
if strings.Contains(stderr.String(), "recovery command:") {
t.Fatalf("successful publication prescribed a recovery command: %q", stderr.String())
}
if got := cliGitOutput(t, remote, "rev-parse", "refs/tags/v1.2.3"); got != tagObject { if got := cliGitOutput(t, remote, "rev-parse", "refs/tags/v1.2.3"); got != tagObject {
t.Fatalf("remote tag object = %s, want %s", got, tagObject) t.Fatalf("remote tag object = %s, want %s", got, tagObject)
} }
@@ -472,7 +598,7 @@ import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {
@@ -506,6 +632,65 @@ func main() {
} }
} }
func TestBuildCommandReportsOnlyHashedArtifactsAfterReadFailure(t *testing.T) {
repository := newCLIBuildRepository(t, "package main\nfunc main() {}\n")
secondArch := "arm64"
if runtime.GOARCH == secondArch {
secondArch = "amd64"
}
settings := cli.Settings{Product: "Example Product", Build: &cli.BuildSettings{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []string{runtime.GOOS + "/" + runtime.GOARCH, runtime.GOOS + "/" + secondArch}}}
profile, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, "releasekit.json", string(profile))
realGo, err := exec.LookPath("go")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
script := `#!/bin/sh
if [ "$1" != build ]; then exec "$RELEASEKIT_REAL_GO" "$@"; fi
output=
previous=
for arg in "$@"; do
if [ "$previous" = -o ]; then output=$arg; fi
previous=$arg
done
"$RELEASEKIT_REAL_GO" "$@" || exit $?
if [ -f "$RELEASEKIT_BUILD_COUNT" ]; then
rm "$output"
mkdir "$output"
else
: > "$RELEASEKIT_BUILD_COUNT"
fi
`
if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("RELEASEKIT_REAL_GO", realGo)
t.Setenv("RELEASEKIT_BUILD_COUNT", filepath.Join(t.TempDir(), "count"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"build", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
first := fmt.Sprintf("fixture-v1.2.3-%s-%s", runtime.GOOS, runtime.GOARCH)
second := fmt.Sprintf("fixture-v1.2.3-%s-%s", runtime.GOOS, secondArch)
if runtime.GOOS == "windows" {
first, second = first+".exe", second+".exe"
}
content, err := os.ReadFile(filepath.Join(repository, "dist", first))
if err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(content)
if status != 1 || stdout.Len() != 0 || !strings.Contains(stderr.String(), fmt.Sprintf("built %s %x", first, digest)) || strings.Contains(stderr.String(), "built "+second) || !strings.Contains(stderr.String(), "hash build output") || !strings.Contains(stderr.String(), second) {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
if _, err := os.Stat(filepath.Join(repository, "dist", cli.BuildReceiptName)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("partial build left receipt: %v", err)
}
}
func TestBuildCommandLeavesNoReceiptAfterSmokeFailure(t *testing.T) { func TestBuildCommandLeavesNoReceiptAfterSmokeFailure(t *testing.T) {
repository := newCLIBuildRepository(t, `package main repository := newCLIBuildRepository(t, `package main
import ( import (
@@ -639,7 +824,7 @@ func TestDeliverPageOnlyCreatesAndReusesRelease(t *testing.T) {
settings := cli.Settings{ settings := cli.Settings{
Product: "Example Product", Product: "Example Product",
Validation: &cli.ValidationSettings{Go: cli.GoValidationSettings{CompileTargets: []string{"linux/amd64"}}}, Validation: &cli.ValidationSettings{Go: cli.GoValidationSettings{CompileTargets: []string{"linux/amd64"}}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
} }
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
@@ -673,7 +858,7 @@ func TestDeliverBuildsTaggedArtifactsAndReusesAssets(t *testing.T) {
settings := cli.Settings{ settings := cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
} }
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
@@ -716,7 +901,7 @@ func TestCIDeliverLoadsTaggedProfileAndSkipsUnavailablePageOnlyDependencies(t *t
defer server.Close() defer server.Close()
writeDeliveryProfileAt(t, repository, "profiles/ci-delivery.json", cli.Settings{ writeDeliveryProfileAt(t, repository, "profiles/ci-delivery.json", cli.Settings{
Product: "Example Product", Product: "Example Product",
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = expectedCommit }) state.update(func(state *deliveryServerData) { state.commit = expectedCommit })
@@ -751,7 +936,7 @@ func TestCIDeliverRejectsWrongCommitBeforeGoOrHostedRequests(t *testing.T) {
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = expectedCommit }) state.update(func(state *deliveryServerData) { state.commit = expectedCommit })
@@ -802,7 +987,7 @@ func TestCIDeliverRejectsExpectedModuleMismatchBeforeDependencyPreparation(t *te
Product: "Example Product", Product: "Example Product",
ModuleDir: "integrations/other", ModuleDir: "integrations/other",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = expectedCommit }) state.update(func(state *deliveryServerData) { state.commit = expectedCommit })
@@ -839,7 +1024,7 @@ func TestCIDeliverPreparesDependenciesAndBuildsConfiguredTargets(t *testing.T) {
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = expectedCommit }) state.update(func(state *deliveryServerData) { state.commit = expectedCommit })
@@ -865,7 +1050,7 @@ func TestCIDeliverValidatesCredentialsBeforePreparingDependencies(t *testing.T)
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = expectedCommit }) state.update(func(state *deliveryServerData) { state.commit = expectedCommit })
@@ -903,7 +1088,7 @@ func TestDeliverRejectsInvalidTaggedSourceBeforeManagedBuild(t *testing.T) {
settings := cli.Settings{ settings := cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
} }
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
@@ -919,6 +1104,15 @@ func TestDeliverRejectsInvalidTaggedSourceBeforeManagedBuild(t *testing.T) {
} }
} }
func TestCompletedDeliveryCleanupFailureReportsCompletedState(t *testing.T) {
var output bytes.Buffer
result := releasekit.DeliveryResult{State: releasekit.DeliveryComplete, ModulePath: "example.com/app", Tag: "v1.2.3", ReleaseURL: "https://example.invalid/release", Uploaded: []releasekit.DeliveryAsset{{Filename: "app", SHA256: "digest"}}}
status := reportDeliveryFailure(&output, result, errors.New("remove temporary directory: failed"))
if status != 1 || !strings.Contains(output.String(), "hosted delivery completed; local cleanup failed") || !strings.Contains(output.String(), "uploaded app digest") || strings.Contains(output.String(), "retry") {
t.Fatalf("status = %d, output = %q", status, output.String())
}
}
func TestDeliverFailureReportsRecoveryForPartialConflictAndUnknownStates(t *testing.T) { func TestDeliverFailureReportsRecoveryForPartialConflictAndUnknownStates(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
name string name string
@@ -958,7 +1152,7 @@ func TestDeliverFailureReportsRecoveryForPartialConflictAndUnknownStates(t *test
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Build: &build, Build: &build,
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
@@ -1002,7 +1196,7 @@ func TestDeliverRejectsWrongHostedTagBeforeReleaseWrite(t *testing.T) {
state := &deliveryServerState{data: deliveryServerData{remoteCommit: strings.Repeat("0", 40)}} state := &deliveryServerState{data: deliveryServerData{remoteCommit: strings.Repeat("0", 40)}}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token") t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
@@ -1018,23 +1212,244 @@ func TestDeliverRequiresCredentialBeforeRemoteRequests(t *testing.T) {
state := &deliveryServerState{} state := &deliveryServerState{}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{}}}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "") t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "ambient-token")
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr) status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "RELEASEKIT_TEST_DELIVERY_TOKEN") { if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "delivery.credentials.local.token_file") {
t.Fatalf("missing credential status=%d requests=%d stdout=%q stderr=%q", status, state.snapshot().apiRequests, stdout.String(), stderr.String()) t.Fatalf("missing credential status=%d requests=%d stdout=%q stderr=%q", status, state.snapshot().apiRequests, stdout.String(), stderr.String())
} }
} }
func TestDeliverRejectsMissingBlankAndUnsupportedForgeBeforeTokenOrBuild(t *testing.T) {
for _, forge := range []string{"", " \t", "unknown"} {
t.Run(forge, func(t *testing.T) {
repository := newCLIRepository(t)
state := &deliveryServerState{}
server := newDeliveryServer(t, state)
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{
Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example",
Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}},
},
})
state.update(func(data *deliveryServerData) { data.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3")
shimDir := t.TempDir()
markerPath := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", markerPath)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 2 || !strings.Contains(stderr.String(), "forge") || strings.Contains(stderr.String(), "missing-token") {
t.Fatalf("deliver status=%d stdout=%q stderr=%q; want selection diagnostic before token access", status, stdout.String(), stderr.String())
}
if _, err := os.Stat(markerPath); !os.IsNotExist(err) {
t.Fatalf("Go was invoked before forge validation: %v", err)
}
if got := state.snapshot().apiRequests; got != 0 {
t.Fatalf("hosted API requests = %d, want 0", got)
}
})
}
}
func TestCIDeliverRejectsUnsupportedForgeBeforeTokenOrDependencyPreparation(t *testing.T) {
repository := newDeliveryBuildRepository(t)
state := &deliveryServerState{}
server := newDeliveryServer(t, state)
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{
Forge: "unsupported", BaseURL: server.URL, Owner: "owner", Repository: "example",
Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}},
},
})
expectedCommit := pushTaggedCLIRepository(t, repository)
state.update(func(data *deliveryServerData) { data.commit = expectedCommit })
shimDir := t.TempDir()
markerPath := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", markerPath)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--commit", expectedCommit, "v1.2.3"}, &stdout, &stderr)
if status != 2 || !strings.Contains(stderr.String(), "forge") || strings.Contains(stderr.String(), "missing-token") {
t.Fatalf("ci-deliver status=%d stdout=%q stderr=%q; want selection diagnostic before token access", status, stdout.String(), stderr.String())
}
if _, err := os.Stat(markerPath); !os.IsNotExist(err) {
t.Fatalf("Go was invoked before forge validation: %v", err)
}
if got := state.snapshot().apiRequests; got != 0 {
t.Fatalf("hosted API requests = %d, want 0", got)
}
}
func TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne(t *testing.T) {
repository := newCLIRepository(t)
var mu sync.Mutex
var requests, writes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
if r.Method != http.MethodGet {
writes++
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
return
}
requests++
if r.URL.Path == "/api/v1/repos/owner/example" {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
return
}
http.Error(w, "verification unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
},
})
expectedCommit := pushTaggedCLIRepository(t, repository)
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "fixture-token")
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--commit", expectedCommit, "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), "unavailable") {
t.Fatalf("page-only ci-deliver status=%d stdout=%q stderr=%q; want unavailable status 1", status, stdout.String(), stderr.String())
}
if requests != 2 || writes != 0 {
t.Fatalf("page-only preflight requests=%d writes=%d, want two reads and no writes", requests, writes)
}
}
func TestDeliverUnavailablePreflightStopsBeforeManagedBuild(t *testing.T) {
repository := newCLIRepository(t)
var mu sync.Mutex
var requests, writes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
if r.Method != http.MethodGet {
writes++
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
return
}
requests++
if r.URL.Path == "/api/v1/repos/owner/example" {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
return
}
http.Error(w, "verification unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
},
})
cliGitRun(t, repository, "tag", "v1.2.3")
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "fixture-token")
shimDir := t.TempDir()
markerPath := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", markerPath)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), "unavailable") {
t.Fatalf("deliver status=%d stdout=%q stderr=%q; want unavailable status 1", status, stdout.String(), stderr.String())
}
if _, err := os.Stat(markerPath); !os.IsNotExist(err) {
t.Fatalf("managed build ran before successful preflight: %v", err)
}
if requests != 2 || writes != 0 {
t.Fatalf("preflight requests=%d writes=%d, want two reads and no writes", requests, writes)
}
}
func TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation(t *testing.T) {
repository := newDeliveryBuildRepository(t)
var mu sync.Mutex
var requests, writes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
if r.Method != http.MethodGet {
writes++
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
return
}
requests++
if r.URL.Path == "/api/v1/repos/owner/example" {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
return
}
http.Error(w, "verification unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
},
})
expectedCommit := pushTaggedCLIRepository(t, repository)
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "fixture-token")
shimDir := t.TempDir()
markerPath := filepath.Join(shimDir, "go-invoked")
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", markerPath)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repository, "--commit", expectedCommit, "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), "unavailable") {
t.Fatalf("ci-deliver status=%d stdout=%q stderr=%q; want unavailable status 1", status, stdout.String(), stderr.String())
}
if _, err := os.Stat(markerPath); !os.IsNotExist(err) {
t.Fatalf("dependency preparation ran before successful preflight: %v", err)
}
if requests != 2 || writes != 0 {
t.Fatalf("preflight requests=%d writes=%d, want two reads and no writes", requests, writes)
}
}
func TestDeliverRejectsCheckoutThatDiffersFromLocalTag(t *testing.T) { func TestDeliverRejectsCheckoutThatDiffersFromLocalTag(t *testing.T) {
repository := newCLIRepository(t) repository := newCLIRepository(t)
state := &deliveryServerState{} state := &deliveryServerState{}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later commit"), 0o600); err != nil { if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later commit"), 0o600); err != nil {
@@ -1061,7 +1476,7 @@ func TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites(t *testin
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
current := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}} current := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
settings := cli.Settings{Product: "Example Product", Build: &current, Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}} settings := cli.Settings{Product: "Example Product", Build: &current, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}}
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
@@ -1097,7 +1512,7 @@ func TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites(t *testin
} }
return return
} }
if status != 1 || state.snapshot().apiRequests != 0 || state.snapshot().releaseCreates != 0 || state.snapshot().assetUploads != 0 { if status != 1 || state.snapshot().writes != 0 {
t.Fatalf("%s receipt status=%d requests=%d stdout=%q stderr=%q", mode, status, state.snapshot().apiRequests, stdout.String(), stderr.String()) t.Fatalf("%s receipt status=%d requests=%d stdout=%q stderr=%q", mode, status, state.snapshot().apiRequests, stdout.String(), stderr.String())
} }
if mode == "tampered" || mode == "missing artifact" { if mode == "tampered" || mode == "missing artifact" {
@@ -1127,6 +1542,8 @@ func writeDeliveryReceipt(t *testing.T, repository string, settings cli.BuildSet
receipt := cli.BuildReceipt{ receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion, SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: resolvedRepository, ModuleDir: resolvedRepository, ModulePath: "example.com/cli-candidate", Tag: "v1.2.3", RepositoryDir: resolvedRepository, ModuleDir: resolvedRepository, ModulePath: "example.com/cli-candidate", Tag: "v1.2.3",
SourceDir: resolvedRepository, SourceSubdir: ".", GoEnabled: true, Publication: "go-module",
VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
CandidateCommit: cliGitOutput(t, repository, "rev-parse", "HEAD"), CandidateCommit: cliGitOutput(t, repository, "rev-parse", "HEAD"),
SourceVerified: true, SourceVerified: true,
Version: "v1.2.3", MainPackage: settings.MainPackage, BinaryName: settings.BinaryName, Version: "v1.2.3", MainPackage: settings.MainPackage, BinaryName: settings.BinaryName,
@@ -1174,6 +1591,7 @@ type deliveryServerData struct {
product string product string
remoteCommit string remoteCommit string
apiRequests int apiRequests int
writes int
pageExists bool pageExists bool
releaseCreates int releaseCreates int
assetUploads int assetUploads int
@@ -1196,11 +1614,19 @@ func newDeliveryServer(t *testing.T, state *deliveryServerState) *httptest.Serve
defer state.mu.Unlock() defer state.mu.Unlock()
if strings.HasPrefix(r.URL.Path, "/api/") { if strings.HasPrefix(r.URL.Path, "/api/") {
data.apiRequests++ data.apiRequests++
if r.Method != http.MethodGet {
data.writes++
}
if r.Header.Get("Authorization") != "token fixture-token" { if r.Header.Get("Authorization") != "token fixture-token" {
t.Errorf("authorization = %q", r.Header.Get("Authorization")) t.Errorf("authorization = %q", r.Header.Get("Authorization"))
} }
} }
switch r.URL.Path { switch r.URL.Path {
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
case "/api/v1/repos/owner/example/tags/" + data.tag: case "/api/v1/repos/owner/example/tags/" + data.tag:
if data.commit == "" { if data.commit == "" {
t.Error("tag source commit was not initialized") t.Error("tag source commit was not initialized")
@@ -1316,7 +1742,11 @@ func writeDeliveryRelease(w http.ResponseWriter, baseURL string, data *deliveryS
if product == "" { if product == "" {
product = "Example Product" product = "Example Product"
} }
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " v1.2.3", "body": data.noteBody, "draft": false, "prerelease": false}) version := data.tag
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " " + version, "body": data.noteBody, "draft": false, "prerelease": false})
} }
func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings) { func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings) {
@@ -1325,6 +1755,22 @@ func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings
func writeDeliveryProfileAt(t *testing.T, repository, name string, settings cli.Settings) { func writeDeliveryProfileAt(t *testing.T, repository, name string, settings cli.Settings) {
t.Helper() t.Helper()
if settings.Delivery != nil {
if settings.Delivery.Credentials == nil {
settings.Delivery.Credentials = &cli.DeliveryCredentials{}
}
credentials := settings.Delivery.Credentials
if credentials.Local == nil {
path := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(path, []byte("fixture-token"), 0o600); err != nil {
t.Fatal(err)
}
credentials.Local = &cli.LocalCredential{TokenFile: path}
}
if credentials.CI == nil {
credentials.CI = &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}
}
}
contents, err := json.Marshal(settings) contents, err := json.Marshal(settings)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -1375,7 +1821,7 @@ func newCLIBuildRepository(t *testing.T, mainSource string) string {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/cli-candidate\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
write := func(name, contents string) { write := func(name, contents string) {
t.Helper() t.Helper()
path := filepath.Join(repository, filepath.FromSlash(name)) path := filepath.Join(repository, filepath.FromSlash(name))
@@ -1445,7 +1891,7 @@ func TestDeliverRejectsReceiptBuiltFromDirtySourceAfterCleanup(t *testing.T) {
state := &deliveryServerState{} state := &deliveryServerState{}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
settings := cli.Settings{Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}} settings := cli.Settings{Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}}
writeDeliveryProfile(t, repository, settings) writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
@@ -1485,7 +1931,7 @@ func TestRecoveredPageCreatePreservesPartialDeliveryOnInspectionFailure(t *testi
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}} build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
assets, _ := writeDeliveryReceipt(t, repository, build) assets, _ := writeDeliveryReceipt(t, repository, build)
@@ -1505,7 +1951,7 @@ func TestUnreadableAssetsDoNotClaimAnUnknownWrite(t *testing.T) {
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}} build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
assets, _ := writeDeliveryReceipt(t, repository, build) assets, _ := writeDeliveryReceipt(t, repository, build)
@@ -1530,7 +1976,7 @@ func TestUnreadableAssetsDoNotClaimAnUnknownWrite(t *testing.T) {
func TestFailedRebuildInvalidatesPreviousReceipt(t *testing.T) { func TestFailedRebuildInvalidatesPreviousReceipt(t *testing.T) {
const source = `package main const source = `package main
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo") import("fmt";"go.maximumdirect.net/releasekit/buildinfo")
func main(){fmt.Println("fixture",buildinfo.Version())} func main(){fmt.Println("fixture",buildinfo.Version())}
` `
repository := newCLIBuildRepository(t, source) repository := newCLIBuildRepository(t, source)
@@ -1561,7 +2007,7 @@ func TestTemporaryDeliveryBuildDoesNotRequireWritableRepositoryParent(t *testing
state := &deliveryServerState{} state := &deliveryServerState{}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
parent := t.TempDir() parent := t.TempDir()

View File

@@ -2,11 +2,14 @@ package main
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io/fs" "io/fs"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"runtime"
"strconv"
"strings" "strings"
"testing" "testing"
) )
@@ -24,6 +27,9 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"}, {mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
{mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"}, {mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"},
{mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"}, {mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
{mode: "tag", value: "configuration/2026-12-05", want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
{mode: "tag", value: "releasekit-test/ckconfig/" + strings.Repeat("a", 32), want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
{mode: "tag", value: "releasekit-test/config/" + strings.Repeat("b", 32), want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
} { } {
t.Run(test.mode+" "+test.value, func(t *testing.T) { t.Run(test.mode+" "+test.value, func(t *testing.T) {
got := runModuleSelector(t, helper, test.mode, test.value, "") got := runModuleSelector(t, helper, test.mode, test.value, "")
@@ -43,10 +49,22 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") { if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
t.Fatalf("ambiguous event error = %q", output) t.Fatalf("ambiguous event error = %q", output)
} }
if output := runModuleSelectorError(t, helper, "tag", "releasekit-test/ckconfig/invalid", ""); !strings.Contains(output, "no module map row") {
t.Fatalf("malformed diagnostic error=%q", output)
}
if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil { if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
reservedMap := filepath.Join(t.TempDir(), "production.tsv")
if err := os.WriteFile(reservedMap, []byte("product\treleasekit-test/product/*\t-\treleasekit.json\n"), 0600); err != nil {
t.Fatal(err)
}
for _, tag := range []string{"releasekit-test/product/v1.2.3", "releasekit-test/product/2026-12-01"} {
if got := runModuleSelector(t, helper, "tag", tag, reservedMap); !strings.HasPrefix(got, "product\t") {
t.Fatalf("production tag=%s mapping=%q", tag, got)
}
}
got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath) got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath)
want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json" want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json"
if strings.TrimSpace(got) != want { if strings.TrimSpace(got) != want {
@@ -59,11 +77,11 @@ func TestMultiModuleLauncherUsesSelectedModuleAndProfile(t *testing.T) {
repository := newCLIRepository(t) repository := newCLIRepository(t)
copyExampleTree(t, example, repository) copyExampleTree(t, example, repository)
rootModule := "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.197\n" rootModule := "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n"
selectedModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.198\n" selectedModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.198\n"
writeRepositoryFile(t, repository, "go.mod", rootModule) writeRepositoryFile(t, repository, "go.mod", rootModule)
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", selectedModule) writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", selectedModule)
spaceModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.299\n" spaceModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.299\n"
writeRepositoryFile(t, repository, "integrations/ck config/go.mod", spaceModule) writeRepositoryFile(t, repository, "integrations/ck config/go.mod", spaceModule)
writeRepositoryFile(t, repository, "profiles/core release.json", `{"product":"Example Consumer Integration","module_dir":"integrations/ck config"}`) writeRepositoryFile(t, repository, "profiles/core release.json", `{"product":"Example Consumer Integration","module_dir":"integrations/ck config"}`)
cliGitRun(t, repository, "add", ".") cliGitRun(t, repository, "add", ".")
@@ -79,21 +97,19 @@ func TestMultiModuleLauncherUsesSelectedModuleAndProfile(t *testing.T) {
shim := `#!/bin/sh shim := `#!/bin/sh
set -eu set -eu
printf 'cwd=%s args=%s\n' "$PWD" "$*" >> "$RELEASEKIT_TEST_GO_LOG" printf 'cwd=%s args=%s\n' "$PWD" "$*" >> "$RELEASEKIT_TEST_GO_LOG"
if [ "$1" = env ]; then
case "$2" in GOHOSTOS) printf '%s\n' "$RELEASEKIT_TEST_HOST_OS" ;; GOHOSTARCH) printf '%s\n' "$RELEASEKIT_TEST_HOST_ARCH" ;; esac
exit 0
fi
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_TEST_GO_LOG" ;; esac
modfile= modfile=
output=
previous=
for argument in "$@"; do for argument in "$@"; do
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
if [ "$previous" = -o ]; then output=$argument; fi
previous=$argument
done done
if [ -n "$modfile" ]; then cat "$modfile" >> "$RELEASEKIT_TEST_GO_LOG"; fi if [ -n "$modfile" ]; then cat "$modfile" >> "$RELEASEKIT_TEST_GO_LOG"; fi
if [ "$1" = build ]; then if [ "$1" = tool ]; then
cat > "$output" <<'TOOL' shift 3
#!/bin/sh printf '<%s>\n' "$@" > "$RELEASEKIT_TEST_TOOL_ARGS"
printf '<%s>\n' "$@" > "$RELEASEKIT_TEST_TOOL_ARGS"
TOOL
chmod +x "$output"
fi fi
` `
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil { if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
@@ -103,6 +119,11 @@ fi
t.Setenv("RELEASEKIT_MODULE_MAP", mapPath) t.Setenv("RELEASEKIT_MODULE_MAP", mapPath)
t.Setenv("RELEASEKIT_TEST_GO_LOG", goLog) t.Setenv("RELEASEKIT_TEST_GO_LOG", goLog)
t.Setenv("RELEASEKIT_TEST_TOOL_ARGS", argsLog) t.Setenv("RELEASEKIT_TEST_TOOL_ARGS", argsLog)
t.Setenv("RELEASEKIT_TEST_HOST_OS", runtime.GOOS)
t.Setenv("RELEASEKIT_TEST_HOST_ARCH", runtime.GOARCH)
foreignOS, foreignArch := foreignTarget()
t.Setenv("GOOS", foreignOS)
t.Setenv("GOARCH", foreignArch)
launcher := filepath.Join(repository, "release.sh") launcher := filepath.Join(repository, "release.sh")
command := exec.Command(launcher, "with space", "v1.2.4") command := exec.Command(launcher, "with space", "v1.2.4")
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
@@ -120,6 +141,9 @@ fi
if !strings.Contains(string(goCommands), "cwd="+wantModule) || !strings.Contains(string(goCommands), "v0.2.299") || strings.Contains(string(goCommands), "v0.2.197") { if !strings.Contains(string(goCommands), "cwd="+wantModule) || !strings.Contains(string(goCommands), "v0.2.299") || strings.Contains(string(goCommands), "v0.2.197") {
t.Fatalf("tool bootstrap did not use selected module metadata: %s", goCommands) t.Fatalf("tool bootstrap did not use selected module metadata: %s", goCommands)
} }
if !strings.Contains(string(goCommands), "target="+runtime.GOOS+"/"+runtime.GOARCH) {
t.Fatalf("dependency inspection did not use host target: %s", goCommands)
}
toolArgs, err := os.ReadFile(argsLog) toolArgs, err := os.ReadFile(argsLog)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -134,12 +158,16 @@ fi
} }
} }
func TestMultiModuleLauncherBuildsToolFromSelectedDependency(t *testing.T) { func TestMultiModuleLauncherRunsToolFromSelectedDependency(t *testing.T) {
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module") example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
repository := newCLIRepository(t) repository := newCLIRepository(t)
copyExampleTree(t, example, repository) copyExampleTree(t, example, repository)
writeRepositoryFile(t, repository, "go.mod", "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.197\n") writeRepositoryFile(t, repository, "go.mod", "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n")
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.198\n") const otherModule = "example.com/other-tool"
other := t.TempDir()
writeRepositoryFile(t, other, "go.mod", "module "+otherModule+"\n\ngo 1.25.0\n")
writeRepositoryFile(t, other, "cmd/releasekit/main.go", "package main\nfunc main() { println(\"unexpected tool ran\") }\n")
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit v0.2.198\nrequire "+otherModule+" v0.0.0\n\nreplace "+otherModule+" => "+strconv.Quote(other)+"\n\ntool "+otherModule+"/cmd/releasekit\n")
cliGitRun(t, repository, "add", ".") cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "prepare selected tool module") cliGitRun(t, repository, "commit", "-m", "prepare selected tool module")
@@ -157,32 +185,72 @@ func TestMultiModuleLauncherBuildsToolFromSelectedDependency(t *testing.T) {
t.Setenv("GOPROXY", "file://"+filepath.ToSlash(proxy)) t.Setenv("GOPROXY", "file://"+filepath.ToSlash(proxy))
t.Setenv("GOSUMDB", "off") t.Setenv("GOSUMDB", "off")
t.Setenv("GOTOOLCHAIN", "local") t.Setenv("GOTOOLCHAIN", "local")
foreignOS, foreignArch := foreignTarget()
t.Setenv("GOOS", foreignOS)
t.Setenv("GOARCH", foreignArch)
moduleBefore, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod")) moduleBefore, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
command := exec.Command(filepath.Join(repository, "release.sh"), "ckconfig", "v1.2.3") for _, status := range []int{0, 1, 2, 3} {
output, err := command.CombinedOutput() t.Run(strconv.Itoa(status), func(t *testing.T) {
if err != nil { command := exec.Command(filepath.Join(repository, "release.sh"), "ckconfig", "v1.2.3")
t.Fatalf("launcher error: %v output=%q", err, output) command.Env = setEnvironment(os.Environ(), "RELEASEKIT_TOOL_EXIT", strconv.Itoa(status))
output, err := command.CombinedOutput()
if status == 0 && err != nil {
t.Fatalf("launcher error: %v output=%q", err, output)
}
if status != 0 {
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != status {
t.Fatalf("launcher error = %v, want exit %d; output=%q", err, status, output)
}
}
for _, expected := range []string{
"tool-version=v0.2.198 helper=tool-only dependency",
`"publish"`, `"--repo"`, `"` + repository + `"`,
`"--config"`, `"releasekit-ckconfig.json"`,
`"--expected-module"`, `"integrations/ckconfig"`, `"v1.2.3"`,
} {
if !strings.Contains(string(output), expected) {
t.Errorf("launcher output %q omits %q", output, expected)
}
}
if strings.Contains(string(output), "tool-version=v0.2.197") {
t.Fatalf("launcher ran the root-selected ReleaseKit version: %s", output)
}
if strings.Contains(string(output), "unexpected tool ran") {
t.Fatalf("launcher ran the other tool with the same name: %s", output)
}
moduleAfter, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
if err != nil || !bytes.Equal(moduleAfter, moduleBefore) {
t.Fatalf("selected module go.mod changed: got %q want %q error=%v", moduleAfter, moduleBefore, err)
}
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
t.Fatalf("launcher changed source: %q", status)
}
entries, err := os.ReadDir(filepath.Dir(repository))
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
t.Fatalf("temporary bootstrap directory remains: %s", entry.Name())
}
}
})
} }
for _, expected := range []string{ }
"tool-version=v0.2.198 helper=tool-only dependency",
`"publish"`, `"--repo"`, `"` + repository + `"`, func foreignTarget() (string, string) {
`"--config"`, `"releasekit-ckconfig.json"`, osName, arch := "windows", "arm64"
`"--expected-module"`, `"integrations/ckconfig"`, `"v1.2.3"`, if runtime.GOOS == osName {
} { osName = "linux"
if !strings.Contains(string(output), expected) {
t.Errorf("launcher output %q omits %q", output, expected)
}
} }
if strings.Contains(string(output), "tool-version=v0.2.197") { if runtime.GOARCH == arch {
t.Fatalf("launcher built the root-selected ReleaseKit version: %s", output) arch = "amd64"
}
moduleAfter, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
if err != nil || !bytes.Equal(moduleAfter, moduleBefore) {
t.Fatalf("selected module go.mod changed: got %q want %q error=%v", moduleAfter, moduleBefore, err)
} }
return osName, arch
} }
func runModuleSelector(t *testing.T, helper, mode, value, mapPath string) string { func runModuleSelector(t *testing.T, helper, mode, value, mapPath string) string {

View File

@@ -1,6 +1,8 @@
package main package main
import ( import (
"bytes"
"debug/elf"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -11,11 +13,14 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"sync" "sync"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
) )
func TestMultiModuleWoodpeckerDelivery(t *testing.T) { func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
@@ -30,7 +35,7 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
command := strings.ReplaceAll(block, "$${", "${") command := strings.ReplaceAll(block, "$${", "${")
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*"} { for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*", "refs/tags/configuration/20*", "refs/tags/releasekit-test/*/*"} {
if !strings.Contains(string(contents), eventTag) { if !strings.Contains(string(contents), eventTag) {
t.Errorf("workflow tag filters omit %q", eventTag) t.Errorf("workflow tag filters omit %q", eventTag)
} }
@@ -38,6 +43,83 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
toolBinary := buildWorkflowCLI(t, root) toolBinary := buildWorkflowCLI(t, root)
proxy := writeWorkflowToolProxy(t) proxy := writeWorkflowToolProxy(t)
t.Run("diagnostic tag selects the committed module and profile", func(t *testing.T) {
attemptID := strings.Repeat("a", 32)
tag := "releasekit-test/ckconfig/" + attemptID
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeMappedProfile(t, repository, "releasekit-ckconfig.json", cli.Settings{Product: "Example Consumer Integration", ModuleDir: "integrations/ckconfig", Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "ckconfig"}})
cliGitRun(t, repository, "add", "--all")
cliGitRun(t, repository, "commit", "-m", "capture diagnostic selection")
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, "HEAD", "releasekit-ckconfig.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "ckconfig", captured.Commit, attemptID)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attemptID, "ckconfig", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
t.Fatal(err)
}
remote := filepath.Join(filepath.Dir(repository), "origin.git")
cliGitRun(t, repository, "init", "--bare", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+tag)
delivery.update(func(data *mappedDeliveryData) { data.commit = captured.Commit })
env := multiModuleWorkflowEnvironment(t, repository, captured.Commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
t.Fatalf("result=%+v error=%v output=%s", result, err, output)
}
})
t.Run("source-only row installs the pinned tool", func(t *testing.T) {
const tag = "configuration/2026-12-05"
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeRepositoryFile(t, repository, ".releasekit-version", "v0.2.197\n")
writeMappedProfile(t, repository, "releasekit-config.json", cli.Settings{Product: "Example Configuration", Source: &cli.SourceSettings{Dir: "configuration"}, Version: &cli.VersionSettings{Format: "date"}, Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "config"}})
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(data *mappedDeliveryData) { data.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") || delivery.snapshot().creates != 1 {
t.Fatalf("output=%s delivery=%+v", output, delivery.snapshot())
}
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, commit, "releasekit-config.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
attemptID := strings.Repeat("b", 32)
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "config", commit, attemptID)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attemptID, "config", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
t.Fatal(err)
}
cliGitRun(t, repository, "push", "origin", "refs/tags/"+identity.Tag)
delivery.update(func(data *mappedDeliveryData) { data.tag = identity.Tag; data.page = false; data.creates = 0 })
env["CI_COMMIT_TAG"] = identity.Tag
output = runWoodpeckerBlock(t, command, repository, env)
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
t.Fatalf("diagnostic result=%+v error=%v output=%s", result, err, output)
}
})
t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) { t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) {
const tag = "integrations/ckconfig/v1.2.3" const tag = "integrations/ckconfig/v1.2.3"
delivery := newMappedDeliveryFixture(t, tag) delivery := newMappedDeliveryFixture(t, tag)
@@ -55,6 +137,7 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
if output := runWoodpeckerBlock(t, command, repository, env); !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") { if output := runWoodpeckerBlock(t, command, repository, env); !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") {
t.Fatalf("tagged page delivery output = %q", output) t.Fatalf("tagged page delivery output = %q", output)
} }
assertGoSelection(t, repository, env["RELEASEKIT_GO_LOG"])
if delivery.snapshot().creates != 1 || delivery.snapshot().requests == 0 || delivery.snapshot().tag != tag { if delivery.snapshot().creates != 1 || delivery.snapshot().requests == 0 || delivery.snapshot().tag != tag {
t.Fatalf("page delivery fixture = %#v", delivery.snapshot()) t.Fatalf("page delivery fixture = %#v", delivery.snapshot())
} }
@@ -77,11 +160,15 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
t.Run("binary delivery from physical major module", func(t *testing.T) { t.Run("binary delivery from physical major module", func(t *testing.T) {
const tag = "integrations/core/v2.1.0" const tag = "integrations/core/v2.1.0"
arch, machine := "arm64", elf.EM_AARCH64
if runtime.GOOS == "linux" && runtime.GOARCH == arch {
arch, machine = "amd64", elf.EM_X86_64
}
delivery := newMappedDeliveryFixture(t, tag) delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example) repository := newWorkflowRepository(t, example)
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{ writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2", Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "core", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "core", Targets: []string{"linux/" + arch}},
Delivery: workflowDeliverySettings(delivery.snapshot().URL), Delivery: workflowDeliverySettings(delivery.snapshot().URL),
}) })
writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n") writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
@@ -97,8 +184,17 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
if observed.creates != 1 || observed.uploads != 2 || observed.tag != tag { if observed.creates != 1 || observed.uploads != 2 || observed.tag != tag {
t.Fatalf("binary delivery fixture = %#v", observed) t.Fatalf("binary delivery fixture = %#v", observed)
} }
if _, ok := observed.assets["core-v2.1.0-linux-amd64"]; !ok { name := "core-v2.1.0-linux-" + arch
t.Fatalf("binary asset missing: %#v", observed.assets) asset, ok := observed.assets[name]
if !ok {
t.Fatalf("binary asset %q missing", name)
}
binary, err := elf.NewFile(bytes.NewReader(asset))
if err != nil {
t.Fatalf("read uploaded %s as ELF: %v", name, err)
}
if binary.Machine != machine {
t.Fatalf("uploaded %s machine = %s, want %s", name, binary.Machine, machine)
} }
if _, ok := observed.assets["SHA256SUMS"]; !ok { if _, ok := observed.assets["SHA256SUMS"]; !ok {
t.Fatalf("checksum asset missing: %#v", observed.assets) t.Fatalf("checksum asset missing: %#v", observed.assets)
@@ -203,12 +299,18 @@ func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
state.mu.Lock() state.mu.Lock()
defer state.mu.Unlock() defer state.mu.Unlock()
data.requests++ data.requests++
tag := data.tag
if r.Header.Get("Authorization") != "token fixture-token" { if r.Header.Get("Authorization") != "token fixture-token" {
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization")) t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
} }
apiRoot := "/api/v1/repos/owner/example/" apiRoot := "/api/v1/repos/owner/example/"
escapedTag := url.PathEscape(tag) escapedTag := url.PathEscape(tag)
switch r.URL.EscapedPath() { switch r.URL.EscapedPath() {
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
case apiRoot + "tags/" + escapedTag: case apiRoot + "tags/" + escapedTag:
_ = json.NewEncoder(w).Encode(map[string]any{"name": tag, "commit": map[string]string{"sha": data.commit}}) _ = json.NewEncoder(w).Encode(map[string]any{"name": tag, "commit": map[string]string{"sha": data.commit}})
case apiRoot + "releases/tags/" + escapedTag: case apiRoot + "releases/tags/" + escapedTag:
@@ -302,7 +404,7 @@ func buildWorkflowCLI(t *testing.T, root string) string {
func writeWorkflowToolProxy(t *testing.T) string { func writeWorkflowToolProxy(t *testing.T) string {
t.Helper() t.Helper()
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
const helper = "example.com/releasekit-helper" const helper = "example.com/releasekit-helper"
proxyDir := t.TempDir() proxyDir := t.TempDir()
moduleFile := "module " + module + "\n\ngo 1.25.0\n\nrequire " + helper + " v1.0.0\n" moduleFile := "module " + module + "\n\ngo 1.25.0\n\nrequire " + helper + " v1.0.0\n"
@@ -331,7 +433,7 @@ func main() {
`, helper, version) `, helper, version)
files := map[string]string{ files := map[string]string{
"cmd/releasekit/main.go": main, "cmd/releasekit/main.go": main,
"buildinfo/version.go": "package buildinfo\nimport \"gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo\"\nfunc Version() string { return runtimeinfo.Version() }\n", "buildinfo/version.go": "package buildinfo\nimport \"go.maximumdirect.net/releasekit/internal/runtimeinfo\"\nfunc Version() string { return runtimeinfo.Version() }\n",
"internal/runtimeinfo/version.go": "package runtimeinfo\nvar injectedVersion string\nfunc Version() string { if injectedVersion != \"\" { return injectedVersion }; return \"dev\" }\n", "internal/runtimeinfo/version.go": "package runtimeinfo\nvar injectedVersion string\nfunc Version() string { if injectedVersion != \"\" { return injectedVersion }; return \"dev\" }\n",
} }
writeModuleProxyVersion(t, proxyDir, module, version, moduleFile, files) writeModuleProxyVersion(t, proxyDir, module, version, moduleFile, files)
@@ -362,11 +464,11 @@ func newWorkflowRepository(t *testing.T, example string) string {
} }
func workflowModuleFile(module, version string) string { func workflowModuleFile(module, version string) string {
return fmt.Sprintf("module %s\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit %s\n", module, version) return fmt.Sprintf("module %s\n\ngo 1.25.0\n\nrequire go.maximumdirect.net/releasekit %s\n", module, version)
} }
func workflowDeliverySettings(baseURL string) *cli.DeliverySettings { func workflowDeliverySettings(baseURL string) *cli.DeliverySettings {
return &cli.DeliverySettings{BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"} return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}}
} }
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) { func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {
@@ -395,6 +497,7 @@ func multiModuleWorkflowEnvironment(t *testing.T, repository, commit, tag, binar
t.Helper() t.Helper()
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
environment := templateEnvironment(repository, commit, goDir, goLog) environment := templateEnvironment(repository, commit, goDir, goLog)
environment["GOOS"], environment["GOARCH"] = foreignTarget()
environment["CI_COMMIT_TAG"] = tag environment["CI_COMMIT_TAG"] = tag
environment["RELEASEKIT_TEST_BINARY"] = binary environment["RELEASEKIT_TEST_BINARY"] = binary
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy)) useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
@@ -421,7 +524,7 @@ func prepareWorkflowModuleSum(t *testing.T, repository, moduleDir, proxy string)
return nil return nil
}) })
}) })
command := exec.Command("go", "mod", "download", "gitea.maximumdirect.net/eric/ReleaseKit@v0.2.197") command := exec.Command("go", "mod", "download", "go.maximumdirect.net/releasekit@v0.2.197")
command.Dir = filepath.Join(repository, filepath.FromSlash(moduleDir)) command.Dir = filepath.Join(repository, filepath.FromSlash(moduleDir))
command.Env = append(os.Environ(), "GOMODCACHE="+cache, "GOPROXY=file://"+filepath.ToSlash(proxy), "GOSUMDB=off", "GOWORK=off", "GOTOOLCHAIN=local", "GOFLAGS=-modcacherw") command.Env = append(os.Environ(), "GOMODCACHE="+cache, "GOPROXY=file://"+filepath.ToSlash(proxy), "GOSUMDB=off", "GOWORK=off", "GOTOOLCHAIN=local", "GOFLAGS=-modcacherw")
if output, err := command.CombinedOutput(); err != nil { if output, err := command.CombinedOutput(); err != nil {

View File

@@ -0,0 +1,616 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
"golang.org/x/mod/modfile"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/publish"
)
func TestSourceOnlyPublicationRecoveryAfterLauncherExit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("fixture executes POSIX recovery commands")
}
repo, remote := newSimplePublishRepository(t, false)
cliGitRun(t, repo, "rm", "go.mod")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","source":{},"version":{"format":"date"}}`)
writeRepositoryFile(t, repo, "docs/releases/2026-12-01.md", "# Example Product 2026-12-01\n\nRelease.\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "Configure source only publication")
cliGitRun(t, repo, "push", "origin", "main")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
executable := filepath.Join(t.TempDir(), "releasekit")
build := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", executable, "./cmd/releasekit")
build.Dir = repositoryRoot(t)
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build CLI: %v: %s", err, output)
}
launcher := exec.Command(executable, "publish", "--repo", repo, "2026-12-01")
output, err := launcher.CombinedOutput()
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("publication: %v: %s", err, output)
}
command := outputLineValue(string(output), "recovery command: ")
if command == "" || !strings.Contains(command, shellQuote(executable)) {
t.Fatalf("missing installed tool handoff: %s", output)
}
recovery := exec.Command("sh", "-c", command)
recovery.Dir = t.TempDir()
recovered, err := recovery.CombinedOutput()
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 || !strings.Contains(string(recovered), "tag=2026-12-01 state=not_published") {
t.Fatalf("source recovery: %v: %s", err, recovered)
}
}
func TestVendoredAPIOnlyPublicationRecovery(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("fixture executes POSIX recovery commands")
}
repo, remote := newSimplePublishRepository(t, false)
source := repositoryRoot(t)
relative, err := filepath.Rel(repo, source)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => "+strconv.Quote(relative)+"\n")
writeRepositoryFile(t, repo, "uses_releasekit.go", "package candidate\nimport _ \"go.maximumdirect.net/releasekit\"\n")
sums, err := os.ReadFile(filepath.Join(source, "go.sum"))
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "go.sum", string(sums))
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
for _, args := range [][]string{{"mod", "tidy"}, {"mod", "vendor"}} {
command := exec.Command(goBinary, args...)
command.Dir = repo
if out, err := command.CombinedOutput(); err != nil {
t.Fatalf("prepare vendored API: %v: %s", err, out)
}
}
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "Vendor API dependency")
cliGitRun(t, repo, "push", "origin", "main")
before := cliGitOutput(t, repo, "rev-parse", "HEAD^{tree}")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
launcherStore := t.TempDir()
launcherArgs, err := gotool.RecoveryTool(t.Context(), repo, launcherStore)
if err != nil {
t.Fatal(err)
}
launcher := exec.Command(goBinary, append(launcherArgs.Args, "publish", "--repo", repo, "v1.2.3")...)
launcher.Dir = launcherArgs.Directory
publicationOutput, err := launcher.CombinedOutput()
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("vendored publication: %v: %s", err, publicationOutput)
}
// The later handoff owns different launch metadata from the original driver.
if err := os.RemoveAll(launcherStore); err != nil {
t.Fatal(err)
}
command := outputLineValue(string(publicationOutput), "recovery command: ")
if command == "" {
t.Fatalf("no handoff: %s", publicationOutput)
}
recovery := exec.Command("sh", "-c", command)
recovery.Dir = t.TempDir()
recovered, err := recovery.CombinedOutput()
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 || !strings.Contains(string(recovered), "module=example.com/cli-candidate tag=v1.2.3 state=not_published") {
t.Fatalf("vendored recovery: %v: %s", err, recovered)
}
if status := cliGitOutput(t, repo, "status", "--porcelain"); status != "" {
t.Fatalf("handoff changed consumer files: %s", status)
}
if after := cliGitOutput(t, repo, "write-tree"); after != before {
t.Fatalf("handoff changed consumer index: %s != %s", after, before)
}
}
func TestRecoveryToolPreservesVersionedReplacement(t *testing.T) {
proxy := writeReleaseKitModuleProxy(t)
environment := make(map[string]string)
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
for key, value := range environment {
t.Setenv(key, value)
}
module := t.TempDir()
data := "module example.com/recovery-consumer\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.2.197\n\nreplace go.maximumdirect.net/releasekit v0.2.197 => go.maximumdirect.net/releasekit v0.2.198\n"
if err := os.WriteFile(filepath.Join(module, "go.mod"), []byte(data), 0600); err != nil {
t.Fatal(err)
}
shimDir := t.TempDir()
logPath := filepath.Join(t.TempDir(), "target")
realGo := filepath.Join(runtime.GOROOT(), "bin", "go")
shim := "#!/bin/sh\ncase \" $* \" in *\" -deps \"*) printf '%s/%s\\n' \"$GOOS\" \"$GOARCH\" > \"$RECOVERY_TARGET_LOG\" ;; esac\nexec \"$RECOVERY_REAL_GO\" \"$@\"\n"
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RECOVERY_TARGET_LOG", logPath)
t.Setenv("RECOVERY_REAL_GO", realGo)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
foreignOS, foreignArch := foreignTarget()
t.Setenv("GOOS", foreignOS)
t.Setenv("GOARCH", foreignArch)
args, err := gotool.RecoveryTool(t.Context(), module, t.TempDir())
if err != nil {
t.Fatal(err)
}
if target, err := os.ReadFile(logPath); err != nil || strings.TrimSpace(string(target)) != runtime.GOOS+"/"+runtime.GOARCH {
t.Fatalf("recovery preparation target = %q, %v", target, err)
}
command := exec.Command(realGo, args.Args...)
command.Dir = args.Directory
command.Env = setEnvironment(setEnvironment(os.Environ(), "GOOS", runtime.GOOS), "GOARCH", runtime.GOARCH)
output, err := command.CombinedOutput()
if err != nil || !strings.Contains(string(output), "tool-version=v0.2.198 helper=tool-only dependency") {
t.Fatalf("versioned recovery selection: %v: %s", err, output)
}
after, err := os.ReadFile(filepath.Join(module, "go.mod"))
if err != nil || string(after) != data {
t.Fatalf("consumer metadata changed: %q, %v", after, err)
}
}
func TestRecoveryToolSupportsReleaseKitSourceModule(t *testing.T) {
args, err := gotool.RecoveryTool(t.Context(), repositoryRoot(t), t.TempDir())
if err != nil {
t.Fatal(err)
}
command := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), append(args.Args, "version")...)
command.Dir = args.Directory
output, err := command.CombinedOutput()
if err != nil || !strings.HasPrefix(string(output), "releasekit ") {
t.Fatalf("source module recovery entry point: %v: %s", err, output)
}
}
func TestColdGoToolRecoverySurvivesLauncherExit(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("fixture observes the cold executable through /proc")
}
for _, mode := range []struct{ registered, canceled bool }{{true, false}, {false, false}, {true, true}, {false, true}} {
registered := mode.registered
t.Run(fmt.Sprintf("registered=%t/canceled=%t", registered, mode.canceled), func(t *testing.T) {
repo, remote := newSimplePublishRepository(t, false)
source := repositoryRoot(t)
// A distinct replacement identity gives this tool a fresh link action
// while retaining the shared compilation cache for its dependencies.
selectedSource := filepath.Join(t.TempDir(), "ReleaseKit source")
if err := os.Symlink(source, selectedSource); err != nil {
t.Fatal(err)
}
const toolModule = "go.maximumdirect.net/releasekit"
const toolVersion = "v0.0.0"
module := "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire " + toolModule + " " + toolVersion + "\n"
var wildcardSource string
if registered {
module += "\nreplace " + toolModule + " => " + strconv.Quote(selectedSource) + "\n"
module += "\ntool " + toolModule + "/cmd/releasekit\n"
} else {
wildcardSource = t.TempDir()
writeRepositoryFile(t, wildcardSource, "go.mod", "module "+toolModule+"\n\ngo 1.26.0\n")
wildcard, err := filepath.Rel(repo, wildcardSource)
if err != nil {
t.Fatal(err)
}
specific, err := filepath.Rel(repo, selectedSource)
if err != nil {
t.Fatal(err)
}
module += "\nreplace (\n" + toolModule + " => " + strconv.Quote(wildcard) + "\n" + toolModule + " " + toolVersion + " => " + strconv.Quote(specific) + "\n)\n"
}
writeRepositoryFile(t, repo, "go.mod", module)
sums, err := os.ReadFile(filepath.Join(source, "go.sum"))
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "go.sum", string(sums))
if !registered {
for _, name := range []string{"release.sh", "select-module.sh"} {
data, err := os.ReadFile(filepath.Join(source, "examples", "multi-module", name))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, name), data, 0700); err != nil {
t.Fatal(err)
}
}
writeRepositoryFile(t, repo, "release-modules.tsv", "root\tv*\t.\treleasekit.json\n")
}
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
if registered {
prepare := exec.Command(goBinary, "list", "-mod=mod", "-deps", "go.maximumdirect.net/releasekit/cmd/releasekit")
prepare.Dir = repo
if out, err := prepare.CombinedOutput(); err != nil {
t.Fatalf("prepare tool: %v: %s", err, out)
}
}
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "Select release tool")
cliGitRun(t, repo, "push", "origin", "main")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
executed := filepath.Join(t.TempDir(), "executed-tool")
wrapper := "#!/bin/sh\nparent=$(readlink \"/proc/$PPID/exe\")\ncase \"$parent\" in */exe/releasekit) printf '%s' \"$parent\" > " + shellQuote(executed) + ";; esac\n" + cancelPushScript + "exec " + shellQuote(realGit) + " \"$@\"\n"
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(wrapper), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
var launch *exec.Cmd
if registered {
launch = exec.Command(goBinary, "tool", "releasekit", "publish", "--repo", repo, "v1.2.3")
} else {
launch = exec.Command(filepath.Join(repo, "release.sh"), "root", "v1.2.3")
}
launch.Dir = repo
var out []byte
if mode.canceled {
out, err = canceledPublicationOutput(t, launch, repo, "")
} else {
out, err = launch.CombinedOutput()
}
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("publication: %v: %s", err, out)
}
text := string(out)
launchedPath, err := os.ReadFile(executed)
if err != nil {
t.Fatalf("did not exercise a cold temporary executable: %v: %s", err, text)
}
if _, err := os.Stat(string(launchedPath)); !os.IsNotExist(err) {
t.Fatalf("cold executable still exists: %s: %v", launchedPath, err)
}
entries, err := os.ReadDir(filepath.Dir(repo))
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
t.Fatalf("launcher bootstrap survived: %s", entry.Name())
}
}
command := outputLineValue(text, "recovery command: ")
if !strings.Contains(command, "go ") || strings.Contains(command, "/exe/releasekit") {
t.Fatalf("unstable handoff: %s", command)
}
if !registered {
store := filepath.Join(repo, ".git", "releasekit", "publication-recovery")
entries, err := os.ReadDir(store)
if err != nil || len(entries) != 1 {
t.Fatalf("API-only recovery modules = %v, %v", entries, err)
}
dir := filepath.Join(store, entries[0].Name())
if !strings.Contains(command, shellQuote(dir)) {
t.Fatalf("API-only handoff lacks durable metadata: %s", command)
}
path := filepath.Join(dir, "go.mod")
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
prepared, err := modfile.Parse(path, data, nil)
if err != nil {
t.Fatal(err)
}
paths := map[string]string{}
for _, replacement := range prepared.Replace {
if replacement.Old.Path == toolModule {
paths[replacement.Old.Version] = replacement.New.Path
}
}
if len(paths) != 2 || paths[""] != wildcardSource || paths[toolVersion] != selectedSource {
t.Fatalf("durable recovery lost replacement selection: %v", paths)
}
}
// Execute from another directory after the original driver and the
// API-only launcher's temporary files are gone.
originalRecord := outputLineValue(text, "publication record saved: ")
evidence, err := publish.LoadEvidence(originalRecord)
if err != nil {
t.Fatal(err)
}
evidence.Endpoint = filepath.Join(t.TempDir(), "unavailable.git")
unknownRecord, err := publish.SaveEvidence(t.Context(), repo, t.TempDir(), evidence)
if err != nil {
t.Fatal(err)
}
for _, scenario := range []struct {
record string
status int
}{{"", 1}, {filepath.Join(t.TempDir(), "missing.json"), 2}, {unknownRecord, 3}, {"", 0}} {
if scenario.status == 0 {
if err := os.Remove(filepath.Join(remote, "hooks", "pre-receive")); err != nil {
t.Fatal(err)
}
cliGitRun(t, repo, "push", "origin", "refs/tags/v1.2.3")
}
selected := command
if scenario.record != "" {
selected = strings.Replace(selected, shellQuote(originalRecord), shellQuote(scenario.record), 1)
}
foreignOS, foreignArch := foreignTarget()
goFunction := "go() { GOOS=" + shellQuote(foreignOS) + " GOARCH=" + shellQuote(foreignArch) + " command go \"$@\"; }\n"
recovery := exec.Command("sh", "-c", goFunction+selected)
recovery.Dir = t.TempDir()
recovery.Env = setEnvironment(setEnvironment(os.Environ(), "GOOS", foreignOS), "GOARCH", foreignArch)
recovered, err := recovery.CombinedOutput()
if scenario.status == 0 && err != nil || scenario.status != 0 && (!errors.As(err, &exitError) || exitError.ExitCode() != scenario.status) {
t.Fatalf("recovery status want %d: %v: %s", scenario.status, err, recovered)
}
if scenario.status == 1 && !strings.Contains(string(recovered), "state=not_published") {
t.Fatalf("wrong observation: %s", recovered)
}
}
if status := cliGitOutput(t, repo, "status", "--porcelain"); status != "" {
t.Fatalf("handoff modified candidate: %s", status)
}
})
}
}
func TestPublishRecordOverrideWarningDoesNotChangeSuccess(t *testing.T) {
repository, _ := newSimplePublishRepository(t, true)
var stdout, stderr bytes.Buffer
status := run(t.Context(), []string{"publish", "--repo", repository, "--record-dir", "record-blocker", "v1.2.3"}, &stdout, &stderr)
if status != 0 || !strings.Contains(stdout.String(), "published v1.2.3") {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "publication record warning:") || strings.Contains(stderr.String(), "publication record saved:") || strings.Contains(stderr.String(), "recovery command:") {
t.Fatalf("recording warning or success handoff output = %q", stderr.String())
}
}
func TestBuiltPublishRecoveryCommandSelectsItsRecordAmongOtherAttempts(t *testing.T) {
for _, mode := range []string{"rejected", "canceled", "preparation failure"} {
t.Run(mode, func(t *testing.T) {
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_TERMINAL_PROMPT", "0")
repository, remote := newSimplePublishRepository(t, false)
store := filepath.Join(t.TempDir(), "attempt records with ' apostrophe")
hook := filepath.Join(remote, "hooks", "pre-receive")
if err := os.WriteFile(hook, []byte("#!/bin/sh\nexit 1\n"), 0o700); err != nil {
t.Fatal(err)
}
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
executable := filepath.Join(t.TempDir(), "releasekit's CLI")
build := exec.Command(goBinary, "build", "-o", executable, "./cmd/releasekit")
build.Dir = repositoryRoot(t)
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build CLI: %v\n%s", err, output)
}
if mode == "canceled" {
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "git"), []byte("#!/bin/sh\n"+cancelPushScript+"exec "+shellQuote(realGit)+" \"$@\"\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
}
if mode == "preparation failure" {
realGo, err := exec.LookPath("go")
if err != nil {
t.Fatal(err)
}
bin := t.TempDir()
script := "#!/bin/sh\nif [ \"$1\" = list ] && [ \"$2\" = -e ]; then exit 73; fi\nexec " + shellQuote(realGo) + " \"$@\"\n"
if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
}
command := exec.Command(executable, "publish", "--repo", repository, "--record-dir", store, "v1.2.3")
command.Dir = repositoryRoot(t)
var output []byte
var err error
if mode == "canceled" {
output, err = canceledPublicationOutput(t, command, repository, store)
} else {
output, err = command.CombinedOutput()
}
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("publication exit = %v, output = %q; want status 1", err, output)
}
text := string(output)
if mode == "preparation failure" && !strings.Contains(text, "recovery tool preparation warning:") {
t.Fatalf("preparation warning missing: %s", text)
}
if !strings.Contains(text, "publication state=not_published phase=reconciliation") {
t.Fatalf("publication failure classification changed: %q", text)
}
recordPath := outputLineValue(text, "publication record saved: ")
if !filepath.IsAbs(recordPath) || !strings.Contains(recordPath, "attempt records with ' apostrophe") {
t.Fatalf("saved record path = %q, output = %q", recordPath, text)
}
recoveryCommand := outputLineValue(text, "recovery command: ")
if recoveryCommand == "" || !strings.Contains(recoveryCommand, shellQuote(executable)) || !strings.Contains(recoveryCommand, shellQuote(recordPath)) {
t.Fatalf("copyable recovery command = %q, output = %q", recoveryCommand, text)
}
if !strings.Contains(text, "selected supported ReleaseKit CLI") {
t.Fatalf("output omits guidance for an unavailable original executable: %q", text)
}
for _, decoy := range []publish.Evidence{
{RepositoryDir: repository, ModulePath: "example.com/other-module", Version: "v8.8.8", Tag: "v8.8.8", Endpoint: remote, Remote: "origin"},
{RepositoryDir: repository, ModulePath: "example.com/retry", Version: "v1.2.4", Tag: "v1.2.4", Endpoint: remote, Remote: "origin"},
} {
if _, err := publish.SaveEvidence(t.Context(), repository, store, decoy); err != nil {
t.Fatal(err)
}
}
recovery := exec.Command("/bin/sh", "-c", recoveryCommand)
recovery.Dir = t.TempDir()
recoveryOutput, recoveryErr := recovery.CombinedOutput()
if !errors.As(recoveryErr, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("recovery command exit = %v, output = %q; want known absence status 1", recoveryErr, recoveryOutput)
}
recoveryText := string(recoveryOutput)
if !strings.Contains(recoveryText, "module=example.com/cli-candidate tag=v1.2.3 state=not_published") || strings.Contains(recoveryText, "example.com/other-module") || strings.Contains(recoveryText, "example.com/retry") {
t.Fatalf("printed command selected the wrong attempt: %q", recoveryText)
}
})
}
}
func TestShellQuoteHandlesApostrophesAndSpaces(t *testing.T) {
got := shellQuote("/tmp/ReleaseKit's recovery record.json")
if got != "'/tmp/ReleaseKit'\"'\"'s recovery record.json'" {
t.Fatalf("shellQuote() = %q", got)
}
}
func newSimplePublishRepository(t *testing.T, recordBlocker bool) (string, string) {
t.Helper()
repository := newCLIRepository(t)
settings, err := json.Marshal(cli.Settings{Product: "Example Product", Remote: "origin"})
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, "releasekit.json", string(settings))
files := []string{"releasekit.json"}
if recordBlocker {
writeRepositoryFile(t, repository, "record-blocker", "tracked file\n")
files = append(files, "record-blocker")
}
cliGitRun(t, repository, append([]string{"add"}, files...)...)
cliGitRun(t, repository, "commit", "-m", "configure source release")
remote := filepath.Join(t.TempDir(), "origin.git")
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "push", "--set-upstream", "origin", "main")
return repository, remote
}
func outputLineValue(output, prefix string) string {
for _, line := range strings.Split(output, "\n") {
if strings.HasPrefix(line, prefix) {
return strings.TrimPrefix(line, prefix)
}
}
return ""
}
func repositoryRoot(t *testing.T) string {
t.Helper()
directory, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
return filepath.Clean(filepath.Join(directory, "..", ".."))
}
// The shim blocks exactly when Git would start the recorded tag push. The CLI
// PID lets the test cancel the actual operation even behind a Go driver/launcher.
const cancelPushScript = `if [ -n "$RELEASEKIT_CANCEL_PUSH_READY" ]; then
for arg in "$@"; do
if [ "$arg" = push ]; then
printf '%s' "$PPID" > "$RELEASEKIT_CANCEL_PUSH_READY"
exec sleep 600
fi
done
fi
`
func canceledPublicationOutput(t *testing.T, command *exec.Cmd, repo, store string) ([]byte, error) {
t.Helper()
ready := filepath.Join(t.TempDir(), "push-ready")
command.Env = append(os.Environ(), "RELEASEKIT_CANCEL_PUSH_READY="+ready)
var output bytes.Buffer
command.Stdout = &output
command.Stderr = &output
if err := command.Start(); err != nil {
t.Fatal(err)
}
defer command.Process.Kill()
done := make(chan error, 1)
go func() { done <- command.Wait() }()
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
defer cancel()
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
var operation *os.Process
waiting:
for {
select {
case err := <-done:
t.Fatalf("publication finished before push interception: %v: %s", err, &output)
case <-ctx.Done():
_ = command.Process.Kill()
<-done
t.Fatal("publication never reached push interception")
case <-ticker.C:
data, err := os.ReadFile(ready)
if err != nil {
continue
}
pid, err := strconv.Atoi(string(data))
if err != nil {
continue
}
operation, err = os.FindProcess(pid)
if err != nil {
t.Fatal(err)
}
defer operation.Release()
break waiting
}
}
// Check the handoff identity before allowing cancellation to reach publication.
listed, err := publish.ListAttempts(t.Context(), repo, store)
if err != nil || len(listed.Attempts) != 1 || listed.Attempts[0].Evidence.TagObject == "" {
_ = operation.Signal(os.Interrupt)
<-done
t.Fatalf("pre-push record is incomplete: %#v, %v", listed, err)
}
if err := operation.Signal(os.Interrupt); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if !strings.Contains(output.String(), "context canceled") {
t.Fatalf("publication lost its cancellation diagnostic: %s", &output)
}
return output.Bytes(), err
case <-ctx.Done():
_ = operation.Kill()
_ = command.Process.Kill()
<-done
t.Fatal("canceled publication did not return")
}
return nil, nil
}

View File

@@ -0,0 +1,351 @@
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestPublicationPushGateHelper(t *testing.T) {
address := os.Getenv("RELEASEKIT_PUSH_GATE_ADDR")
if address == "" {
return
}
connection, err := net.DialTimeout("tcp", address, 10*time.Second)
if err != nil {
t.Fatalf("connect to pre-receive gate: %v", err)
}
defer connection.Close()
if _, err := fmt.Fprintln(connection, "ready"); err != nil {
t.Fatalf("announce pre-receive readiness: %v", err)
}
response, err := bufio.NewReader(connection).ReadString('\n')
if err != nil || strings.TrimSpace(response) != "reject" {
t.Fatalf("pre-receive gate response = %q, %v", response, err)
}
// The test process is the pre-receive hook's gate. Reject only after the
// parent has observed the pre-push record and explicitly released it.
t.Fatal("controlled rejection after pre-push record observation")
}
func TestLostPublicationOutputCanBeRecoveredFromExplicitRecords(t *testing.T) {
setIsolatedGitEnvironment(t)
repository := newCLIRepository(t)
store := filepath.Join(t.TempDir(), "publication records")
checkLog := filepath.Join(t.TempDir(), "candidate checks.log")
var hostedRequests atomic.Int64
hostedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hostedRequests.Add(1)
w.WriteHeader(http.StatusNotFound)
}))
defer hostedServer.Close()
settings := cli.Settings{
Product: "Example Product",
Remote: "origin",
Checks: []cli.CheckCommand{{
Args: []string{"/bin/sh", "-c", "printf 'candidate\\n' >> \"$RELEASEKIT_CANDIDATE_LOG\""},
Env: map[string]string{"RELEASEKIT_CANDIDATE_LOG": checkLog},
}},
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: hostedServer.URL, Owner: "example", Repository: "candidate"},
}
writeSettings := func() {
t.Helper()
contents, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, "releasekit.json", string(contents))
cliGitRun(t, repository, "add", "releasekit.json")
cliGitRun(t, repository, "commit", "-m", "update publication profile")
}
writeSettings()
remote := filepath.Join(t.TempDir(), "original.git")
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "push", "--set-upstream", "origin", "main")
nestedDir := "integrations/recovery"
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "go.mod")), "module example.com/cli-candidate/recovery\n\ngo 1.25.0\n")
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "candidate_test.go")), "package recovery\nimport \"testing\"\nfunc TestFixture(t *testing.T) {}\n")
writeRepositoryFile(t, repository, filepath.ToSlash(filepath.Join(nestedDir, "docs/releases/v1.2.3.md")), "# Example Product v1.2.3\n\nRecovery fixture.\n")
cliGitRun(t, repository, "add", nestedDir)
cliGitRun(t, repository, "commit", "-m", "add nested module")
cliGitRun(t, repository, "push", "origin", "main")
installPushGate(t, remote)
goBinary := filepath.Join(runtime.GOROOT(), "bin", "go")
executable := filepath.Join(t.TempDir(), "releasekit recovery workflow")
build := exec.Command(goBinary, "build", "-o", executable, "./cmd/releasekit")
build.Dir = repositoryRoot(t)
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build CLI: %v\n%s", err, output)
}
testBinary, err := os.Executable()
if err != nil {
t.Fatal(err)
}
rootTag := "v1.2.3"
rootRecord := rejectPublicationAfterRecording(t, executable, testBinary, repository, store, rootTag, "")
if rootRecord.Evidence.ModuleDir != repository || rootRecord.Evidence.Tag != rootTag {
t.Fatalf("root attempt evidence = %#v", rootRecord.Evidence)
}
settings.ModuleDir = nestedDir
writeSettings()
cliGitRun(t, repository, "push", "origin", "main")
nestedTag := nestedDir + "/v1.2.3"
nestedRecord := rejectPublicationAfterRecording(t, executable, testBinary, repository, store, nestedTag, nestedDir)
if nestedRecord.Evidence.ModuleDir != filepath.Join(repository, nestedDir) || nestedRecord.Evidence.Tag != nestedTag {
t.Fatalf("nested attempt evidence = %#v", nestedRecord.Evidence)
}
if rootRecord.RecordPath == nestedRecord.RecordPath {
t.Fatalf("publication attempts reused record path %q", rootRecord.RecordPath)
}
// Replace the rejected root tag on the original endpoint with a different
// annotated object, then make the current checkout point somewhere else.
hook := filepath.Join(remote, "hooks", "pre-receive")
if err := os.Remove(hook); err != nil {
t.Fatal(err)
}
cliGitRun(t, repository, "tag", "-f", "-a", rootTag, "-m", "remote replacement after failed attempt", "HEAD")
cliGitRun(t, repository, "push", "origin", "refs/tags/"+rootTag)
decoyRemote := filepath.Join(t.TempDir(), "replacement-origin.git")
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", decoyRemote)
cliGitRun(t, repository, "remote", "set-url", "origin", decoyRemote)
cliGitRun(t, repository, "switch", "-c", "recovery-inspection")
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "move recovery checkout")
cliGitRun(t, repository, "tag", "-d", rootTag, nestedTag)
writeRepositoryFile(t, repository, "untracked recovery marker", "preserve this file\n")
before := snapshotRecoveryRepository(t, repository, remote, rootRecord.RecordPath, nestedRecord.RecordPath)
listing := runCLIJSON(t, executable, t.TempDir(), "publication-attempts", "--repo", repository, "--record-dir", store, "--json")
var listed struct {
Attempts []struct {
RecordPath string `json:"record_path"`
Evidence struct {
Tag string `json:"tag"`
ModuleDir string `json:"module_dir"`
} `json:"evidence"`
} `json:"attempts"`
}
if err := json.Unmarshal(listing, &listed); err != nil {
t.Fatalf("decode publication-attempts output: %v\n%s", err, listing)
}
selectedRoot := ""
selectedNested := ""
for _, attempt := range listed.Attempts {
switch attempt.Evidence.Tag {
case rootTag:
selectedRoot = attempt.RecordPath
case nestedTag:
selectedNested = attempt.RecordPath
}
}
if selectedRoot != rootRecord.RecordPath || selectedNested != nestedRecord.RecordPath {
t.Fatalf("discovery selected root=%q nested=%q; want %q and %q; listing=%s", selectedRoot, selectedNested, rootRecord.RecordPath, nestedRecord.RecordPath, listing)
}
rootResult := runCLIStatusJSON(t, executable, t.TempDir(), "reconcile", "--record", selectedRoot, "--json")
if rootResult.status != 1 || rootResult.document["state"] != "conflict" {
t.Fatalf("explicit root reconciliation status=%d document=%s; want conflict on the recorded original endpoint", rootResult.status, rootResult.output)
}
nestedResult := runCLIStatusJSON(t, executable, t.TempDir(), "reconcile", "--record", selectedNested, "--json")
if nestedResult.status != 1 || nestedResult.document["state"] != "not_published" {
t.Fatalf("explicit nested reconciliation status=%d document=%s; want not_published", nestedResult.status, nestedResult.output)
}
if got := hostedRequests.Load(); got != 0 {
t.Fatalf("later recovery made %d hosted delivery requests", got)
}
after := snapshotRecoveryRepository(t, repository, remote, rootRecord.RecordPath, nestedRecord.RecordPath)
if before != after {
t.Fatalf("reconciliation changed local or saved state:\nbefore: %#v\nafter: %#v", before, after)
}
checkBytes, err := os.ReadFile(checkLog)
if err != nil {
t.Fatal(err)
}
if got := strings.Count(string(checkBytes), "candidate\n"); got != 2 {
t.Fatalf("candidate checks ran %d times; want once per publication and none during recovery: %q", got, checkBytes)
}
}
type listedAttempt struct {
RecordPath string
Evidence releasekit.PublicationEvidence
}
func rejectPublicationAfterRecording(t *testing.T, executable, testBinary, repository, store, tag, expectedModule string) listedAttempt {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
commandArgs := []string{"publish", "--repo", repository, "--record-dir", store}
if expectedModule != "" {
commandArgs = append(commandArgs, "--expected-module", expectedModule)
}
commandArgs = append(commandArgs, "v1.2.3")
command := exec.Command(executable, commandArgs...)
command.Dir = repositoryRoot(t)
command.Env = append(os.Environ(), "RELEASEKIT_PUSH_GATE_ADDR="+listener.Addr().String(), "RELEASEKIT_PUSH_GATE_TEST_BINARY="+testBinary)
command.Stdout = io.Discard
command.Stderr = io.Discard
if err := command.Start(); err != nil {
t.Fatal(err)
}
defer func() {
if command.Process != nil {
_ = command.Process.Kill()
_ = command.Wait()
}
}()
if tcpListener, ok := listener.(*net.TCPListener); ok {
if err := tcpListener.SetDeadline(time.Now().Add(90 * time.Second)); err != nil {
t.Fatal(err)
}
}
connection, err := listener.Accept()
if err != nil {
t.Fatalf("wait for pre-receive gate for %s: %v", tag, err)
}
defer connection.Close()
if tcpConnection, ok := connection.(*net.TCPConn); ok {
if err := tcpConnection.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
t.Fatal(err)
}
}
line, err := bufio.NewReader(connection).ReadString('\n')
if err != nil || strings.TrimSpace(line) != "ready" {
t.Fatalf("pre-receive gate readiness for %s = %q, %v", tag, line, err)
}
listed, err := releasekit.ListPublicationAttempts(context.Background(), releasekit.PublicationAttemptsRequest{RepositoryDir: repository, RecordDir: store})
if err != nil {
t.Fatalf("list attempts while tag push is held: %v", err)
}
var selected *releasekit.PublicationAttempt
for i := range listed.Attempts {
if listed.Attempts[i].Evidence.Tag == tag {
selected = &listed.Attempts[i]
break
}
}
if selected == nil {
t.Fatalf("pre-push record for %s was not visible before the hook continued: %#v", tag, listed.Attempts)
}
if selected.Evidence.CandidateCommit == "" || selected.Evidence.TagObject == "" || selected.Evidence.Endpoint == "" {
t.Fatalf("pre-push evidence for %s is incomplete: %#v", tag, selected.Evidence)
}
if _, err := fmt.Fprintln(connection, "reject"); err != nil {
t.Fatalf("release pre-receive gate for %s: %v", tag, err)
}
waitErr := command.Wait()
command.Process = nil
if waitErr == nil {
t.Fatalf("publish %s succeeded despite the controlled rejection", tag)
} else {
var exitError *exec.ExitError
if !errors.As(waitErr, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("publish %s exit = %v; want publication failure status 1", tag, waitErr)
}
}
return listedAttempt{RecordPath: selected.RecordPath, Evidence: selected.Evidence}
}
func installPushGate(t *testing.T, remote string) {
t.Helper()
hook := filepath.Join(remote, "hooks", "pre-receive")
script := "#!/bin/sh\nwhile read old new ref; do\n case \"$ref\" in\n refs/tags/*) \"$RELEASEKIT_PUSH_GATE_TEST_BINARY\" -test.run='^TestPublicationPushGateHelper$'; exit $? ;;\n esac\ndone\nexit 0\n"
if err := os.WriteFile(hook, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
}
func setIsolatedGitEnvironment(t *testing.T) {
t.Helper()
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_TERMINAL_PROMPT", "0")
}
func runCLIJSON(t *testing.T, executable, directory string, args ...string) []byte {
t.Helper()
result := runCLIStatusJSON(t, executable, directory, args...)
if result.status != 0 {
t.Fatalf("CLI %v exited with status %d: %s", args, result.status, result.output)
}
return result.output
}
type cliJSONResult struct {
status int
output []byte
document map[string]any
}
func runCLIStatusJSON(t *testing.T, executable, directory string, args ...string) cliJSONResult {
t.Helper()
command := exec.Command(executable, args...)
command.Dir = directory
output, err := command.CombinedOutput()
status := 0
if err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) {
t.Fatalf("run CLI %v: %v\n%s", args, err, output)
}
status = exitError.ExitCode()
}
var document map[string]any
if err := json.Unmarshal(output, &document); err != nil {
t.Fatalf("decode CLI JSON for %v: %v\n%s", args, err, output)
}
return cliJSONResult{status: status, output: output, document: document}
}
type recoverySnapshot struct {
Branch string
Head string
Worktree string
LocalRefs string
RemoteRefs string
Records string
}
func snapshotRecoveryRepository(t *testing.T, repository, remote string, recordPaths ...string) recoverySnapshot {
t.Helper()
branch := cliGitOutput(t, repository, "branch", "--show-current")
head := cliGitOutput(t, repository, "rev-parse", "HEAD")
worktree := cliGitOutput(t, repository, "status", "--porcelain=v1", "--untracked-files=all")
localRefs := cliGitOutput(t, repository, "show-ref")
remoteRefs := cliGitOutput(t, remote, "show-ref")
var records strings.Builder
for _, path := range recordPaths {
contents, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read saved record %s: %v", path, err)
}
fmt.Fprintf(&records, "%s\x00%s\n", path, contents)
}
return recoverySnapshot{Branch: branch, Head: head, Worktree: worktree, LocalRefs: localRefs, RemoteRefs: remoteRefs, Records: records.String()}
}

170
cmd/releasekit/readiness.go Normal file
View File

@@ -0,0 +1,170 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
type readinessCheckDocument struct {
ID string `json:"id"`
Operation releasekit.ReadinessOperation `json:"operation"`
Status releasekit.ReadinessStatus `json:"status"`
Reason string `json:"reason,omitempty"`
Message string `json:"message"`
}
type readinessCredentialDocument struct {
Context string `json:"context"`
Source string `json:"source,omitempty"`
Declared bool `json:"declared"`
}
type readinessDocument struct {
SchemaVersion int `json:"schema_version"`
Command string `json:"command"`
InputSource string `json:"input_source"`
RepositoryDir string `json:"repository_dir,omitempty"`
Operations []releasekit.ReadinessOperation `json:"operations"`
Context string `json:"context"`
Offline bool `json:"offline"`
GitDestination string `json:"git_destination,omitempty"`
DeliveryDestination string `json:"delivery_destination,omitempty"`
Credentials []readinessCredentialDocument `json:"credentials,omitempty"`
Checks []readinessCheckDocument `json:"checks"`
}
func runValidate(ctx context.Context, invocation cli.Invocation, output io.Writer) int {
report := releasekit.ValidationReport{InputSource: "working", Context: invocation.Context, Offline: invocation.Offline}
for _, operation := range invocation.Operations {
report.Operations = append(report.Operations, releasekit.ReadinessOperation(operation))
}
var reportErr error
root, err := git.RepositoryRoot(ctx, invocation.Repository)
if err != nil {
report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "repository", Operation: "configuration", Status: releasekit.ReadinessFailed, Reason: "required_input", Message: git.DisplayDiagnostic(err.Error()), Cause: err})
reportErr = err
} else {
invocation.Repository = root
settings, loadErr := cli.LoadSettings(root, invocation.ConfigPath)
if loadErr != nil {
report.RepositoryDir = root
report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "profile", Operation: "configuration", Status: releasekit.ReadinessFailed, Reason: "configuration", Message: git.DisplayDiagnostic(loadErr.Error()), Cause: loadErr})
reportErr = loadErr
} else {
request := releasekit.ValidateRequest{RepositoryDir: root, ModuleDir: settings.ModuleDir, Source: sourceSpec(settings), Product: settings.Product, Remote: settings.Remote, ExpectedPushURL: settings.ExpectedPushURL, Context: invocation.Context, Offline: invocation.Offline, Build: configuredBuildSpec(settings.Build), Validation: validationSpec(settings.Validation)}
for _, operation := range invocation.Operations {
request.Operations = append(request.Operations, releasekit.ReadinessOperation(operation))
}
for _, operation := range invocation.Operations {
if operation == "rehearsal" && settings.Rehearsal != nil && settings.Rehearsal.Woodpecker != nil {
request.RehearsalSelector = settings.Rehearsal.RehearsalSelector()
wood := settings.Rehearsal.Woodpecker
token, _, credentialErr := cli.ResolveWoodpeckerCredential(root, wood)
request.Woodpecker = &releasekit.WoodpeckerObservation{BaseURL: wood.BaseURL, RepositoryID: wood.RepositoryID, Workflow: wood.Workflow, Step: wood.Step, Token: token, CredentialError: credentialErr}
}
}
if settings.Readiness != nil {
request.RequiredFiles = append([]string(nil), settings.Readiness.RequiredFiles...)
}
wantsDelivery := len(invocation.Operations) == 0 && settings.Delivery != nil
for _, operation := range invocation.Operations {
if operation == "delivery" || operation == "rehearsal" {
wantsDelivery = true
}
}
if delivery := settings.Delivery; delivery != nil {
request.Destination = &releasekit.DeliveryDestination{Forge: releasekit.Forge(delivery.Forge), BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository}
if credentials := delivery.Credentials; credentials != nil {
if credentials.Local != nil {
request.Credentials = append(request.Credentials, releasekit.ReadinessCredential{Context: "local", Source: git.DisplayDiagnostic(credentials.Local.TokenFile), Declared: true})
}
if credentials.CI != nil {
name := credentials.CI.TokenEnvironmentVariable
if strings.TrimSpace(name) == "" {
name = "RELEASEKIT_DELIVERY_TOKEN"
}
request.Credentials = append(request.Credentials, releasekit.ReadinessCredential{Context: "ci", Source: git.DisplayDiagnostic(name), Declared: true})
}
}
if wantsDelivery {
token, _, tokenErr := cli.ResolveDeliveryCredential(root, delivery.Credentials, cli.CredentialContext(invocation.Context))
request.Destination.Token = token
request.CredentialError = tokenErr
}
}
var assetErr error
assetSkipped := false
if invocation.AssetsDir != "" {
if !wantsDelivery {
assetErr = fmt.Errorf("--assets requires delivery selection")
} else {
selection, selectionErr := releaseidentity.ResolveWorkingSource(root, settings.ModuleDir, settings.SourceSpec())
if selectionErr != nil {
assetSkipped = true
} else {
directory := artifact.OutputDirectory(selection.ModuleDir, invocation.AssetsDir)
receipt, receiptErr := cli.LoadBuildReceipt(filepath.Join(directory, cli.BuildReceiptName))
if receiptErr != nil {
assetErr = receiptErr
} else {
request.Prebuilt = buildResultFromReceipt(receipt)
}
}
}
}
report, reportErr = releasekit.Validate(ctx, request)
if assetSkipped {
report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "prebuilt", Operation: releasekit.ReadinessDelivery, Status: releasekit.ReadinessSkipped, Reason: "dependency", Message: "selected source unavailable"})
}
if assetErr != nil {
report.Checks = append(report.Checks, releasekit.ReadinessResult{ID: "prebuilt", Operation: releasekit.ReadinessDelivery, Status: releasekit.ReadinessFailed, Reason: "configuration", Message: git.DisplayDiagnostic(assetErr.Error()), Cause: assetErr})
reportErr = assetErr
}
}
}
if err := writeReadinessReport(output, invocation.JSON, report); err != nil {
return 1
}
if reportErr == nil {
return 0
}
if ctx.Err() != nil {
return 1
}
for _, check := range report.Checks {
if check.Status == releasekit.ReadinessFailed && (check.Reason == "configuration" || check.Reason == "required_input") {
return 2
}
}
return 1
}
func writeReadinessReport(output io.Writer, structured bool, report releasekit.ValidationReport) error {
document := readinessDocument{SchemaVersion: 1, Command: "validate", InputSource: report.InputSource, RepositoryDir: git.DisplayDiagnostic(report.RepositoryDir), Operations: append([]releasekit.ReadinessOperation{}, report.Operations...), Context: report.Context, Offline: report.Offline, GitDestination: git.DisplayURL(report.GitDestination), DeliveryDestination: git.DisplayDiagnostic(report.DeliveryDestination), Checks: make([]readinessCheckDocument, 0, len(report.Checks))}
for _, credential := range report.Credentials {
document.Credentials = append(document.Credentials, readinessCredentialDocument{Context: credential.Context, Source: git.DisplayDiagnostic(credential.Source), Declared: credential.Declared})
}
for _, check := range report.Checks {
document.Checks = append(document.Checks, readinessCheckDocument{ID: check.ID, Operation: check.Operation, Status: check.Status, Reason: check.Reason, Message: git.DisplayDiagnostic(check.Message)})
}
if structured {
return json.NewEncoder(output).Encode(document)
}
if _, err := fmt.Fprintf(output, "readiness source=%s context=%s offline=%t operations=%v\n", document.InputSource, document.Context, document.Offline, document.Operations); err != nil {
return err
}
for _, check := range document.Checks {
if _, err := fmt.Fprintf(output, "%s %s [%s]: %s\n", check.Status, check.ID, check.Operation, check.Message); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,330 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestValidateReportsUnavailableOnlineObservation(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Errorf("unexpected remote write %s", r.Method)
}
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{}}}}`, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
if status != 1 || !strings.Contains(output.String(), `"reason":"remote"`) || strings.Contains(output.String(), "fixture-token") {
t.Fatalf("status=%d output=%s", status, &output)
}
}
func TestValidateAggregatesDestinationAndCredentialFailures(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":"ssh://invalid","owner":"owner","repository":"example","credentials":{"local":{"token_file":"missing"}}}}`)
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
if status != 2 || !strings.Contains(output.String(), `"id":"delivery-inputs","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-credential","operation":"delivery","status":"failed"`) || !strings.Contains(output.String(), `"id":"delivery-access","operation":"delivery","status":"skipped"`) {
t.Fatalf("status=%d output=%s", status, &output)
}
}
func TestValidatePrebuiltInputsWithoutWorkingReleaseNote(t *testing.T) {
repo := newCLIRepository(t)
build := cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}
writeDeliveryProfile(t, repo, cli.Settings{Product: "Example Product", Build: &build, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example"}})
assets, binary := writeDeliveryReceipt(t, repo, build)
if err := os.Remove(filepath.Join(repo, "docs", "releases", "v1.2.3.md")); err != nil {
t.Fatal(err)
}
var output bytes.Buffer
args := []string{"validate", "--repo", repo, "--operation", "delivery", "--offline", "--assets", assets, "--json"}
if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 0 {
t.Fatalf("status=%d report=%s", status, &output)
}
if err := os.WriteFile(binary, []byte("tampered artifact"), 0600); err != nil {
t.Fatal(err)
}
output.Reset()
if status := run(context.Background(), args, &output, &bytes.Buffer{}); status != 2 || !strings.Contains(output.String(), `"id":"prebuilt"`) {
t.Fatalf("tampered status=%d report=%s", status, &output)
}
}
func TestValidateOnlineUsesReadOnlyDeliveryPreflight(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
state := &deliveryServerState{}
server := newDeliveryServer(t, state)
defer server.Close()
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}`, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
t.Setenv("READINESS_TEST_TOKEN", "fixture-token")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--json"}, &output, &bytes.Buffer{})
if status != 0 || state.snapshot().apiRequests != 2 || state.snapshot().releaseCreates != 0 || state.snapshot().assetUploads != 0 || strings.Contains(output.String(), "fixture-token") {
t.Fatalf("status=%d requests=%d creates=%d output=%s", status, state.snapshot().apiRequests, state.snapshot().releaseCreates, &output)
}
}
func TestValidateBuildChecksInputsWithoutBuilding(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "main.go", "package main\nfunc main() {}\n")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","build":{"main_package":".","binary_name":"helper","targets":["linux/amd64"]},"checks":[{"args":["false"]}]}`)
shim := t.TempDir()
log := filepath.Join(shim, "calls")
script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$READINESS_GO_LOG\"\nif [ \"$1\" = version ]; then echo 'go version go1.27.4 linux/amd64'; exit 0; fi\nexit 99\n"
if err := os.WriteFile(filepath.Join(shim, "go"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("READINESS_GO_LOG", log)
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{})
calls, err := os.ReadFile(log)
if err != nil || status != 0 || string(calls) != "version\n" || !strings.Contains(output.String(), `"id":"go-dependencies","operation":"go","status":"unchecked"`) {
t.Fatalf("status=%d calls=%q error=%v output=%s", status, calls, err, &output)
}
if _, err := os.Stat(filepath.Join(repo, "dist")); !os.IsNotExist(err) {
t.Fatalf("validation created build outputs: %v", err)
}
writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.28.0\n")
output.Reset()
status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &bytes.Buffer{})
if status != 2 || !strings.Contains(output.String(), "older than declared Go 1.28.0") {
t.Fatalf("toolchain status=%d report=%s", status, &output)
}
}
func TestValidateOfflineInspectsWorkingSourceWithoutReleaseNote(t *testing.T) {
repo, remote := newSimplePublishRepository(t, false)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{},"readiness":{"required_files":["required.txt"]}}`)
writeRepositoryFile(t, repo, "required.txt", "local input\n")
before := cliGitOutput(t, remote, "show-ref", "--heads")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{})
var report readinessDocument
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
t.Fatalf("decode: %v: %s", err, output.String())
}
if status != 0 || report.SchemaVersion != 1 || report.Command != "validate" || report.InputSource != "working" || !report.Offline || len(report.Operations) != 1 || report.Operations[0] != "publication" {
t.Fatalf("status=%d report=%+v", status, report)
}
found := false
for _, check := range report.Checks {
if check.ID == "git-main" && check.Status == "unchecked" && check.Reason == "offline" {
found = true
}
}
if !found {
t.Fatalf("missing offline evidence: %+v", report.Checks)
}
if got := cliGitOutput(t, remote, "show-ref", "--heads"); got != before {
t.Fatalf("validation changed remote refs: %s != %s", got, before)
}
}
func TestValidatePublicationReadsMainWithoutRequiringCurrentCommit(t *testing.T) {
repo, remote := newSimplePublishRepository(t, false)
before := cliGitOutput(t, remote, "rev-parse", "refs/heads/main")
writeRepositoryFile(t, repo, "new-file", "unpublished\n")
cliGitRun(t, repo, "add", "new-file")
cliGitRun(t, repo, "commit", "-m", "unpublished work")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`)
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "publication", "--json"}, &output, &bytes.Buffer{})
if status != 0 || !strings.Contains(output.String(), `"id":"git-main","operation":"publication","status":"passed"`) {
t.Fatalf("status=%d output=%s", status, &output)
}
if got := cliGitOutput(t, remote, "rev-parse", "refs/heads/main"); got != before {
t.Fatalf("validation changed remote main to %s", got)
}
}
func TestValidateOfflineChecksGitIdentity(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{}}`)
cliGitRun(t, repo, "config", "--unset", "user.name")
cliGitRun(t, repo, "config", "--unset", "user.email")
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("GIT_COMMITTER_NAME", "")
t.Setenv("GIT_COMMITTER_EMAIL", "")
t.Setenv("EMAIL", "")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--offline", "--json"}, &output, &bytes.Buffer{})
if status != 2 || !strings.Contains(output.String(), `"id":"git-identity","operation":"publication","status":"failed"`) {
t.Fatalf("status=%d output=%s", status, &output)
}
}
func TestValidateAggregatesInputsAndKeepsCredentialContextsSeparate(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
profile := `{"product":"Config","source":{},"readiness":{"required_files":["absent"]},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"project","credentials":{"local":{"token_file":"absent-token"},"ci":{"token_environment_variable":"READINESS_TEST_TOKEN"}}}}`
writeRepositoryFile(t, repo, "releasekit.json", profile)
t.Setenv("READINESS_TEST_TOKEN", "secret-value")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{})
var report readinessDocument
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
t.Fatal(err)
}
if status != 2 || strings.Contains(output.String(), "secret-value") {
t.Fatalf("status=%d report=%s", status, &output)
}
required, destination := false, false
for _, check := range report.Checks {
if check.ID == "required-file" && check.Status == "failed" {
required = true
}
if check.ID == "delivery-inputs" && check.Status == "passed" {
destination = true
}
}
if !required || !destination {
t.Fatalf("checks = %+v", report.Checks)
}
writeRepositoryFile(t, repo, "absent", "present\n")
output.Reset()
status = run(context.Background(), []string{"validate", "--repo", repo, "--context", "local", "--operation", "delivery", "--offline", "--json"}, &output, &bytes.Buffer{})
if status != 2 || strings.Contains(output.String(), "secret-value") || !strings.Contains(output.String(), "absent-token") {
t.Fatalf("local status=%d report=%s", status, &output)
}
}
func TestValidateReportsMalformedProfileAsJSON(t *testing.T) {
repo := newCLIRepository(t)
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("{"), 0600); err != nil {
t.Fatal(err)
}
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--json"}, &output, &bytes.Buffer{})
var report readinessDocument
if err := json.Unmarshal(output.Bytes(), &report); err != nil || status != 2 || len(report.Checks) != 1 || report.Checks[0].ID != "profile" {
t.Fatalf("status=%d report=%s err=%v", status, &output, err)
}
}
func TestValidateSkipsAssetsWhenSourceIsUnavailable(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{"dir":"missing"},"delivery":{"forge":"gitea","base_url":"https://gitea.example","owner":"owner","repository":"example","credentials":{"ci":{}}}}`)
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "fixture-token")
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--context", "ci", "--operation", "delivery", "--offline", "--assets", "dist", "--json"}, &output, &bytes.Buffer{})
if status != 2 || !strings.Contains(output.String(), `"id":"prebuilt","operation":"delivery","status":"skipped"`) {
t.Fatalf("status=%d output=%s", status, &output)
}
}
func TestValidateRejectsInconsistentSourceSelection(t *testing.T) {
repo := newCLIRepository(t)
for _, profile := range []string{
`{"product":"Example","go":{},"publication":{"mode":"go-module"},"version":{"format":"date"}}`,
`{"product":"Example","source":{"tag_prefix":"bad..tag"}}`,
} {
writeRepositoryFile(t, repo, "releasekit.json", profile)
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "go", "--offline", "--json"}, &output, &bytes.Buffer{})
if status != 2 || !strings.Contains(output.String(), `"id":"source","operation":"configuration","status":"failed"`) {
t.Fatalf("status=%d output=%s profile=%s", status, &output, profile)
}
}
}
func TestValidateRehearsalObservesWoodpeckerWithSeparateLocalCredential(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
state := &deliveryServerState{}
forgeServer := newDeliveryServer(t, state)
defer forgeServer.Close()
calls := 0
ciServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != http.MethodGet || r.URL.Path != "/api/repos/42" || r.Header.Get("Authorization") != "Bearer woodpecker-private-value" {
t.Errorf("unexpected Woodpecker request %s %s", r.Method, r.URL.Path)
http.Error(w, "invalid", 400)
return
}
fmt.Fprint(w, `{"id":42}`)
}))
defer ciServer.Close()
writeRepositoryFile(t, repo, "forge-token", "fixture-token\n")
writeRepositoryFile(t, repo, "ci-token", "woodpecker-private-value\n")
profile := fmt.Sprintf(`{"product":"Config","source":{},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"local":{"token_file":"forge-token"},"ci":{}}},"rehearsal":{"woodpecker":{"base_url":%q,"repository_id":42,"workflow":"release","step":"deliver","token_file":"ci-token"}}}`, forgeServer.URL, ciServer.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
var output bytes.Buffer
status := run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--json"}, &output, &bytes.Buffer{})
if status != 0 || calls != 1 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"passed"`) || strings.Contains(output.String(), "woodpecker-private-value") || strings.Contains(output.String(), "fixture-token") {
t.Fatalf("status=%d calls=%d report=%s", status, calls, output.String())
}
output.Reset()
calls = 0
status = run(context.Background(), []string{"validate", "--repo", repo, "--operation", "rehearsal", "--offline", "--json"}, &output, &bytes.Buffer{})
if status != 0 || calls != 0 || !strings.Contains(output.String(), `"id":"woodpecker-access","operation":"rehearsal","status":"unchecked","reason":"offline"`) {
t.Fatalf("offline status=%d calls=%d report=%s", status, calls, output.String())
}
}
func TestValidateChecksSelectedExecutionConfiguration(t *testing.T) {
for _, test := range []struct {
name, operation, selector string
goChecks map[string]any
missingCI, online bool
want int
}{
{name: "source race", goChecks: map[string]any{"race": true}, want: 2},
{name: "source vet", goChecks: map[string]any{"full_vet": true}, want: 2},
{name: "source compilation", goChecks: map[string]any{"compile_targets": []string{"linux/amd64"}}, want: 2},
{name: "narrow local delivery", operation: "delivery", goChecks: map[string]any{"race": true}},
{name: "missing CI offline", operation: "rehearsal", missingCI: true, want: 2},
{name: "missing CI online", operation: "rehearsal", missingCI: true, online: true, want: 2},
{name: "selector slash", operation: "rehearsal", selector: "invalid/selector", want: 2},
{name: "selector ref syntax", operation: "rehearsal", selector: "invalid..selector", want: 2},
} {
t.Run(test.name, func(t *testing.T) {
repo, _ := newSimplePublishRepository(t, false)
forge := newDeliveryServer(t, &deliveryServerState{})
defer forge.Close()
ci := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"id":42}`) }))
defer ci.Close()
writeRepositoryFile(t, repo, "forge-token", "fixture-token\n")
writeRepositoryFile(t, repo, "ci-token", "wood-token\n")
credentials := map[string]any{"local": map[string]any{"token_file": "forge-token"}}
if !test.missingCI {
credentials["ci"] = map[string]any{}
}
profile := map[string]any{"product": "Config", "source": map[string]any{}, "validation": map[string]any{"go": test.goChecks},
"delivery": map[string]any{"forge": "gitea", "base_url": forge.URL, "owner": "owner", "repository": "example", "credentials": credentials},
"rehearsal": map[string]any{"selector": test.selector, "woodpecker": map[string]any{"base_url": ci.URL, "repository_id": 42, "workflow": "release", "step": "deliver", "token_file": "ci-token"}}}
data, err := json.Marshal(profile)
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "releasekit.json", string(data))
args := []string{"validate", "--repo", repo, "--json"}
if test.operation != "" {
args = append(args, "--operation", test.operation)
}
if !test.online {
args = append(args, "--offline")
}
var output bytes.Buffer
if status := run(t.Context(), args, &output, &bytes.Buffer{}); status != test.want {
t.Fatalf("status=%d want=%d report=%s", status, test.want, &output)
}
})
}
}

275
cmd/releasekit/recovery.go Normal file
View File

@@ -0,0 +1,275 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/git"
)
type recoveryDiagnostic struct {
Kind string `json:"kind"`
Message string `json:"message"`
RecordPath string `json:"record_path,omitempty"`
MissingFields []string `json:"missing_fields,omitempty"`
}
type safeEvidence struct {
RepositoryDir string `json:"repository_dir,omitempty"`
SourceDir string `json:"source_dir,omitempty"`
SourceSubdir string `json:"source_subdir,omitempty"`
GoEnabled bool `json:"go_enabled,omitempty"`
Publication string `json:"publication_mode,omitempty"`
VersionFormat string `json:"version_format,omitempty"`
VersionPrefix string `json:"version_prefix,omitempty"`
IdentityKind string `json:"identity_kind,omitempty"`
NotePath string `json:"note_path,omitempty"`
ModuleDir string `json:"module_dir,omitempty"`
ModulePath string `json:"module_path,omitempty"`
Version string `json:"version,omitempty"`
Tag string `json:"tag,omitempty"`
CandidateCommit string `json:"candidate_commit,omitempty"`
TagObject string `json:"tag_object,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Remote string `json:"remote,omitempty"`
RecordedAt string `json:"recorded_at,omitempty"`
}
type attemptDocument struct {
RecordPath string `json:"record_path"`
Evidence safeEvidence `json:"evidence"`
}
type reconciliationDocument struct {
SchemaVersion int `json:"schema_version"`
Command string `json:"command"`
RecordPath string `json:"record_path"`
Evidence *safeEvidence `json:"evidence,omitempty"`
State string `json:"state,omitempty"`
ObservedTagObject string `json:"observed_tag_object,omitempty"`
ObservedCommit string `json:"observed_commit,omitempty"`
Diagnostic *recoveryDiagnostic `json:"diagnostic,omitempty"`
}
type attemptsDocument struct {
SchemaVersion int `json:"schema_version"`
Command string `json:"command"`
RecordDir string `json:"record_dir"`
Attempts []attemptDocument `json:"attempts"`
Diagnostics []*recoveryDiagnostic `json:"diagnostics"`
Diagnostic *recoveryDiagnostic `json:"diagnostic,omitempty"`
}
func safe(e releasekit.PublicationEvidence) safeEvidence {
return safeEvidence{
RepositoryDir: git.DisplayDiagnostic(e.RepositoryDir),
SourceDir: git.DisplayDiagnostic(e.SourceDir),
SourceSubdir: git.DisplayDiagnostic(e.SourceSubdir),
GoEnabled: e.GoEnabled,
Publication: git.DisplayDiagnostic(e.Publication),
VersionFormat: git.DisplayDiagnostic(e.VersionFormat),
VersionPrefix: git.DisplayDiagnostic(e.VersionPrefix),
IdentityKind: git.DisplayDiagnostic(e.IdentityKind),
NotePath: git.DisplayDiagnostic(e.NotePath),
ModuleDir: git.DisplayDiagnostic(e.ModuleDir),
ModulePath: git.DisplayDiagnostic(e.ModulePath),
Version: git.DisplayDiagnostic(e.Version),
Tag: git.DisplayDiagnostic(e.Tag),
CandidateCommit: git.DisplayDiagnostic(e.CandidateCommit),
TagObject: git.DisplayDiagnostic(e.TagObject),
Endpoint: git.DisplayDiagnostic(e.Endpoint),
Remote: git.DisplayDiagnostic(e.Remote),
RecordedAt: git.DisplayDiagnostic(e.RecordedAt),
}
}
func diagnostic(err error) *recoveryDiagnostic {
if err == nil {
return nil
}
var typed *releasekit.PublicationRecoveryError
if errors.As(err, &typed) {
missing := make([]string, len(typed.MissingFields))
for i, field := range typed.MissingFields {
missing[i] = git.DisplayDiagnostic(field)
}
return &recoveryDiagnostic{Kind: git.DisplayDiagnostic(typed.Kind), Message: git.DisplayError(err).Error(), RecordPath: git.DisplayDiagnostic(typed.RecordPath), MissingFields: missing}
}
return &recoveryDiagnostic{Kind: "invocation", Message: git.DisplayError(err).Error()}
}
func runRecovery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
if invocation.Command == cli.ReconcileAction {
return runReconcile(ctx, invocation, stdout, stderr)
}
listed, err := releasekit.ListPublicationAttempts(ctx, releasekit.PublicationAttemptsRequest{RepositoryDir: invocation.Repository, RecordDir: invocation.RecordDir})
return reportAttempts(listed, err, invocation.JSON, stdout, stderr)
}
func reportAttempts(listed releasekit.PublicationAttemptsResult, err error, jsonOutput bool, stdout, stderr io.Writer) int {
if jsonOutput {
attempts := make([]attemptDocument, 0, len(listed.Attempts))
for _, item := range listed.Attempts {
attempts = append(attempts, attemptDocument{RecordPath: git.DisplayDiagnostic(item.RecordPath), Evidence: safe(item.Evidence)})
}
diagnostics := make([]*recoveryDiagnostic, 0, len(listed.Diagnostics))
for _, item := range listed.Diagnostics {
diagnostics = append(diagnostics, diagnostic(item))
}
if writeErr := writeJSON(stdout, attemptsDocument{
SchemaVersion: 1,
Command: "publication-attempts",
RecordDir: git.DisplayDiagnostic(listed.RecordDir),
Attempts: attempts,
Diagnostics: diagnostics,
Diagnostic: diagnostic(err),
}); writeErr != nil {
fmt.Fprintf(stderr, "write recovery output: %v\n", git.DisplayError(writeErr))
return 1
}
} else {
fmt.Fprintf(stdout, "publication records in %s\n", git.DisplayDiagnostic(listed.RecordDir))
for _, item := range listed.Attempts {
fmt.Fprintf(stdout, "%s module=%s tag=%s commit=%s recorded-at=%s\n", git.DisplayDiagnostic(item.RecordPath), git.DisplayDiagnostic(item.Evidence.ModulePath), git.DisplayDiagnostic(item.Evidence.Tag), git.DisplayDiagnostic(item.Evidence.CandidateCommit), git.DisplayDiagnostic(item.Evidence.RecordedAt))
}
if err != nil || len(listed.Diagnostics) > 0 {
fmt.Fprintln(stderr, "discovery is incomplete")
}
for _, item := range listed.Diagnostics {
fmt.Fprintf(stderr, "record %s: %s\n", git.DisplayDiagnostic(item.RecordPath), humanDiagnostic(item))
}
if err != nil {
fmt.Fprintf(stderr, "discovery failed: %v\n", git.DisplayError(err))
}
}
if err != nil || len(listed.Diagnostics) > 0 {
return 1
}
return 0
}
func runReconcile(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
evidence, loadErr := releasekit.LoadPublicationEvidence(invocation.RecordPath)
var result releasekit.PublicationReconciliationResult
err := loadErr
if err == nil {
result, err = releasekit.ReconcilePublication(ctx, evidence)
}
status := reconciliationStatus(result.State, err)
if invocation.JSON {
dto := reconciliationDocument{SchemaVersion: 1, Command: "reconcile", RecordPath: git.DisplayDiagnostic(invocation.RecordPath)}
if loadErr == nil {
safeEvidence := safe(evidence)
dto.Evidence = &safeEvidence
dto.State = string(result.State)
dto.ObservedTagObject = result.ObservedTagObject
dto.ObservedCommit = result.ObservedCommit
}
dto.Diagnostic = diagnostic(err)
if writeErr := writeJSON(stdout, dto); writeErr != nil {
fmt.Fprintf(stderr, "write recovery output: %v\n", git.DisplayError(writeErr))
return 1
}
} else if err == nil {
fmt.Fprintf(stdout, "reconciled %s module=%s tag=%s state=%s\n", git.DisplayDiagnostic(invocation.RecordPath), git.DisplayDiagnostic(evidence.ModulePath), git.DisplayDiagnostic(evidence.Tag), result.State)
if result.State == releasekit.PublicationConflict {
fmt.Fprintf(stdout, "expected tag-object=%s commit=%s; observed tag-object=%s commit=%s\n", git.DisplayDiagnostic(evidence.TagObject), git.DisplayDiagnostic(evidence.CandidateCommit), result.ObservedTagObject, result.ObservedCommit)
} else if result.ObservedTagObject != "" || result.ObservedCommit != "" {
fmt.Fprintf(stdout, "observed tag-object=%s commit=%s\n", result.ObservedTagObject, result.ObservedCommit)
}
if guidance := reconciliationGuidance(result.State); guidance != "" {
fmt.Fprintf(stdout, "%s\n", guidance)
}
}
if err != nil && !invocation.JSON {
if loadErr == nil {
fmt.Fprintf(stdout, "reconciled %s module=%s tag=%s state=%s\n", git.DisplayDiagnostic(invocation.RecordPath), git.DisplayDiagnostic(evidence.ModulePath), git.DisplayDiagnostic(evidence.Tag), result.State)
if result.ObservedTagObject != "" || result.ObservedCommit != "" {
fmt.Fprintf(stdout, "observed tag-object=%s commit=%s\n", result.ObservedTagObject, result.ObservedCommit)
}
}
fmt.Fprintf(stderr, "reconcile %s: %s\n", git.DisplayDiagnostic(invocation.RecordPath), humanDiagnostic(err))
if guidance := recoveryGuidance(err); guidance != "" {
fmt.Fprintf(stderr, "%s\n", guidance)
}
}
return status
}
func reconciliationStatus(state releasekit.PublicationState, err error) int {
if err == nil {
switch state {
case releasekit.PublicationPublished:
return 0
case releasekit.PublicationNotPublished, releasekit.PublicationConflict:
return 1
case releasekit.PublicationUnknown:
return 3
default:
return 2
}
}
var typed *releasekit.PublicationRecoveryError
if errors.As(err, &typed) {
switch typed.Kind {
case "record_read", "record_format":
return 2
default:
return 3
}
}
return 2
}
func recoveryGuidance(err error) string {
var typed *releasekit.PublicationRecoveryError
if !errors.As(err, &typed) {
return ""
}
switch typed.Kind {
case "missing_evidence":
return "Select a record with the missing identity fields, or provide complete typed evidence through the Go API."
case "invalid_evidence":
return "Use a record with a valid full tag and Git object ID."
case "endpoint_changed":
return "Review Git URL rewrite settings and restore the captured endpoint mapping before retrying."
case "transport_configuration":
return "Review Git configuration and the supported transport settings, then retry observation."
case "canceled":
return "Retry observation with a context that allows it to complete."
case "remote_observation", "inconsistent_observation":
return "Review the Git diagnostic and the remote tag refs before taking any corrective action."
default:
return ""
}
}
func reconciliationGuidance(state releasekit.PublicationState) string {
switch state {
case releasekit.PublicationNotPublished:
return "This reports current absence only; review publication history and version policy before retrying."
case releasekit.PublicationConflict:
return "Do not replace a conflicting remote tag; verify the observed IDs and follow the repository's immutable-tag procedure."
default:
return ""
}
}
func humanDiagnostic(err error) string {
var typed *releasekit.PublicationRecoveryError
if errors.As(err, &typed) && len(typed.MissingFields) > 0 {
return git.DisplayDiagnostic(fmt.Sprintf("%s (missing fields: %s): %s", typed.Kind, strings.Join(typed.MissingFields, ", "), err.Error()))
}
return git.DisplayError(err).Error()
}
func writeJSON(writer io.Writer, value any) error {
encoder := json.NewEncoder(writer)
return encoder.Encode(value)
}

View File

@@ -0,0 +1,487 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
releasekit "go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/internal/publish"
)
func TestRecoveryEndpointSetupFailureDiagnostics(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("fixture injects Git failures through a POSIX launcher")
}
for _, test := range []struct {
name, remote, kind, guidance string
exitCode int
}{
{"unnamed configuration", "", "transport_configuration", "Git configuration", 128},
{"named configuration", "origin", "transport_configuration", "Git configuration", 128},
{"rewrite", "", "endpoint_changed", "URL rewrite", 0},
{"tooling", "", "remote_observation", "Git diagnostic", 71},
} {
t.Run(test.name, func(t *testing.T) {
repo := newCLIRepository(t)
evidence := publish.Evidence{RepositoryDir: repo, Endpoint: repo, Tag: "v1.2.3", Remote: test.remote}
path, err := publish.SaveEvidence(t.Context(), repo, t.TempDir(), evidence)
if err != nil {
t.Fatal(err)
}
if test.kind == "transport_configuration" {
file, err := os.OpenFile(filepath.Join(repo, ".git", "config"), os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
if _, err := file.WriteString("\n[broken\n"); err != nil {
t.Fatal(err)
}
if err := file.Close(); err != nil {
t.Fatal(err)
}
} else if test.kind == "endpoint_changed" {
cliGitRun(t, repo, "config", "url."+t.TempDir()+".insteadOf", repo)
}
realGit, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
marker := filepath.Join(t.TempDir(), "queried")
bin := t.TempDir()
failValidation := ""
if test.name == "tooling" {
failValidation = "[ \"$arg\" = check-ref-format ] && exit 71\n"
}
script := "#!/bin/sh\nquery=0\nget_url=0\nfor arg in \"$@\"; do\n" + failValidation + "[ \"$arg\" = ls-remote ] && query=1\n[ \"$arg\" = --get-url ] && get_url=1\ndone\nif [ \"$query\" = 1 ] && [ \"$get_url\" = 0 ]; then : > " + shellQuote(marker) + "; exit 72; fi\nexec " + shellQuote(realGit) + " \"$@\"\n"
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
loaded, err := releasekit.LoadPublicationEvidence(path)
if err != nil {
t.Fatal(err)
}
result, err := releasekit.ReconcilePublication(t.Context(), loaded)
var typed *releasekit.PublicationRecoveryError
if !errors.As(err, &typed) || typed.Kind != test.kind || result.State != releasekit.PublicationUnknown {
t.Fatalf("setup classification = %#v, %v", result, err)
}
if test.exitCode != 0 {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != test.exitCode {
t.Fatalf("lost Git cause: %v", err)
}
}
for _, structured := range []bool{false, true} {
args := []string{"reconcile", "--record", path}
if structured {
args = append(args, "--json")
}
var stdout, stderr bytes.Buffer
if status := run(t.Context(), args, &stdout, &stderr); status != 3 {
t.Fatalf("setup status=%d: %s%s", status, &stdout, &stderr)
}
if structured {
var document reconciliationDocument
if err := json.Unmarshal(stdout.Bytes(), &document); err != nil {
t.Fatal(err)
}
if document.State != "unknown" || document.Diagnostic == nil || document.Diagnostic.Kind != test.kind {
t.Fatalf("setup JSON: %s", &stdout)
}
} else if !strings.Contains(stderr.String(), test.kind) || !strings.Contains(stderr.String(), test.guidance) {
t.Fatalf("setup guidance: %s", &stderr)
}
}
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("setup failure reached remote query: %v", err)
}
})
}
}
type failingRecoveryWriter struct{ err error }
func (writer failingRecoveryWriter) Write([]byte) (int, error) { return 0, writer.err }
func TestRecoveryCommandsReportJSONWriteFailure(t *testing.T) {
repo := newCLIRepository(t)
cliGitRun(t, repo, "tag", "-a", "v1.2.3", "-m", "Release")
store := t.TempDir()
path, err := publish.SaveEvidence(t.Context(), repo, store, publish.Evidence{
RepositoryDir: repo, Endpoint: repo, Tag: "v1.2.3",
CandidateCommit: cliGitOutput(t, repo, "rev-parse", "HEAD"),
TagObject: cliGitOutput(t, repo, "rev-parse", "v1.2.3"),
})
if err != nil {
t.Fatal(err)
}
failure := errors.New("output unavailable: https://user:audit-secret@example.invalid/output")
for _, args := range [][]string{{"reconcile", "--record", path, "--json"}, {"publication-attempts", "--record-dir", store, "--json"}} {
var normal, stderr bytes.Buffer
if status := run(t.Context(), args, &normal, &stderr); status != 0 {
t.Fatalf("normal output status=%d: %s", status, &stderr)
}
stderr.Reset()
if status := run(t.Context(), args, failingRecoveryWriter{failure}, &stderr); status != 1 {
t.Fatalf("failed output status=%d: %s", status, &stderr)
}
if !strings.Contains(stderr.String(), "output unavailable") || strings.Contains(stderr.String(), "audit-secret") {
t.Fatalf("output diagnostic: %s", &stderr)
}
if args[0] == "reconcile" && !strings.Contains(normal.String(), `"state":"published"`) {
t.Fatalf("observation changed: %s", &normal)
}
}
}
func TestDiscoveryReportsPartialAttemptsAndEnumerationFailure(t *testing.T) {
listed := releasekit.PublicationAttemptsResult{
RecordDir: "records",
Attempts: []releasekit.PublicationAttempt{{RecordPath: "good.json", Evidence: releasekit.PublicationEvidence{Tag: "v1.2.3"}}},
Diagnostics: []*releasekit.PublicationRecoveryError{{Kind: "record_format", RecordPath: "broken.json"}},
}
failure := &releasekit.PublicationRecoveryError{Kind: "storage_enumeration"}
for _, jsonOutput := range []bool{false, true} {
var stdout, stderr bytes.Buffer
if status := reportAttempts(listed, failure, jsonOutput, &stdout, &stderr); status != 1 {
t.Fatalf("partial discovery status=%d", status)
}
if jsonOutput {
var document attemptsDocument
if err := json.Unmarshal(stdout.Bytes(), &document); err != nil {
t.Fatal(err)
}
if len(document.Attempts) != 1 || document.Attempts[0].RecordPath != "good.json" || len(document.Diagnostics) != 1 || document.Diagnostics[0].RecordPath != "broken.json" || document.Diagnostic == nil || document.Diagnostic.Kind != "storage_enumeration" {
t.Fatalf("partial JSON lost data: %s", &stdout)
}
} else if !strings.Contains(stdout.String(), "good.json") || !strings.Contains(stderr.String(), "broken.json") || !strings.Contains(stderr.String(), "storage_enumeration") {
t.Fatalf("partial human output lost data: %s%s", &stdout, &stderr)
}
}
}
func TestRecoveryDisplaysRedactCredentialPathsAndMetadata(t *testing.T) {
secret := "audit-secret"
raw := "https://audit-user:" + secret + "@example.invalid/attempt.json"
for _, jsonOutput := range []bool{false, true} {
args := []string{"reconcile", "--record", raw}
if jsonOutput {
args = append(args, "--json")
}
var out, diagnostics bytes.Buffer
if status := run(t.Context(), args, &out, &diagnostics); status != 2 {
t.Fatalf("load status=%d", status)
}
if strings.Contains(out.String()+diagnostics.String(), secret) {
t.Fatalf("credential leaked: %s%s", &out, &diagnostics)
}
}
repo := newCLIRepository(t)
store := t.TempDir()
evidence := publish.Evidence{RepositoryDir: raw, ModuleDir: raw, ModulePath: raw, Version: raw, Tag: raw, CandidateCommit: raw, TagObject: raw, Remote: raw, RecordedAt: raw}
path, err := publish.SaveEvidence(t.Context(), repo, store, evidence)
if err != nil {
t.Fatal(err)
}
for _, command := range [][]string{{"reconcile", "--record", path}, {"publication-attempts", "--record-dir", store}} {
for _, jsonOutput := range []bool{false, true} {
args := append([]string{}, command...)
if jsonOutput {
args = append(args, "--json")
}
var out, diagnostics bytes.Buffer
run(t.Context(), args, &out, &diagnostics)
if strings.Contains(out.String()+diagnostics.String(), secret) {
t.Fatalf("metadata leaked: %s%s", &out, &diagnostics)
}
}
}
loaded, err := publish.LoadEvidence(path)
if err != nil || loaded != evidence {
t.Fatalf("private metadata changed: %#v, %v", loaded, err)
}
var out bytes.Buffer
reportPublicationRecord(t.Context(), releasekit.PublicationResult{RecordPath: raw, Phase: releasekit.PublicationPush}, fmt.Errorf("push failed"), &out)
if strings.Contains(out.String(), secret) {
t.Fatalf("handoff leaked credentials: %s", &out)
}
}
func TestReconcileCommandClassifiesRecordsFromAnotherWorkingDirectory(t *testing.T) {
repository := newCLIRepository(t)
remote := filepath.Join(t.TempDir(), "bare remote.git")
cliGitRun(t, repository, "init", "--bare", "--initial-branch=main", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "tag", "-a", "v1.2.3", "-m", "first tag object")
cliGitRun(t, repository, "push", "origin", "refs/tags/v1.2.3")
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
tagObject := cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")
store := filepath.Join(t.TempDir(), "records with ' punctuation")
evidence := publish.Evidence{
RepositoryDir: repository,
ModuleDir: repository,
ModulePath: "example.com/cli-candidate",
Version: "v1.2.3",
Tag: "v1.2.3",
CandidateCommit: commit,
TagObject: tagObject,
Endpoint: remote,
Remote: "origin",
RecordedAt: "2026-11-02T00:00:00Z",
}
record, err := publish.SaveEvidence(t.Context(), repository, store, evidence)
if err != nil {
t.Fatal(err)
}
cliGitRun(t, repository, "switch", "-c", "changed-head")
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "change current HEAD")
cliGitRun(t, repository, "tag", "-d", "v1.2.3")
if err := os.WriteFile(filepath.Join(repository, "uncommitted recovery check.txt"), []byte("dirty"), 0o600); err != nil {
t.Fatal(err)
}
otherDirectory := t.TempDir()
relativeRecord, err := filepath.Rel(otherDirectory, record)
if err != nil {
t.Fatal(err)
}
previousDirectory, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(otherDirectory); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.Chdir(previousDirectory); err != nil {
t.Errorf("restore working directory: %v", err)
}
})
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"reconcile", "--record", relativeRecord, "--json"}, &stdout, &stderr)
if status != 0 || stderr.Len() != 0 {
t.Fatalf("published status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
var published map[string]any
if err := json.Unmarshal(stdout.Bytes(), &published); err != nil {
t.Fatalf("decode published JSON: %v; output = %q", err, stdout.String())
}
if published["state"] != string("published") || published["record_path"] != relativeRecord {
t.Fatalf("published JSON = %#v", published)
}
if _, ok := published["diagnostic"]; ok {
t.Fatalf("successful reconciliation includes a diagnostic: %#v", published)
}
evidenceJSON, ok := published["evidence"].(map[string]any)
if !ok || evidenceJSON["candidate_commit"] != commit || evidenceJSON["tag_object"] != tagObject {
t.Fatalf("safe evidence = %#v", published["evidence"])
}
if evidenceJSON["module_path"] != evidence.ModulePath || evidenceJSON["candidateCommit"] != nil {
t.Fatalf("evidence does not use the versioned snake-case shape: %#v", evidenceJSON)
}
cliGitRun(t, repository, "push", "origin", ":refs/tags/v1.2.3")
cliGitRun(t, repository, "tag", "-f", "-a", "v1.2.3", "-m", "replacement tag object")
cliGitRun(t, repository, "push", "origin", "refs/tags/v1.2.3")
var conflictOut, conflictErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", record, "--json"}, &conflictOut, &conflictErr)
if status != 1 || conflictErr.Len() != 0 {
t.Fatalf("conflict status = %d, stdout = %q, stderr = %q", status, conflictOut.String(), conflictErr.String())
}
var conflict map[string]any
if err := json.Unmarshal(conflictOut.Bytes(), &conflict); err != nil {
t.Fatal(err)
}
if conflict["state"] != string("conflict") || conflict["observed_tag_object"] == tagObject {
t.Fatalf("conflict JSON = %#v", conflict)
}
var humanOut, humanErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", record}, &humanOut, &humanErr)
if status != 1 || !strings.Contains(humanOut.String(), "expected tag-object="+tagObject) || !strings.Contains(humanOut.String(), "observed tag-object=") || !strings.Contains(humanOut.String(), "Do not replace a conflicting remote tag") {
t.Fatalf("human conflict status = %d, stdout = %q, stderr = %q", status, humanOut.String(), humanErr.String())
}
partialEvidence := evidence
partialEvidence.TagObject = cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")
partialEvidence.CandidateCommit = ""
partialRecord, err := publish.SaveEvidence(t.Context(), repository, store, partialEvidence)
if err != nil {
t.Fatal(err)
}
var unknownOut, unknownErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", partialRecord, "--json"}, &unknownOut, &unknownErr)
if status != 3 || unknownErr.Len() != 0 {
t.Fatalf("unknown status = %d, stdout = %q, stderr = %q", status, unknownOut.String(), unknownErr.String())
}
var unknown map[string]any
if err := json.Unmarshal(unknownOut.Bytes(), &unknown); err != nil {
t.Fatal(err)
}
unknownDiagnostic, ok := unknown["diagnostic"].(map[string]any)
if unknown["state"] != "unknown" || !ok || unknownDiagnostic["kind"] != "missing_evidence" {
t.Fatalf("unknown JSON = %#v", unknown)
}
var unknownHumanOut, unknownHumanErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", partialRecord}, &unknownHumanOut, &unknownHumanErr)
if status != 3 || !strings.Contains(unknownHumanOut.String(), "state=unknown") || !strings.Contains(unknownHumanErr.String(), "candidate_commit") {
t.Fatalf("human unknown status = %d, stdout = %q, stderr = %q", status, unknownHumanOut.String(), unknownHumanErr.String())
}
cliGitRun(t, repository, "push", "origin", ":refs/tags/v1.2.3")
var absentOut, absentErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", record, "--json"}, &absentOut, &absentErr)
if status != 1 || absentErr.Len() != 0 {
t.Fatalf("absent status = %d, stdout = %q, stderr = %q", status, absentOut.String(), absentErr.String())
}
var absent map[string]any
if err := json.Unmarshal(absentOut.Bytes(), &absent); err != nil {
t.Fatal(err)
}
if absent["state"] != "not_published" {
t.Fatalf("absence JSON = %#v", absent)
}
if _, ok := absent["diagnostic"]; ok {
t.Fatalf("known absence includes an unresolved diagnostic: %#v", absent)
}
var absentHumanOut, absentHumanErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", record}, &absentHumanOut, &absentHumanErr)
if status != 1 || !strings.Contains(absentHumanOut.String(), "state=not_published") || !strings.Contains(absentHumanOut.String(), "current absence only") {
t.Fatalf("human absence status = %d, stdout = %q, stderr = %q", status, absentHumanOut.String(), absentHumanErr.String())
}
brokenRecord := filepath.Join(store, "broken record's.json")
if err := os.WriteFile(brokenRecord, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
var brokenOut, brokenErr bytes.Buffer
status = run(context.Background(), []string{"reconcile", "--record", brokenRecord, "--json"}, &brokenOut, &brokenErr)
if status != 2 || brokenErr.Len() != 0 {
t.Fatalf("record-format status = %d, stdout = %q, stderr = %q", status, brokenOut.String(), brokenErr.String())
}
var broken map[string]any
if err := json.Unmarshal(brokenOut.Bytes(), &broken); err != nil {
t.Fatal(err)
}
brokenDiagnostic, ok := broken["diagnostic"].(map[string]any)
if !ok || brokenDiagnostic["kind"] != "record_format" || broken["record_path"] != brokenRecord {
t.Fatalf("record-format JSON = %#v", broken)
}
for _, field := range []string{"evidence", "state", "observed_tag_object", "observed_commit"} {
if _, ok := broken[field]; ok {
t.Errorf("record-format JSON includes %q: %#v", field, broken)
}
}
}
func TestPublicationAttemptsCommandRedactsCredentialsAndReportsPartialDiscovery(t *testing.T) {
repository := newCLIRepository(t)
store := filepath.Join(t.TempDir(), "external records")
evidence := publish.Evidence{
RepositoryDir: repository,
ModulePath: "example.com/cli-candidate",
Version: "v1.2.3",
Tag: "v1.2.3",
Endpoint: "https://cli-user:cli-secret@example.test/repository.git",
Remote: "origin",
RecordedAt: "2026-11-02T00:00:00Z",
}
if _, err := publish.SaveEvidence(t.Context(), repository, store, evidence); err != nil {
t.Fatal(err)
}
brokenPath := filepath.Join(store, "damaged.json")
if err := os.WriteFile(brokenPath, []byte(`{"format_version":99,"evidence":{}}`), 0o600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"publication-attempts", "--record-dir", store, "--json"}, &stdout, &stderr)
if status != 1 || stderr.Len() != 0 {
t.Fatalf("partial discovery status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
output := stdout.String()
if strings.Contains(output, "cli-user") || strings.Contains(output, "cli-secret") || !strings.Contains(output, "https://redacted@example.test/repository.git") {
t.Fatalf("structured discovery exposed or failed to redact endpoint credentials: %q", output)
}
var listed map[string]any
if err := json.Unmarshal(stdout.Bytes(), &listed); err != nil {
t.Fatal(err)
}
attempts, ok := listed["attempts"].([]any)
if !ok || len(attempts) != 1 {
t.Fatalf("attempts = %#v", listed["attempts"])
}
diagnostics, ok := listed["diagnostics"].([]any)
if !ok || len(diagnostics) != 1 {
t.Fatalf("diagnostics = %#v", listed["diagnostics"])
}
if listed["schema_version"] != float64(1) || listed["command"] != "publication-attempts" || listed["diagnostic"] != nil {
t.Fatalf("listing document = %#v", listed)
}
entry := attempts[0].(map[string]any)
if entry["record_path"] == "" {
t.Fatalf("attempt is missing record_path: %#v", entry)
}
entryEvidence := entry["evidence"].(map[string]any)
if entryEvidence["module_path"] != evidence.ModulePath || entryEvidence["recorded_at"] != evidence.RecordedAt {
t.Fatalf("attempt evidence = %#v", entryEvidence)
}
diagnostic := diagnostics[0].(map[string]any)
if diagnostic["kind"] != "record_format" || diagnostic["record_path"] != brokenPath {
t.Fatalf("record diagnostic = %#v", diagnostic)
}
emptyStore := filepath.Join(t.TempDir(), "empty store")
if err := os.Mkdir(emptyStore, 0o700); err != nil {
t.Fatal(err)
}
var emptyOut, emptyErr bytes.Buffer
status = run(context.Background(), []string{"publication-attempts", "--record-dir", emptyStore, "--json"}, &emptyOut, &emptyErr)
if status != 0 || emptyErr.Len() != 0 {
t.Fatalf("empty discovery status = %d, stdout = %q, stderr = %q", status, emptyOut.String(), emptyErr.String())
}
var empty map[string]any
if err := json.Unmarshal(emptyOut.Bytes(), &empty); err != nil {
t.Fatal(err)
}
if len(empty["attempts"].([]any)) != 0 || len(empty["diagnostics"].([]any)) != 0 || empty["diagnostic"] != nil {
t.Fatalf("empty listing document = %#v", empty)
}
var failedOut, failedErr bytes.Buffer
status = run(context.Background(), []string{"publication-attempts", "--record-dir", filepath.Join(emptyStore, "missing"), "--json"}, &failedOut, &failedErr)
if status != 1 || failedErr.Len() != 0 {
t.Fatalf("enumeration failure status = %d, stdout = %q, stderr = %q", status, failedOut.String(), failedErr.String())
}
var failed map[string]any
if err := json.Unmarshal(failedOut.Bytes(), &failed); err != nil {
t.Fatal(err)
}
failedDiagnostic, ok := failed["diagnostic"].(map[string]any)
if !ok || failedDiagnostic["kind"] != "storage_enumeration" {
t.Fatalf("enumeration failure JSON = %#v", failed)
}
}
func TestRecoveryArgumentErrorsUseExistingUsagePath(t *testing.T) {
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"reconcile", "--json"}, &stdout, &stderr)
if status != 2 || stdout.Len() != 0 || !strings.Contains(stderr.String(), "reconcile requires --record FILE") {
t.Fatalf("argument failure status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
if strings.Contains(stdout.String(), "schema_version") || strings.Contains(stderr.String(), fmt.Sprint("\"command\"")) {
t.Fatalf("argument failure unexpectedly used structured output: stdout=%q stderr=%q", stdout.String(), stderr.String())
}
}

250
cmd/releasekit/rehearsal.go Normal file
View File

@@ -0,0 +1,250 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/forge"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/woodpecker"
)
type rehearsalDocument struct {
SchemaVersion int `json:"schema_version"`
Command string `json:"command"`
AttemptID string `json:"attempt_id,omitempty"`
Tag string `json:"tag,omitempty"`
Commit string `json:"commit,omitempty"`
ProfilePath string `json:"profile_path,omitempty"`
ProfileSHA256 string `json:"profile_sha256,omitempty"`
Selector string `json:"selector,omitempty"`
SourceDir string `json:"source_dir,omitempty"`
DiagnosticVersion string `json:"diagnostic_version,omitempty"`
Scope string `json:"scope,omitempty"`
RecordPath string `json:"record_path,omitempty"`
TagObject string `json:"tag_object,omitempty"`
Workflow string `json:"workflow"`
Build string `json:"build"`
Verification string `json:"verification"`
Cleanup string `json:"cleanup"`
PageID int64 `json:"page_id,omitempty"`
PageURL string `json:"page_url,omitempty"`
PipelineURLs []string `json:"pipeline_urls,omitempty"`
Jobs []rehearsalJobDocument `json:"jobs,omitempty"`
Workflows []rehearsalWorkflowDocument `json:"workflows,omitempty"`
Artifacts []rehearsalArtifactDocument `json:"artifacts"`
Remaining []string `json:"remaining,omitempty"`
Diagnostics []string `json:"diagnostics,omitempty"`
}
type rehearsalJobDocument struct {
PipelineID int64 `json:"pipeline_id"`
PipelineNumber int64 `json:"pipeline_number"`
WorkflowID int64 `json:"workflow_id"`
StepID int64 `json:"step_id"`
PipelineStatus string `json:"pipeline_status"`
WorkflowState string `json:"workflow_state"`
StepState string `json:"step_state"`
}
type rehearsalWorkflowDocument struct {
PipelineID int64 `json:"pipeline_id"`
PipelineNumber int64 `json:"pipeline_number"`
ID int64 `json:"id"`
Name string `json:"name"`
State string `json:"state"`
}
type rehearsalArtifactDocument struct {
Name string `json:"name"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}
type rehearsalInputError struct{ err error }
func (err *rehearsalInputError) Error() string { return err.err.Error() }
func (err *rehearsalInputError) Unwrap() error { return err.err }
func runRehearsal(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
var result releasekit.RehearsalResult
var err error
if invocation.Command == cli.TestAction {
result, err = startRehearsal(ctx, invocation, stderr)
} else {
result, err = recoverRecordedRehearsal(ctx, invocation, stderr)
}
status := rehearsalExitStatus(invocation.Command, result, err)
if writeErr := writeRehearsalReport(stdout, invocation, result, err); writeErr != nil {
fmt.Fprintf(stderr, "write rehearsal report: %v\n", git.DisplayError(writeErr))
return 1
}
return status
}
func startRehearsal(ctx context.Context, invocation cli.Invocation, progress io.Writer) (releasekit.RehearsalResult, error) {
captured, err := cli.CaptureCommittedProfile(ctx, invocation.Repository, invocation.Ref, invocation.ConfigPath)
if err != nil {
return releasekit.RehearsalResult{}, err
}
settings := captured.Settings
if settings.Rehearsal == nil || settings.Rehearsal.Woodpecker == nil {
return releasekit.RehearsalResult{}, errors.New("rehearsal.woodpecker settings are required")
}
if settings.Delivery == nil {
return releasekit.RehearsalResult{}, errors.New("delivery settings are required")
}
forgeToken, _, err := cli.ResolveDeliveryCredential(captured.RepositoryDir, settings.Delivery.Credentials, cli.LocalCredentials)
if err != nil {
return releasekit.RehearsalResult{}, err
}
ciToken, _, err := cli.ResolveWoodpeckerCredential(captured.RepositoryDir, settings.Rehearsal.Woodpecker)
if err != nil {
return releasekit.RehearsalResult{}, err
}
configured := settings.Delivery.Credentials != nil && settings.Delivery.Credentials.CI != nil
wood := settings.Rehearsal.Woodpecker
request := releasekit.RehearsalRequest{RepositoryDir: captured.RepositoryDir, Ref: captured.Commit, ProfilePath: captured.Path, ModuleDir: settings.ModuleDir, Source: sourceSpec(settings), Product: settings.Product, Selector: settings.Rehearsal.RehearsalSelector(), Remote: settings.Remote, ExpectedPushURL: settings.ExpectedPushURL, Build: configuredBuildSpec(settings.Build), Destination: releasekit.DeliveryDestination{Forge: releasekit.Forge(settings.Delivery.Forge), BaseURL: settings.Delivery.BaseURL, Owner: settings.Delivery.Owner, Repository: settings.Delivery.Repository, Token: forgeToken}, Woodpecker: releasekit.WoodpeckerObservation{BaseURL: wood.BaseURL, RepositoryID: wood.RepositoryID, Workflow: wood.Workflow, Step: wood.Step, Token: ciToken}, CIConfigured: configured, RecordDir: invocation.RecordDir, ObservationTimeout: releasekit.RehearsalTimeout(invocation.Timeout), CleanupTimeout: releasekit.RehearsalTimeout(invocation.CleanupTimeout), Output: progress}
if settings.Readiness != nil {
request.RequiredFiles = append([]string(nil), settings.Readiness.RequiredFiles...)
}
return releasekit.Rehearse(ctx, request)
}
func recoverRecordedRehearsal(ctx context.Context, invocation cli.Invocation, progress io.Writer) (releasekit.RehearsalResult, error) {
attempt, err := rehearsal.LoadAttempt(invocation.RecordPath)
if err != nil {
return releasekit.RehearsalResult{RecordPath: invocation.RecordPath}, err
}
summary := releasekit.RehearsalResult{RecordPath: invocation.RecordPath, AttemptID: attempt.Manifest.AttemptID, Tag: attempt.Manifest.Tag, Commit: attempt.Manifest.Commit, ProfilePath: attempt.Manifest.ProfilePath, ProfileSHA256: attempt.Manifest.ProfileSHA256, Selector: attempt.Manifest.Selector, SourceDir: attempt.Manifest.SourceDir, DiagnosticVersion: attempt.Manifest.DiagnosticVersion, TagObject: attempt.TagObject, Workflow: attempt.Outcomes["workflow"], Build: attempt.Outcomes["build"], Verification: attempt.Outcomes["verification"], Cleanup: attempt.Outcomes["cleanup"]}
summary.Scope = "page"
if len(attempt.PlannedAssets) > 0 {
summary.Scope = "page-and-assets"
}
var token, woodToken string
remoteDone := attempt.Outcomes["cleanup-page"] == "complete" && attempt.Outcomes["cleanup-remote-tag"] == "complete"
if attempt.Outcomes["cleanup"] != "complete" && attempt.Outcomes["push"] != "not_attempted" && attempt.Outcomes["push"] != "not_dispatched" && !remoteDone {
token, woodToken, err = cli.ResolveRehearsalRecoveryCredentials(ctx, attempt.RepositoryDir, attempt.Manifest.Commit, attempt.Manifest.ProfilePath, attempt.Manifest.ProfileSHA256, invocation.TokenFile, invocation.WoodpeckerTokenFile)
if err != nil {
return summary, &rehearsalInputError{err: err}
}
}
request := releasekit.RehearsalRecoveryRequest{RecordPath: invocation.RecordPath, DeliveryToken: token, WoodpeckerToken: woodToken, ObservationTimeout: releasekit.RehearsalTimeout(invocation.Timeout), CleanupTimeout: releasekit.RehearsalTimeout(invocation.CleanupTimeout), Output: progress}
if invocation.Command == cli.TestResumeAction {
return releasekit.ResumeRehearsal(ctx, request)
}
return releasekit.CleanupRehearsal(ctx, request)
}
func rehearsalExitStatus(command cli.Command, result releasekit.RehearsalResult, err error) int {
if err == nil {
if command == cli.TestCleanupAction && result.Cleanup == "complete" {
return 0
}
if result.Verification == "complete" && result.Cleanup == "complete" {
return 0
}
return 1
}
var inputErr *rehearsalInputError
if errors.As(err, &inputErr) {
return 2
}
if result.Cleanup == "conflict" {
return 1
}
if result.RecordPath != "" && (result.Cleanup == "pending" || result.Cleanup == "unknown" || result.Workflow == "unknown" || result.Workflow == "waiting") {
return 3
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return 1
}
var preflight *forge.PreflightFailure
if errors.As(err, &preflight) && preflight.Kind == forge.PreflightUnavailable {
return 1
}
var ciErr *woodpecker.Error
if errors.As(err, &ciErr) && (ciErr.Status == 0 || ciErr.Status >= http.StatusInternalServerError) {
return 1
}
if errors.Is(err, git.ErrRemoteStateUnreadable) {
return 1
}
if result.RecordPath == "" || result.AttemptID == "" {
return 2
}
return 1
}
func writeRehearsalReport(output io.Writer, invocation cli.Invocation, result releasekit.RehearsalResult, err error) error {
doc := rehearsalDocument{SchemaVersion: 1, Command: string(invocation.Command), AttemptID: git.DisplayDiagnostic(result.AttemptID), Tag: git.DisplayDiagnostic(result.Tag), Commit: git.DisplayDiagnostic(result.Commit), ProfilePath: git.DisplayDiagnostic(result.ProfilePath), ProfileSHA256: git.DisplayDiagnostic(result.ProfileSHA256), Selector: git.DisplayDiagnostic(result.Selector), SourceDir: git.DisplayDiagnostic(result.SourceDir), DiagnosticVersion: git.DisplayDiagnostic(result.DiagnosticVersion), Scope: git.DisplayDiagnostic(result.Scope), RecordPath: git.DisplayDiagnostic(result.RecordPath), TagObject: git.DisplayDiagnostic(result.TagObject), Workflow: result.Workflow, Build: result.Build, Verification: result.Verification, Cleanup: result.Cleanup, PageID: result.PageID, PageURL: git.DisplayURL(result.PageURL), Artifacts: []rehearsalArtifactDocument{}}
for _, link := range result.PipelineURLs {
doc.PipelineURLs = append(doc.PipelineURLs, git.DisplayURL(link))
}
for _, j := range result.Jobs {
doc.Jobs = append(doc.Jobs, rehearsalJobDocument{PipelineID: j.PipelineID, PipelineNumber: j.PipelineNumber, WorkflowID: j.WorkflowID, StepID: j.StepID, PipelineStatus: git.DisplayDiagnostic(j.PipelineStatus), WorkflowState: git.DisplayDiagnostic(j.WorkflowState), StepState: git.DisplayDiagnostic(j.StepState)})
}
for _, w := range result.Workflows {
doc.Workflows = append(doc.Workflows, rehearsalWorkflowDocument{PipelineID: w.PipelineID, PipelineNumber: w.PipelineNumber, ID: w.ID, Name: git.DisplayDiagnostic(w.Name), State: git.DisplayDiagnostic(w.State)})
}
for _, a := range result.Artifacts {
doc.Artifacts = append(doc.Artifacts, rehearsalArtifactDocument{Name: git.DisplayDiagnostic(a.Name), Size: a.Size, SHA256: git.DisplayDiagnostic(a.SHA256)})
}
for _, s := range result.Remaining {
doc.Remaining = append(doc.Remaining, git.DisplayDiagnostic(s))
}
for _, s := range result.Diagnostics {
doc.Diagnostics = append(doc.Diagnostics, git.DisplayDiagnostic(s))
}
if err != nil {
doc.Diagnostics = append(doc.Diagnostics, git.DisplayError(err).Error())
}
if invocation.JSON {
return json.NewEncoder(output).Encode(doc)
}
if _, writeErr := fmt.Fprintf(output, "rehearsal %s tag=%s commit=%s\nworkflow=%s build=%s verification=%s cleanup=%s\n", doc.AttemptID, doc.Tag, doc.Commit, doc.Workflow, doc.Build, doc.Verification, doc.Cleanup); writeErr != nil {
return writeErr
}
for _, message := range doc.Diagnostics {
if _, err := fmt.Fprintf(output, "diagnostic: %s\n", message); err != nil {
return err
}
}
for _, resource := range doc.Remaining {
if _, err := fmt.Fprintf(output, "remaining: %s\n", resource); err != nil {
return err
}
}
for _, link := range doc.PipelineURLs {
if _, err := fmt.Fprintf(output, "pipeline: %s\n", link); err != nil {
return err
}
}
if doc.PageURL != "" {
if _, err := fmt.Fprintf(output, "release: %s\n", doc.PageURL); err != nil {
return err
}
}
if doc.RecordPath != "" {
quoted := shellQuote(doc.RecordPath)
resume := "releasekit test-resume --record " + quoted
cleanup := "releasekit test-cleanup --record " + quoted
handoff, handoffErr := executableRecoveryCommand(doc.RecordPath, "test-resume")
if handoffErr == nil {
resume = handoff
cleanup, handoffErr = executableRecoveryCommand(doc.RecordPath, "test-cleanup")
if handoffErr != nil {
cleanup = "releasekit test-cleanup --record " + quoted
}
}
if _, err := fmt.Fprintf(output, "record: %s\nresume: %s\ncleanup: %s\n", doc.RecordPath, resume, cleanup); err != nil {
return err
}
if handoffErr != nil {
if _, err := fmt.Fprintln(output, "Use a supported ReleaseKit executable if the current Go-run executable is temporary."); err != nil {
return err
}
}
}
return nil
}

View File

@@ -0,0 +1,181 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
releasekit "go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func TestRehearsalArgumentsAndDefaults(t *testing.T) {
parsed, err := cli.Parse([]string{"test", "--ref", "HEAD~1", "--timeout", "0", "--json"})
if err != nil || parsed.Ref != "HEAD~1" || parsed.Timeout != 0 || parsed.CleanupTimeout != 2*time.Minute || !parsed.JSON {
t.Fatalf("parsed=%+v error=%v", parsed, err)
}
parsed, err = cli.Parse([]string{"test-resume", "--record", "attempt.json", "--token-file", "forge", "--woodpecker-token-file", "ci"})
if err != nil || parsed.RecordPath != "attempt.json" || parsed.Timeout != 30*time.Minute || parsed.TokenFile != "forge" || parsed.WoodpeckerTokenFile != "ci" {
t.Fatalf("parsed=%+v error=%v", parsed, err)
}
for _, args := range [][]string{{"test-resume"}, {"test-cleanup", "--record", "x", "--cleanup-timeout", "0"}, {"test", "--timeout", "-1s"}, {"test", "v1.0.0"}, {"test-cleanup", "--record", "x", "--timeout", "1s"}} {
if _, err := cli.Parse(args); err == nil {
t.Fatalf("accepted %v", args)
}
}
}
func TestRehearsalJSONReportsInputFailure(t *testing.T) {
var output, diagnostics bytes.Buffer
status := run(t.Context(), []string{"test", "--repo", t.TempDir(), "--json"}, &output, &diagnostics)
var doc rehearsalDocument
if err := json.Unmarshal(output.Bytes(), &doc); err != nil || status != 2 || doc.Command != "test" || doc.SchemaVersion != 1 || len(doc.Diagnostics) == 0 {
t.Fatalf("status=%d output=%s diagnostics=%s error=%v", status, &output, &diagnostics, err)
}
}
func TestCleanupCommandSelectsExplicitRecordAndReportsSeparateOutcome(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{},"rehearsal":{}}`)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, id, "root", captured.Path, captured.Bytes)
object, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest)
if err != nil {
t.Fatal(err)
}
record := rehearsal.Attempt{Forge: "gitea", Manifest: manifest, RepositoryDir: repo, TagObject: object, Outcomes: map[string]string{"tag": "created", "push": "not_attempted", "workflow": "failed", "verification": "incomplete", "cleanup": "pending"}}
record.JobEvidence = &rehearsal.JobResult{Manifest: manifest, Scope: "page", Build: "not_requested", Delivery: "not_attempted", Verification: "not_attempted", Diagnostics: []string{"delivery credential unavailable", "prepare build dependencies", "diagnostic delivery failed"}}
store, err := rehearsal.CreateAttempt(t.Context(), repo, "", record)
if err != nil {
t.Fatal(err)
}
var output, diagnostics bytes.Buffer
status := run(t.Context(), []string{"test-cleanup", "--record", store.Path, "--json"}, &output, &diagnostics)
var doc rehearsalDocument
if err := json.Unmarshal(output.Bytes(), &doc); err != nil || status != 0 || doc.Cleanup != "complete" || doc.Verification != "incomplete" || doc.RecordPath != store.Path {
t.Fatalf("status=%d output=%s diagnostics=%s error=%v", status, &output, &diagnostics, err)
}
for _, phase := range record.JobEvidence.Diagnostics {
if !strings.Contains(output.String(), phase) {
t.Fatalf("JSON dropped job phase %q: %s", phase, &output)
}
}
if _, err := os.Stat(filepath.Join(repo, ".git", "refs", "tags", filepath.FromSlash(identity.Tag))); !os.IsNotExist(err) {
t.Fatalf("local tag remains: %v", err)
}
output.Reset()
diagnostics.Reset()
status = run(t.Context(), []string{"test-resume", "--record", store.Path, "--json"}, &output, &diagnostics)
if status != 1 || !strings.Contains(output.String(), `"cleanup":"complete"`) {
t.Fatalf("resume status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
if runtime.GOOS != "windows" {
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
command := exec.Command(binary, "test-cleanup", "--record", store.Path)
text, err := command.CombinedOutput()
for _, phase := range record.JobEvidence.Diagnostics {
if !strings.Contains(string(text), phase) {
t.Fatalf("human output dropped job phase %q: %s", phase, text)
}
}
if err != nil {
t.Fatalf("built cleanup: %v: %s", err, text)
}
handoff := outputLineValue(string(text), "cleanup: ")
if !strings.Contains(handoff, shellQuote(binary)) {
t.Fatalf("cleanup handoff does not select executable: %s", text)
}
command = exec.Command("sh", "-c", handoff)
command.Dir = t.TempDir()
if result, err := command.CombinedOutput(); err != nil {
t.Fatalf("run cleanup handoff: %v: %s", err, result)
}
}
}
func TestRehearsalExitStatusPreservesObservedOutcomes(t *testing.T) {
failure := errors.New("incomplete")
for _, test := range []struct {
command cli.Command
result releasekit.RehearsalResult
err error
want int
}{
{cli.TestAction, releasekit.RehearsalResult{Verification: "complete", Cleanup: "complete"}, nil, 0},
{cli.TestCleanupAction, releasekit.RehearsalResult{Verification: "failed", Cleanup: "complete"}, nil, 0},
{cli.TestResumeAction, releasekit.RehearsalResult{Verification: "failed", Cleanup: "complete", RecordPath: "record", AttemptID: "attempt"}, failure, 1},
{cli.TestAction, releasekit.RehearsalResult{Workflow: "waiting", Cleanup: "pending", RecordPath: "record"}, failure, 3},
{cli.TestAction, releasekit.RehearsalResult{Cleanup: "conflict", RecordPath: "record"}, failure, 1},
{cli.TestAction, releasekit.RehearsalResult{}, failure, 2},
{cli.TestCleanupAction, releasekit.RehearsalResult{Cleanup: "pending", RecordPath: "record"}, &rehearsalInputError{err: failure}, 2},
} {
if got := rehearsalExitStatus(test.command, test.result, test.err); got != test.want {
t.Fatalf("command=%s result=%+v got=%d want=%d", test.command, test.result, got, test.want)
}
}
}
func TestCleanupKnownRejectedDispatchNeedsNoRemoteCredentials(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example","source":{},"rehearsal":{}}`)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, id, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, id, "root", captured.Path, captured.Bytes)
object, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest)
if err != nil {
t.Fatal(err)
}
record := rehearsal.Attempt{Forge: "gitea", Manifest: manifest, RepositoryDir: repo, TagObject: object, Outcomes: map[string]string{"tag": "created", "push": "not_dispatched", "workflow": "failed", "verification": "incomplete", "cleanup": "pending"}}
store, err := rehearsal.CreateAttempt(t.Context(), repo, "", record)
if err != nil {
t.Fatal(err)
}
var output, diagnostics bytes.Buffer
status := run(t.Context(), []string{"test-cleanup", "--record", store.Path, "--json"}, &output, &diagnostics)
var doc rehearsalDocument
if err := json.Unmarshal(output.Bytes(), &doc); err != nil || status != 0 || doc.Cleanup != "complete" || doc.Verification != "incomplete" || doc.RecordPath != store.Path {
t.Fatalf("status=%d output=%s diagnostics=%s error=%v", status, &output, &diagnostics, err)
}
if _, err := os.Stat(filepath.Join(repo, ".git", "refs", "tags", filepath.FromSlash(identity.Tag))); !os.IsNotExist(err) {
t.Fatalf("local tag remains: %v", err)
}
output.Reset()
diagnostics.Reset()
status = run(t.Context(), []string{"test-resume", "--record", store.Path, "--json"}, &output, &diagnostics)
if status != 1 || !strings.Contains(output.String(), `"cleanup":"complete"`) {
t.Fatalf("resume status=%d output=%s diagnostics=%s", status, &output, &diagnostics)
}
}

View File

@@ -79,10 +79,11 @@ func TestReleaseCandidate(t *testing.T) {
"product": "ReleaseKit", "product": "ReleaseKit",
"checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}}, "checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}},
"delivery": map[string]any{ "delivery": map[string]any{
"base_url": "https://gitea.maximumdirect.net", "forge": "gitea",
"owner": "eric", "base_url": "https://forge.maximumdirect.net",
"repository": "ReleaseKit", "owner": "base-layer",
"token_env": "RELEASEKIT_GITEA_TOKEN", "repository": "releasekit",
"credentials": map[string]any{"ci": map[string]string{"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}},
}, },
} }
content, _ := json.Marshal(profile) content, _ := json.Marshal(profile)

View File

@@ -8,7 +8,7 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
@@ -24,7 +24,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
if profile.Build != nil && len(profile.Build.Targets) != 0 { if profile.Build != nil && len(profile.Build.Targets) != 0 {
t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets) t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets)
} }
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://gitea.maximumdirect.net" || profile.Delivery.Owner != "eric" || profile.Delivery.Repository != "ReleaseKit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" { if profile.Delivery == nil || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.Credentials == nil || profile.Delivery.Credentials.CI == nil || profile.Delivery.Credentials.CI.TokenEnvironmentVariable != "RELEASEKIT_GITEA_TOKEN" {
t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery) t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery)
} }
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit") repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
@@ -34,12 +34,22 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
} }
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test") cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test") cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
// The workflow builds the tagged CLI, including changes under test that may
// not yet be committed in the repository from which this fixture was cloned.
files := []string{"cmd/releasekit/main.go", "cmd/releasekit/readiness.go", "cmd/releasekit/diagnostic.go", "cmd/releasekit/rehearsal.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go", "readiness.go", "rehearsal.go", "internal/readiness/readiness.go", "internal/readiness/committed.go", "internal/woodpecker/client.go", "internal/git/remote.go", "internal/git/source.go", "internal/gitea/backend.go", "internal/gotool/gotool.go", "internal/build/build.go", "internal/delivery/delivery.go", "internal/delivery/diagnostic.go", "internal/rehearsal/manifest.go", "internal/rehearsal/result.go", "internal/rehearsal/cleanup.go", "internal/releaseidentity/diagnostic.go"}
for _, name := range files {
contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name)))
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, name, string(contents))
}
const version = "v1.2.3" const version = "v1.2.3"
note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" + note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" +
"[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/COPYRIGHT) |\n" + "[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/COPYRIGHT) |\n" +
"[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/LICENSE) |\n" + "[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/LICENSE) |\n" +
"[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/docs/oss/attribution.md)\n" "[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/docs/oss/attribution.md)\n"
notePath := filepath.Join(repository, "docs", "releases", version+".md") notePath := filepath.Join(repository, "docs", "releases", version+".md")
if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil { if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -47,7 +57,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil { if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
cliGitRun(t, repository, "add", "docs/releases/"+version+".md") cliGitRun(t, repository, append([]string{"add", "docs/releases/" + version + ".md"}, files...)...)
cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery") cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery")
state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}} state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}}
@@ -55,7 +65,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "ReleaseKit", Product: "ReleaseKit",
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "-a", version, "-m", "ReleaseKit v1.2.3") cliGitRun(t, repository, "tag", "-a", version, "-m", "ReleaseKit v1.2.3")

View File

@@ -24,11 +24,13 @@ func TestNativeCheckFromChildUsesRootProfileAndSuite(t *testing.T) {
} }
} }
func TestNativeBuildClassifiesInvalidVersionBeforeSourceAccess(t *testing.T) { func TestNativeBuildClassifiesInvalidVersionAfterProfileSelection(t *testing.T) {
binary := buildWorkflowCLI(t, cliRepositoryRoot(t)) binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
command := exec.Command(binary, "build", "--repo", filepath.Join(t.TempDir(), "absent"), "bad-version") repository := newCLIRepository(t)
writeRepositoryFile(t, repository, "releasekit.json", `{"product":"Example Product","build":{}}`)
command := exec.Command(binary, "build", "--repo", repository, "bad-version")
output, err := command.CombinedOutput() output, err := command.CombinedOutput()
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "stable vMAJOR.MINOR.PATCH") { if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "invalid stable version") {
t.Fatalf("invalid build error = %v, output = %s", err, output) t.Fatalf("invalid build error = %v, output = %s", err, output)
} }
} }

View File

@@ -0,0 +1,338 @@
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
func TestSourceOnlyWorkflowUsesPinFromVerifiedTag(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX workflow")
}
root := cliRepositoryRoot(t)
repo := filepath.Join(t.TempDir(), "configuration")
if err := os.Mkdir(repo, 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only"), repo)
cliGitRun(t, repo, "init", "--initial-branch=main")
cliGitRun(t, repo, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repo, "config", "user.email", "releasekit@example.test")
state := &deliveryServerState{data: deliveryServerData{tag: "2026-12-05", product: "Example Configuration"}}
server := newDeliveryServer(t, state)
defer server.Close()
profile := fmt.Sprintf(`{"product":"Example Configuration","source":{},"version":{"format":"date"},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{"token_environment_variable":"RELEASEKIT_GITEA_TOKEN"}}}}`, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.197\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "prepare configuration")
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
state.update(func(data *deliveryServerData) { data.commit = commit })
cliGitRun(t, repo, "-c", "tag.gpgsign=false", "tag", "-a", "2026-12-05", "-m", "Example Configuration 2026-12-05")
tagObject := cliGitOutput(t, repo, "rev-parse", "refs/tags/2026-12-05")
remote := filepath.Join(t.TempDir(), "origin.git")
cliGitRun(t, repo, "init", "--bare", remote)
cliGitRun(t, repo, "remote", "add", "origin", remote)
cliGitRun(t, repo, "push", "origin", "main", "refs/tags/2026-12-05")
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.198\n")
cliGitRun(t, repo, "add", ".releasekit-version")
cliGitRun(t, repo, "commit", "-m", "change tool pin")
otherCommit := cliGitOutput(t, repo, "rev-parse", "HEAD")
proxy := currentReleaseKitProxy(t, root, "v0.2.197")
environment := map[string]string{"CI_WORKSPACE": repo, "CI_COMMIT_TAG": "2026-12-05", "CI_COMMIT_SHA": tagObject, "RELEASEKIT_GITEA_TOKEN": "fixture-token", "GOOS": "windows", "GOARCH": "386"}
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
workflow, err := os.ReadFile(filepath.Join(repo, ".woodpecker", "delivery.yml"))
if err != nil {
t.Fatal(err)
}
block, err := extractWoodpeckerCommand(string(workflow), "deliver")
if err != nil {
t.Fatal(err)
}
block = strings.ReplaceAll(block, "$${", "${")
environment["CI_COMMIT_SHA"] = otherCommit
mismatch, mismatchErr := executeWoodpeckerBlock(block, repo, environment)
if mismatchErr == nil || !strings.Contains(mismatch, "resolves to commit") || state.snapshot().apiRequests != 0 {
t.Fatalf("mismatched event was not rejected before delivery: %v: %s", mismatchErr, mismatch)
}
if _, err := os.Stat(filepath.Join(repo, ".releasekit", "tools")); !os.IsNotExist(err) {
t.Fatalf("mismatched event installed a tool: %v", err)
}
environment["CI_COMMIT_SHA"] = tagObject
output := runWoodpeckerBlock(t, block, repo, environment)
if !strings.Contains(output, "state complete") || !strings.Contains(output, commit) || !strings.Contains(output, "2026-12-05") || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("workflow output = %q", output)
}
installed := filepath.Join(repo, ".releasekit", "tools", "v0.2.197", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
version, err := exec.Command(installed, "version").Output()
if err != nil || !strings.Contains(string(version), "v0.2.197") {
t.Fatalf("installed tagged tool version = %q, error = %v", version, err)
}
if status := cliGitOutput(t, repo, "status", "--porcelain", "--untracked-files=all"); status != "" {
t.Fatalf("installed tool changed checkout state: %s", status)
}
}
func TestSourceOnlyInstalledToolRecoveryAfterLauncherExit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX launcher")
}
root := cliRepositoryRoot(t)
repo, remote := newSimplePublishRepository(t, false)
if err := os.Mkdir(filepath.Join(repo, "scripts"), 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only", "scripts"), filepath.Join(repo, "scripts"))
cliGitRun(t, repo, "rm", "go.mod")
writeRepositoryFile(t, repo, ".gitignore", ".releasekit/\n")
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.197\n")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","source":{},"version":{"format":"date"}}`)
writeRepositoryFile(t, repo, "docs/releases/2026-12-01.md", "# Example Product 2026-12-01\n\nRelease.\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "configure source release")
cliGitRun(t, repo, "push", "origin", "main")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
proxy := currentReleaseKitProxy(t, root, "v0.2.197")
environment := map[string]string{}
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
for key, value := range environment {
t.Setenv(key, value)
}
launcher := exec.Command(filepath.Join(repo, "scripts", "release"), "2026-12-01")
output, err := launcher.CombinedOutput()
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("publication: %v: %s", err, output)
}
command := outputLineValue(string(output), "recovery command: ")
installed := filepath.Join(repo, ".releasekit", "tools", "v0.2.197", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
if command == "" || !strings.Contains(command, shellQuote(installed)) {
t.Fatalf("recovery did not select installed tool: %s", output)
}
shim := t.TempDir()
marker := filepath.Join(shim, "go-invoked")
if err := os.WriteFile(filepath.Join(shim, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", marker)
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
recovery := exec.Command("sh", "-c", command)
recovery.Dir = t.TempDir()
recovered, err := recovery.CombinedOutput()
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(string(recovered), "tag=2026-12-01 state=not_published") {
t.Fatalf("recovery: %v: %s", err, recovered)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("recovery invoked Go after installation: %v", err)
}
}
// currentReleaseKitProxy packages the current CLI as a synthetic tool version
// and copies its prepared dependencies into a test-owned file proxy.
func currentReleaseKitProxy(t *testing.T, root, version string) string {
t.Helper()
proxy := t.TempDir()
moduleBytes, err := os.ReadFile(filepath.Join(root, "go.mod"))
if err != nil {
t.Fatal(err)
}
declaration, err := modfile.Parse("go.mod", moduleBytes, nil)
if err != nil {
t.Fatal(err)
}
files := map[string]string{}
for _, name := range []string{"buildinfo", "cmd/releasekit", "internal"} {
err := filepath.WalkDir(filepath.Join(root, filepath.FromSlash(name)), func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
relative, err := filepath.Rel(root, path)
if err != nil {
return err
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
files[filepath.ToSlash(relative)] = string(data)
return nil
})
if err != nil {
t.Fatal(err)
}
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
data, err := os.ReadFile(filepath.Join(root, entry.Name()))
if err != nil {
t.Fatal(err)
}
files[entry.Name()] = string(data)
}
writeModuleProxyVersion(t, proxy, "go.maximumdirect.net/releasekit", version, string(moduleBytes), files)
goCommand := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "env", "GOMODCACHE")
goCommand.Dir = root
cache, err := goCommand.Output()
if err != nil {
t.Fatalf("find prepared module cache: %v", err)
}
for _, dependency := range declaration.Require {
path, err := module.EscapePath(dependency.Mod.Path)
if err != nil {
t.Fatal(err)
}
version, err := module.EscapeVersion(dependency.Mod.Version)
if err != nil {
t.Fatal(err)
}
source := filepath.Join(strings.TrimSpace(string(cache)), "cache", "download", filepath.FromSlash(path), "@v")
target := filepath.Join(proxy, filepath.FromSlash(path), "@v")
if err := os.MkdirAll(target, 0700); err != nil {
t.Fatal(err)
}
for _, suffix := range []string{".info", ".mod", ".zip"} {
name := version + suffix
contents, err := os.ReadFile(filepath.Join(source, name))
if err != nil {
t.Fatalf("read prepared dependency %s: %v", name, err)
}
if err := os.WriteFile(filepath.Join(target, name), contents, 0600); err != nil {
t.Fatal(err)
}
}
}
return proxy
}
func TestSourceOnlyToolPinInstallsHostAndRetainsExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX launcher")
}
root := cliRepositoryRoot(t)
repo := filepath.Join(t.TempDir(), "configuration")
if err := os.Mkdir(repo, 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only"), repo)
cliGitRun(t, repo, "init", "--initial-branch=main")
proxy := writeWorkflowToolProxy(t)
env := map[string]string{}
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
for key, value := range env {
t.Setenv(key, value)
}
t.Setenv("GOOS", "windows")
t.Setenv("GOARCH", "386")
stub := filepath.Join(t.TempDir(), "consumer-tool")
if err := os.WriteFile(stub, []byte("#!/bin/sh\nprintf 'delegated %s\\n' \"$*\"\nexit 23\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_BINARY", stub)
writeRepositoryFile(t, repo, ".releasekit-version", " v0.2.197\r\n")
command := func(name string, args ...string) ([]byte, error) {
process := exec.Command(filepath.Join(repo, "scripts", name), args...)
process.Dir = repo
return process.Output()
}
pathBytes, err := command("releasekit-tool")
if err != nil {
t.Fatalf("install: %v: %s", err, pathBytes)
}
path := strings.TrimSpace(string(pathBytes))
if !filepath.IsAbs(path) || !strings.Contains(path, "v0.2.197") || !strings.Contains(path, runtime.GOOS+"-"+runtime.GOARCH) {
t.Fatalf("installed path = %q", path)
}
output, err := command("releasekit", "version")
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 23 || !strings.Contains(string(output), "tool-version=v0.2.197") || !strings.Contains(string(output), "delegated version") {
t.Fatalf("launcher: %v: %s", err, output)
}
output, err = command("releasekit", "test", "--repo", repo, "--json")
if !errors.As(err, &exit) || exit.ExitCode() != 23 || !strings.Contains(string(output), "delegated test --repo "+repo+" --json") {
t.Fatalf("diagnostic invocation: %v: %s", err, output)
}
if info, err := os.Stat(path); err != nil {
t.Fatalf("installed executable did not survive launcher: %v", err)
} else if info.Mode().Perm()&0077 != 0 {
t.Fatalf("installed executable is not private: %v", info.Mode())
}
t.Setenv("GOPROXY", "off")
t.Setenv("GOMODCACHE", t.TempDir())
reused, err := command("releasekit-tool")
if err != nil || strings.TrimSpace(string(reused)) != path {
t.Fatalf("reuse without proxy: %v: %s", err, reused)
}
t.Setenv("GOPROXY", env["GOPROXY"])
t.Setenv("GOMODCACHE", env["GOMODCACHE"])
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.198\n")
other, err := command("releasekit-tool")
if err != nil || strings.TrimSpace(string(other)) == path || !strings.Contains(string(other), "v0.2.198") {
t.Fatalf("changed pin install: %v: %s", err, other)
}
for _, invalid := range []string{"", "v0.2.197 v0.2.198", "v0.2.197-rc1", "v00.2.197"} {
writeRepositoryFile(t, repo, ".releasekit-version", invalid)
output, err := command("releasekit-tool")
if !errors.As(err, &exit) || exit.ExitCode() != 2 || !strings.Contains(string(exit.Stderr), "one stable module version") {
t.Fatalf("pin %q: %v: %s", invalid, err, output)
}
}
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.199\n")
output, err = command("releasekit-tool")
if err == nil {
t.Fatalf("unavailable install succeeded: %s", output)
}
missing := filepath.Join(repo, ".releasekit", "tools", "v0.2.199", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
if _, err := os.Stat(missing); !os.IsNotExist(err) {
t.Fatalf("failed install left executable: %v", err)
}
temporary, err := filepath.Glob(filepath.Join(filepath.Dir(missing), ".install.*"))
if err != nil || len(temporary) != 0 {
t.Fatalf("failed install left temporary files: %v, error = %v", temporary, err)
}
shim := t.TempDir()
script := "#!/bin/sh\nif [ \"$1\" = install ]; then printf partial > \"$GOBIN/releasekit\"; chmod +x \"$GOBIN/releasekit\"; exit 37; fi\nexec \"$RELEASEKIT_TEST_GO\" \"$@\"\n"
if err := os.WriteFile(filepath.Join(shim, "go"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_GO", filepath.Join(runtime.GOROOT(), "bin", "go"))
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.200\n")
output, err = command("releasekit-tool")
if !errors.As(err, &exit) || exit.ExitCode() != 37 {
t.Fatalf("partial install exit = %v: %s", err, output)
}
for _, launcher := range []string{"releasekit", "release"} {
output, err = command(launcher, "version")
if !errors.As(err, &exit) || exit.ExitCode() != 37 {
t.Fatalf("%s install failure exit = %v: %s", launcher, err, output)
}
}
failedDir := filepath.Join(repo, ".releasekit", "tools", "v0.2.200", runtime.GOOS+"-"+runtime.GOARCH)
if _, err := os.Stat(filepath.Join(failedDir, "releasekit")); !os.IsNotExist(err) {
t.Fatalf("partial install left a usable executable: %v", err)
}
if temporary, err := filepath.Glob(filepath.Join(failedDir, ".install.*")); err != nil || len(temporary) != 0 {
t.Fatalf("partial install left temporary files: %v, error = %v", temporary, err)
}
}

View File

@@ -0,0 +1,174 @@
package main
import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
releasekit "go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestSourceSelectionMapsToRequest(t *testing.T) {
empty := ""
settings := cli.Settings{
ModuleDir: "app",
Source: &cli.SourceSettings{TagPrefix: &empty},
Go: &struct{}{},
Version: &cli.VersionSettings{Format: "date", Prefix: &empty},
}
request := candidateRequest(cli.Invocation{}, settings, nil)
if request.Source == nil || !request.Source.GoEnabled || request.Source.Dir != "" || string(request.Source.Publication) != "" || string(request.Source.VersionFormat) != "date" || request.Source.VersionPrefix == nil || *request.Source.VersionPrefix != "" || request.Source.TagPrefix == nil || *request.Source.TagPrefix != "" || request.ModuleDir != "app" {
t.Fatalf("mapped selection = %+v, module directory = %q", request.Source, request.ModuleDir)
}
if sourceSpec(cli.Settings{}) != nil {
t.Fatal("legacy profile was converted to an explicit source selection")
}
}
func TestCIDeliveryChecksFullCalendarTagAgainstProfile(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "config/docs/releases/2026-12-01.md", "# Config 2026-12-01\n")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Config","source":{"dir":"config"},"version":{"format":"date"}}`)
cliGitRun(t, repo, "add", "config", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "configure source release")
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
cliGitRun(t, repo, "tag", "config/2026-12-01")
cliGitRun(t, repo, "tag", "other/2026-12-01")
for _, tt := range []struct {
tag, message string
status int
}{
{tag: "other/2026-12-01", status: 1, message: "does not match"},
{tag: "config/2026-12-01", status: 2, message: "delivery.forge"},
} {
t.Run(tt.tag, func(t *testing.T) {
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"ci-deliver", "--repo", repo, "--prepared", "--expected-source", "config", "--commit", commit, tt.tag}, &stdout, &stderr)
if status != tt.status || !strings.Contains(stderr.String(), tt.message) {
t.Fatalf("status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
})
}
}
func TestCIDeliveryProductionTagsMayUseDiagnosticPrefix(t *testing.T) {
for _, legacy := range []bool{false, true} {
t.Run(fmt.Sprintf("legacy=%t", legacy), func(t *testing.T) {
repo := newCLIRepository(t)
version, tag := "2026-12-01", "releasekit-test/product/2026-12-01"
profile := `{"product":"Config","source":{"tag_prefix":"releasekit-test/product"},"version":{"format":"date"}}`
note := "docs/releases/" + version + ".md"
if legacy {
version, tag = "v1.2.3", "releasekit-test/product/v1.2.3"
profile = `{"product":"Config","module_dir":"releasekit-test/product"}`
note = "releasekit-test/product/docs/releases/" + version + ".md"
writeRepositoryFile(t, repo, "releasekit-test/product/go.mod", "module example.com/product\n\ngo 1.27.0\n")
writeRepositoryFile(t, repo, "releasekit-test/product/product.go", "package product\n")
}
writeRepositoryFile(t, repo, note, "# Config "+version+"\n")
writeRepositoryFile(t, repo, "releasekit.json", profile)
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "configure production tag prefix")
var out, diag bytes.Buffer
if code := run(t.Context(), []string{"check", "--repo", repo, version}, &out, &diag); code != 0 {
t.Fatalf("check code=%d diagnostic=%s", code, &diag)
}
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
cliGitRun(t, repo, "tag", "-a", "-m", "# Config "+version, tag)
out.Reset()
diag.Reset()
if code := run(t.Context(), []string{"ci-deliver", "--repo", repo, "--prepared", "--commit", commit, tag}, &out, &diag); code != 2 || !strings.Contains(diag.String(), "delivery.forge") {
t.Fatalf("production dispatch code=%d output=%s diagnostics=%s", code, &out, &diag)
}
})
}
}
func TestSourceCheckCommandUsesSelectedDirectoryAndEnvironment(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX shell check")
}
repo := t.TempDir()
source := filepath.Join(repo, "config")
if err := os.Mkdir(source, 0755); err != nil {
t.Fatal(err)
}
result := filepath.Join(t.TempDir(), "context")
settings := cli.Settings{Checks: []cli.CheckCommand{{
Args: []string{"sh", "-c", `printf '%s\n' "$PWD" "$RELEASEKIT_SOURCE_DIR" "$RELEASEKIT_MODULE_DIR" "$RELEASEKIT_MODULE_PATH" "$RELEASEKIT_TAG" > "$RESULT"`},
Env: map[string]string{"RESULT": result},
}}}
request := candidateRequest(cli.Invocation{}, settings, nil)
if err := request.AdditionalChecks(context.Background(), releasekit.Candidate{RepositoryDir: repo, SourceDir: source, Tag: "config/v1.0.0"}); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(result)
if err != nil {
t.Fatal(err)
}
want := strings.Join([]string{source, source, "", "", "config/v1.0.0", ""}, "\n")
if string(data) != want {
t.Fatalf("check context = %q, want %q", data, want)
}
}
func TestExpectedSourceChecksTheProfileSelection(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "config/data.json", "{}")
writeRepositoryFile(t, repo, "other/data.json", "{}")
cliGitRun(t, repo, "add", "config", "other")
cliGitRun(t, repo, "commit", "-m", "add source directories")
settings := cli.Settings{Source: &cli.SourceSettings{Dir: "config"}}
if err := checkExpectedSelection(context.Background(), repo, "config", "config", settings); err != nil {
t.Fatalf("matching expected source: %v", err)
}
if err := checkExpectedSelection(context.Background(), repo, "other", "config", settings); err == nil {
t.Fatal("accepted conflicting expected directories")
}
}
func TestCalendarBuildWritesIdentityReceipt(t *testing.T) {
repo := newCLIBuildRepository(t, `package main
import ("fmt"; "os"; "go.maximumdirect.net/releasekit/buildinfo")
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
`)
profile := fmt.Sprintf(`{"product":"Example Product","go":{},"version":{"format":"date"},"build":{"main_package":"./cmd/app","binary_name":"fixture","targets":[%q]}}`, runtime.GOOS+"/"+runtime.GOARCH)
writeRepositoryFile(t, repo, "releasekit.json", profile)
output := t.TempDir()
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"build", "--repo", repo, "--output", output, "2026-12-01.1"}, &stdout, &stderr)
if status != 0 {
t.Fatalf("build status = %d, stdout = %q, stderr = %q", status, stdout.String(), stderr.String())
}
receipt, err := cli.LoadBuildReceipt(filepath.Join(output, cli.BuildReceiptName))
if err != nil || receipt.SchemaVersion != 2 || receipt.SourceDir != repo || receipt.SourceSubdir != "." || !receipt.GoEnabled || receipt.Publication != "source" || receipt.VersionFormat != "date" || receipt.VersionPrefix != "" || receipt.IdentityKind != "production" || receipt.Version != "2026-12-01.1" || receipt.Tag != "2026-12-01.1" {
t.Fatalf("calendar receipt = %+v, error = %v", receipt, err)
}
}
func TestPackagePatternBuildAndReadinessAgree(t *testing.T) {
for _, pattern := range []string{"./...", "example.com/tagged-app/..."} {
t.Run(pattern, func(t *testing.T) {
repo := newDeliveryBuildRepository(t)
profile := fmt.Sprintf(`{"product":"Example Product","build":{"main_package":%q,"binary_name":"helper","targets":[%q]}}`, pattern, runtime.GOOS+"/"+runtime.GOARCH)
writeRepositoryFile(t, repo, "releasekit.json", profile)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "configure main package pattern")
var output, diagnostics bytes.Buffer
if code := run(t.Context(), []string{"build", "--repo", repo, "--output", t.TempDir(), "v1.2.3"}, &output, &diagnostics); code != 0 {
t.Fatalf("build code=%d error=%s", code, &diagnostics)
}
output.Reset()
diagnostics.Reset()
if code := run(t.Context(), []string{"validate", "--repo", repo, "--operation", "build", "--offline", "--json"}, &output, &diagnostics); code != 0 || !strings.Contains(output.String(), `"id":"main-package","operation":"build","status":"unchecked"`) {
t.Fatalf("readiness code=%d report=%s error=%s", code, &output, &diagnostics)
}
})
}
}

View File

@@ -0,0 +1,118 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestDeliveryCredentialSelection(t *testing.T) {
repository := t.TempDir()
path := filepath.Join(repository, "token")
if err := os.WriteFile(path, []byte(" file-secret \n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_TOKEN", " ambient-secret ")
credentials := &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_TOKEN"}}
for _, test := range []struct {
context cli.CredentialContext
want string
}{{cli.LocalCredentials, "file-secret"}, {cli.CICredentials, "ambient-secret"}} {
token, source, err := cli.ResolveDeliveryCredential(repository, credentials, test.context)
if err != nil || token != test.want || source.Context != test.context {
t.Fatalf("context=%s token matches=%t source=%+v error=%v", test.context, token == test.want, source, err)
}
}
credentials.Local.TokenFile = "missing"
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil || strings.Contains(err.Error(), "ambient-secret") {
t.Fatalf("missing local file error = %v", err)
}
if token, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err != nil || token != "ambient-secret" {
t.Fatalf("CI credential with missing local file: token matches=%t error=%v", token == "ambient-secret", err)
}
credentials.Local.TokenFile = path
if err := os.WriteFile(path, []byte(" \t\n"), 0600); err != nil {
t.Fatal(err)
}
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil {
t.Fatal("accepted blank file")
}
t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "default-secret")
token, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{CI: &cli.CICredential{}}, cli.CICredentials)
if err != nil || token != "default-secret" {
t.Fatalf("default CI credential matches=%t error=%v", token == "default-secret", err)
}
if _, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{}, cli.CICredentials); err == nil {
t.Fatal("accepted missing CI declaration")
}
t.Setenv("RELEASEKIT_TEST_TOKEN", " ")
if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err == nil {
t.Fatal("accepted blank CI token")
}
}
func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) {
repository := newCLIRepository(t)
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Validation: &cli.ValidationSettings{ForbiddenFiles: []string{"token-file"}},
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "missing-token-file"}}},
})
writeRepositoryFile(t, repository, "token-file", "fixture-secret\n")
cliGitRun(t, repository, "add", "token-file")
cliGitRun(t, repository, "commit", "-m", "capture a selected token path")
var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"check", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 1 || !strings.Contains(stderr.String(), "forbidden-files") || !strings.Contains(stderr.String(), "token-file") {
t.Fatalf("check status=%d output=%s diagnostics=%s", status, &stdout, &stderr)
}
if strings.Contains(stdout.String()+stderr.String(), "fixture-secret") {
t.Fatal("check exposed the token")
}
}
func TestDeliverAndCIDeliverSelectContextCredentials(t *testing.T) {
for _, command := range []string{"deliver", "ci-deliver"} {
t.Run(command, func(t *testing.T) {
repository := newCLIRepository(t)
state := &deliveryServerState{}
server := newDeliveryServer(t, state)
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product",
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: ".releasekit/token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}},
})
writeRepositoryFile(t, repository, ".gitignore", ".releasekit/\n")
cliGitRun(t, repository, "add", ".gitignore")
cliGitRun(t, repository, "commit", "-m", "ignore local delivery credentials")
commit := pushTaggedCLIRepository(t, repository)
state.update(func(data *deliveryServerData) { data.commit = commit })
if command == "deliver" {
writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n")
} else if err := os.MkdirAll(filepath.Join(repository, ".releasekit"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
var stdout, stderr bytes.Buffer
args := []string{command, "--repo", filepath.Join(repository, ".releasekit")}
if command == "ci-deliver" {
args = append(args, "--commit", commit)
}
args = append(args, "v1.2.3")
if status := run(context.Background(), args, &stdout, &stderr); status != 0 {
t.Fatalf("delivery status=%d output=%s diagnostics=%s", status, &stdout, &stderr)
}
if state.snapshot().releaseCreates != 1 {
t.Fatal("token-file delivery did not create the release page")
}
if strings.Contains(stdout.String()+stderr.String(), "fixture-token") {
t.Fatal("delivery exposed the token")
}
})
}
}

View File

@@ -15,7 +15,7 @@ import (
"sync/atomic" "sync/atomic"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestWoodpeckerTagDeliveryTemplate(t *testing.T) { func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
@@ -39,13 +39,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = commit }) state.update(func(state *deliveryServerData) { state.commit = commit })
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")) moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
output := runWoodpeckerBlock(t, command, repository, env) output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "state complete") { if !strings.Contains(output, "state complete") {
@@ -70,13 +71,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
BinaryName: "helper", BinaryName: "helper",
Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)}, Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)},
}, },
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
}) })
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
state.update(func(state *deliveryServerData) { state.commit = commit }) state.update(func(state *deliveryServerData) { state.commit = commit })
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")) moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum")) sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
for attempt := 0; attempt < 2; attempt++ { for attempt := 0; attempt < 2; attempt++ {
@@ -108,6 +110,7 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
unrelated := cliGitOutput(t, repository, "rev-parse", "HEAD") unrelated := cliGitOutput(t, repository, "rev-parse", "HEAD")
goDir, goLog := installControlledGoBootstrapShim(t) goDir, goLog := installControlledGoBootstrapShim(t)
env := templateEnvironment(repository, unrelated, goDir, goLog) env := templateEnvironment(repository, unrelated, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil { if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
t.Fatalf("wrong tag succeeded: %s", output) t.Fatalf("wrong tag succeeded: %s", output)
} else if !strings.Contains(output, commit) || !strings.Contains(output, unrelated) { } else if !strings.Contains(output, commit) || !strings.Contains(output, unrelated) {
@@ -123,6 +126,7 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
writeRepositoryFile(t, repository, "go.mod", "module example.com/different-tool-selection\n\ngo 1.25.0\n") writeRepositoryFile(t, repository, "go.mod", "module example.com/different-tool-selection\n\ngo 1.25.0\n")
goDir, goLog := installControlledGoBootstrapShim(t) goDir, goLog := installControlledGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil { if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
t.Fatalf("dirty module succeeded: %s", output) t.Fatalf("dirty module succeeded: %s", output)
} }
@@ -153,6 +157,7 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
goDir, goLog := installControlledGoBootstrapShim(t) goDir, goLog := installControlledGoBootstrapShim(t)
toolArgs := filepath.Join(t.TempDir(), "tool-arguments") toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
env := templateEnvironment(repository, strings.ToUpper(eventID), goDir, goLog) env := templateEnvironment(repository, strings.ToUpper(eventID), goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
env["CI_COMMIT_TAG"] = event.tag env["CI_COMMIT_TAG"] = event.tag
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
env["RELEASEKIT_TOOL_EXIT"] = "37" env["RELEASEKIT_TOOL_EXIT"] = "37"
@@ -176,6 +181,31 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
}) })
} }
func TestSingleProductWorkflowClassifiesCompleteDiagnosticTags(t *testing.T) {
for _, file := range []string{"examples/woodpecker/tag-delivery.yml", "examples/woodpecker/releasekit-source-delivery.yml", "examples/source-only/.woodpecker/delivery.yml"} {
t.Run(file, func(t *testing.T) {
body := readWorkflowFile(t, cliRepositoryRoot(t), file)
block, err := extractWoodpeckerCommand(body, "deliver")
if err != nil {
t.Fatal(err)
}
guard, _, ok := strings.Cut(block, "git check-ref-format")
if !ok {
t.Fatal("workflow has no tag preparation boundary")
}
guard = strings.ReplaceAll(guard, "$${", "${")
for _, tag := range []string{"releasekit-test/product/v1.2.3", "releasekit-test/product/2026-12-01", "releasekit-test/root/" + strings.Repeat("a", 32)} {
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": tag, "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err != nil {
t.Fatalf("valid tag=%s output=%s error=%v", tag, output, err)
}
}
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": "releasekit-test/foreign/" + strings.Repeat("a", 32), "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err == nil {
t.Fatalf("foreign selector accepted: %s", output)
}
})
}
}
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) { func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
// Synthetic downloads must leave the caller's module cache untouched. // Synthetic downloads must leave the caller's module cache untouched.
callerCache := t.TempDir() callerCache := t.TempDir()
@@ -205,7 +235,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
t.Run("older tag retry uses its committed module selection", func(t *testing.T) { t.Run("older tag retry uses its committed module selection", func(t *testing.T) {
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
repository := newCLIRepository(t) repository := newCLIRepository(t)
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n") writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n")
cliGitRun(t, repository, "add", "go.mod") cliGitRun(t, repository, "add", "go.mod")
cliGitRun(t, repository, "commit", "-m", "select the earlier ReleaseKit version") cliGitRun(t, repository, "commit", "-m", "select the earlier ReleaseKit version")
@@ -225,6 +255,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")) moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
commit := oldCommit commit := oldCommit
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy)) useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
sumLog := filepath.Join(t.TempDir(), "tool-only-sums") sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
env["RELEASEKIT_SUM_LOG"] = sumLog env["RELEASEKIT_SUM_LOG"] = sumLog
@@ -236,10 +267,31 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
assertToolOnlyChecksums(t, sumLog) assertToolOnlyChecksums(t, sumLog)
}) })
t.Run("vendored tool dependency", func(t *testing.T) {
goDir, goLog := installGoBootstrapShim(t)
repository := newCLIRepository(t)
const module = "go.maximumdirect.net/releasekit"
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n\ntool "+module+"/cmd/releasekit\n")
env := templateEnvironment(repository, "", goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
runWoodpeckerBlock(t, "go mod tidy\ngo mod vendor", repository, env)
cliGitRun(t, repository, "add", "go.mod", "go.sum", "vendor")
cliGitRun(t, repository, "commit", "-m", "vendor the selected release tool")
env["CI_COMMIT_SHA"] = pushTaggedCLIRepository(t, repository)
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "tool-version=v0.2.197 helper=tool-only dependency") {
t.Fatalf("vendored tool was not selected: %q", output)
}
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
})
t.Run("versioned replacement selects its declared source", func(t *testing.T) { t.Run("versioned replacement selects its declared source", func(t *testing.T) {
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
repository := newCLIRepository(t) repository := newCLIRepository(t)
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
goMod := "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire " + module + " v0.2.197\n\nreplace " + module + " v0.2.197 => " + module + " v0.2.198\n" goMod := "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire " + module + " v0.2.197\n\nreplace " + module + " v0.2.197 => " + module + " v0.2.198\n"
writeRepositoryFile(t, repository, "go.mod", goMod) writeRepositoryFile(t, repository, "go.mod", goMod)
cliGitRun(t, repository, "add", "go.mod") cliGitRun(t, repository, "add", "go.mod")
@@ -247,6 +299,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")) moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy)) useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
sumLog := filepath.Join(t.TempDir(), "tool-only-sums") sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
env["RELEASEKIT_SUM_LOG"] = sumLog env["RELEASEKIT_SUM_LOG"] = sumLog
@@ -293,6 +346,7 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
goDir, goLog := installGoBootstrapShim(t) goDir, goLog := installGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog) env := templateEnvironment(repository, commit, goDir, goLog)
env["GOOS"], env["GOARCH"] = foreignTarget()
useSyntheticModuleProxy(t, env, proxy.URL) useSyntheticModuleProxy(t, env, proxy.URL)
proxyRequests.Store(0) proxyRequests.Store(0)
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit)) env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
@@ -315,6 +369,9 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
t.Fatalf("self-bootstrapped command arguments = %q", output) t.Fatalf("self-bootstrapped command arguments = %q", output)
} }
log := readWoodpeckerFixtureFile(t, goLog) log := readWoodpeckerFixtureFile(t, goLog)
if !strings.Contains(log, "build-target="+runtime.GOOS+"/"+runtime.GOARCH) {
t.Fatalf("source build did not use host target: %s", log)
}
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, "build -mod=readonly -o ") || !strings.Contains(log, "./cmd/releasekit") { if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, "build -mod=readonly -o ") || !strings.Contains(log, "./cmd/releasekit") {
t.Fatalf("self-bootstrap Go command = %q", log) t.Fatalf("self-bootstrap Go command = %q", log)
} }
@@ -398,9 +455,11 @@ func installGoBootstrapShim(t *testing.T) (string, string) {
goLog := filepath.Join(shimDir, "go-commands") goLog := filepath.Join(shimDir, "go-commands")
shim := `#!/bin/sh shim := `#!/bin/sh
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG" printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG" ;; esac
if [ "$1" = build ]; then printf 'build-target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG"; fi
"$RELEASEKIT_REAL_GO" "$@" "$RELEASEKIT_REAL_GO" "$@"
status=$? status=$?
if [ "$status" -eq 0 ] && [ "$1" = "build" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then if [ "$status" -eq 0 ] && [ "$1" = "tool" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then
modfile= modfile=
for argument in "$@"; do for argument in "$@"; do
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
@@ -422,6 +481,8 @@ func installControlledGoBootstrapShim(t *testing.T) (string, string) {
shim := `#!/bin/sh shim := `#!/bin/sh
set -eu set -eu
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG" printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
if [ "$1" = env ]; then exec "$RELEASEKIT_REAL_GO" "$@"; fi
case " $* " in *" -deps "*) printf 'target=%s/%s\n' "$GOOS" "$GOARCH" >> "$RELEASEKIT_GO_LOG" ;; esac
modfile= modfile=
for argument in "$@"; do for argument in "$@"; do
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
@@ -433,20 +494,12 @@ case "$1" in
list) list)
printf '%s v0.2.0\n' "$RELEASEKIT_MODULE" printf '%s v0.2.0\n' "$RELEASEKIT_MODULE"
;; ;;
build) mod)
output= ;;
previous= tool)
for argument in "$@"; do shift 3
if [ "$previous" = "-o" ]; then output=$argument; break; fi printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
previous=$argument exit "${RELEASEKIT_TOOL_EXIT:-0}"
done
[ -n "$output" ] || { echo 'go build omitted output path' >&2; exit 90; }
cat > "$output" <<'TOOL'
#!/bin/sh
printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
exit "${RELEASEKIT_TOOL_EXIT:-0}"
TOOL
chmod +x "$output"
;; ;;
*) *)
echo "unexpected Go command: $1" >&2 echo "unexpected Go command: $1" >&2
@@ -480,7 +533,7 @@ func templateEnvironment(repository, commit, shimDir, goLog string) map[string]s
"CI_COMMIT_SHA": commit, "CI_COMMIT_SHA": commit,
"CI_COMMIT_TAG": "v1.2.3", "CI_COMMIT_TAG": "v1.2.3",
"RELEASEKIT_GITEA_TOKEN": "fixture-token", "RELEASEKIT_GITEA_TOKEN": "fixture-token",
"RELEASEKIT_MODULE": "gitea.maximumdirect.net/eric/ReleaseKit", "RELEASEKIT_MODULE": "go.maximumdirect.net/releasekit",
"RELEASEKIT_REAL_GO": realGo, "RELEASEKIT_REAL_GO": realGo,
"RELEASEKIT_GO_LOG": goLog, "RELEASEKIT_GO_LOG": goLog,
"GOTOOLCHAIN": "local", "GOTOOLCHAIN": "local",
@@ -513,8 +566,8 @@ func executeWoodpeckerBlock(block, repository string, environment map[string]str
func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) { func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) {
t.Helper() t.Helper()
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.26.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource)) goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.27.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
writeRepositoryFile(t, repository, "go.mod", goMod) writeRepositoryFile(t, repository, "go.mod", goMod)
cliGitRun(t, repository, "add", "go.mod") cliGitRun(t, repository, "add", "go.mod")
if includeSum { if includeSum {
@@ -526,13 +579,13 @@ func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, i
func writeReleaseKitModuleProxy(t *testing.T) string { func writeReleaseKitModuleProxy(t *testing.T) string {
t.Helper() t.Helper()
const module = "gitea.maximumdirect.net/eric/ReleaseKit" const module = "go.maximumdirect.net/releasekit"
const toolDependency = "example.com/releasekit-helper" const toolDependency = "example.com/releasekit-helper"
proxyDir := t.TempDir() proxyDir := t.TempDir()
toolModule := "module " + module + "\n\ngo 1.25.0\n\nrequire " + toolDependency + " v1.0.0\n" toolModule := "module " + module + "\n\ngo 1.25.0\n\nrequire " + toolDependency + " v1.0.0\n"
for _, version := range []string{"v0.2.197", "v0.2.198"} { for _, version := range []string{"v0.2.197", "v0.2.198"} {
files := map[string]string{ files := map[string]string{
"cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n", "cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; \"strconv\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n\tstatus, _ := strconv.Atoi(os.Getenv(\"RELEASEKIT_TOOL_EXIT\"))\n\tos.Exit(status)\n}\n",
} }
writeModuleProxyVersion(t, proxyDir, module, version, toolModule, files) writeModuleProxyVersion(t, proxyDir, module, version, toolModule, files)
} }
@@ -632,17 +685,20 @@ func assertModuleBootstrap(t *testing.T, repository, goLog, moduleBefore string,
func assertGoSelection(t *testing.T, repository, goLog string) { func assertGoSelection(t *testing.T, repository, goLog string) {
t.Helper() t.Helper()
log := readWoodpeckerFixtureFile(t, goLog) log := readWoodpeckerFixtureFile(t, goLog)
if !strings.Contains(log, "target="+runtime.GOOS+"/"+runtime.GOARCH) {
t.Fatalf("dependency inspection did not use host target: %s", log)
}
list := "list -mod=mod -modfile=" list := "list -mod=mod -modfile="
build := "build -mod=mod -modfile=" tool := "tool -modfile="
module := "gitea.maximumdirect.net/eric/ReleaseKit" module := "go.maximumdirect.net/releasekit"
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, list) || !strings.Contains(log, "-m "+module) { if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, list) || !strings.Contains(log, "-m "+module) {
t.Fatalf("Go module selection command is missing required settings: %q", log) t.Fatalf("Go module selection command is missing required settings: %q", log)
} }
if !strings.Contains(log, build) || !strings.Contains(log, module+"/cmd/releasekit") || strings.Contains(log, "@v0.2.0") { if !strings.Contains(log, tool) || !strings.Contains(log, " "+module+"/cmd/releasekit ci-deliver ") || strings.Contains(log, "@v0.2.0") {
t.Fatalf("Go build did not use the selected module without a version suffix: %q", log) t.Fatalf("Go tool did not run the module-selected ReleaseKit: %q", log)
} }
if strings.Index(log, list) > strings.Index(log, build) { if strings.Index(log, list) > strings.Index(log, tool) {
t.Fatalf("Go build ran before module selection: %q", log) t.Fatalf("Go tool ran before module selection: %q", log)
} }
var modfile string var modfile string
for _, field := range strings.Fields(log) { for _, field := range strings.Fields(log) {

View File

@@ -2,11 +2,15 @@ package releasekit
import ( import (
"context" "context"
"errors"
"fmt"
"io" "io"
"strings"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" internalbuild "go.maximumdirect.net/releasekit/internal/build"
internaldelivery "gitea.maximumdirect.net/eric/ReleaseKit/internal/delivery" internaldelivery "go.maximumdirect.net/releasekit/internal/delivery"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea" "go.maximumdirect.net/releasekit/internal/forge"
"go.maximumdirect.net/releasekit/internal/gitea"
) )
// DeliveryState describes the result of one delivery invocation. // DeliveryState describes the result of one delivery invocation.
@@ -25,36 +29,87 @@ const (
DeliveryUnknown DeliveryState = "unknown" DeliveryUnknown DeliveryState = "unknown"
) )
// GiteaDestination supplies the hosted repository and explicit access token. // Forge selects the hosted delivery backend. A delivery request must select a
type GiteaDestination struct { // supported value explicitly; the destination URL does not select a backend.
type Forge string
const (
// ForgeGitea selects Gitea for hosted delivery.
ForgeGitea Forge = "gitea"
)
// DeliveryDestination supplies an explicitly selected hosted destination.
type DeliveryDestination struct {
// Forge selects the adapter that interprets the destination fields.
Forge Forge
BaseURL string BaseURL string
Owner string Owner string
Repository string Repository string
Token string Token string
} }
// DeliveryPreflightFailureKind classifies a failure while checking destination
// settings, credentials, and repository access.
type DeliveryPreflightFailureKind string
const (
// DeliveryPreflightInvalidDestination means the destination settings fail local validation.
DeliveryPreflightInvalidDestination DeliveryPreflightFailureKind = "invalid_destination"
// DeliveryPreflightMissingCredential means no nonblank credential was supplied.
DeliveryPreflightMissingCredential DeliveryPreflightFailureKind = "missing_credential"
// DeliveryPreflightInvalidCredential means the selected service rejected the credential.
DeliveryPreflightInvalidCredential DeliveryPreflightFailureKind = "invalid_credential"
// DeliveryPreflightInsufficientPermissions means a required delivery permission is known to be absent.
DeliveryPreflightInsufficientPermissions DeliveryPreflightFailureKind = "insufficient_permissions"
// DeliveryPreflightInaccessibleDestination means the credential cannot access the selected repository.
DeliveryPreflightInaccessibleDestination DeliveryPreflightFailureKind = "inaccessible_destination"
// DeliveryPreflightUnavailable means the service response could not verify access.
DeliveryPreflightUnavailable DeliveryPreflightFailureKind = "unavailable"
)
// DeliveryPreflightError reports a classified failure to verify a destination.
type DeliveryPreflightError struct {
Kind DeliveryPreflightFailureKind
Err error
}
func (err *DeliveryPreflightError) Error() string {
if err.Err == nil {
return fmt.Sprintf("delivery preflight %s", err.Kind)
}
return fmt.Sprintf("delivery preflight %s: %v", err.Kind, err.Err)
}
func (err *DeliveryPreflightError) Unwrap() error { return err.Err }
// DeliveryAsset identifies a hosted asset by filename and SHA-256 digest. // DeliveryAsset identifies a hosted asset by filename and SHA-256 digest.
type DeliveryAsset struct { type DeliveryAsset struct {
Filename string Filename string
SHA256 string SHA256 string
} }
// DeliveryRequest identifies a local tagged checkout and its explicit Gitea // DeliveryRequest identifies a local tagged checkout and its explicit
// destination. Build selects a managed build; Prebuilt supplies caller-owned // destination. Build selects a managed build; Prebuilt supplies caller-owned
// build output instead. They cannot both be set. Either may be nil for // build output instead. They cannot both be set. The ordinary page-only request
// page-only delivery when both are nil. Build with no targets, or an empty // leaves both nil. A Build with no targets or a matching Prebuilt result with
// Prebuilt result, also performs page-only delivery. // no targets or artifacts also performs page-only delivery. Any supplied
// Prebuilt must match the repository, module directory and path, tag, commit,
// and version; a zero BuildResult does not supply that identity. Source and
// artifact requirements for binaries apply when binary work is selected.
type DeliveryRequest struct { type DeliveryRequest struct {
RepositoryDir string // directory within the tagged source Git checkout. RepositoryDir string // directory within the tagged source Git checkout.
// ModuleDir selects a repository-relative module directory; empty selects // ModuleDir selects a repository-relative module directory; empty selects
// the repository root. // the repository root.
ModuleDir string ModuleDir string
Product string // Source selects explicit source and publication capabilities. Nil retains
Version string // the ModuleDir Go-module shorthand.
Source *SourceSpec
Product string
Version string
// ExpectedTag optionally requires the full CI event tag to match the // ExpectedTag optionally requires the full CI event tag to match the
// selected module's derived tag before building or making hosted requests. // selected module's derived tag before building or making hosted requests.
ExpectedTag string ExpectedTag string
Destination GiteaDestination Destination DeliveryDestination
// Build selects binaries to build in temporary storage outside the checkout. // Build selects binaries to build in temporary storage outside the checkout.
Build *BuildSpec Build *BuildSpec
// Prebuilt supplies an existing build whose files remain caller-owned. // Prebuilt supplies an existing build whose files remain caller-owned.
@@ -64,15 +119,22 @@ type DeliveryRequest struct {
} }
// DeliveryResult reports hosted content and the state reached by this // DeliveryResult reports hosted content and the state reached by this
// invocation. A partial result may accompany an error. The asset slices are // invocation. A result may accompany an error, including Complete when hosted
// delivery succeeded but local managed-build cleanup failed. The asset slices are
// current observations: an asset appears in at most one slice, and early // current observations: an asset appears in at most one slice, and early
// failures may leave some declared assets unreported. // failures may leave some declared assets unreported.
type DeliveryResult struct { type DeliveryResult struct {
RepositoryDir string RepositoryDir string
SourceDir string
SourceSubdir string
GoEnabled bool
Publication PublicationMode
VersionFormat VersionFormat
VersionPrefix string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
Tag string // complete derived Git tag. Tag string // complete derived Git tag.
Version string // selected stable semantic version. Version string // selected production or diagnostic identifier.
CandidateCommit string CandidateCommit string
ReleaseURL string ReleaseURL string
State DeliveryState State DeliveryState
@@ -88,19 +150,22 @@ type DeliveryResult struct {
Uncertain []DeliveryAsset Uncertain []DeliveryAsset
} }
// Deliver verifies the selected local tag and hosted source, then creates or // Deliver requires an explicit supported destination forge. It checks the local
// finds its release page and adds any missing declared build assets. Build // request and source, then performs read-only credential preflight before a
// requests are compiled into temporary storage that Deliver removes on return. // managed build or full artifact verification. It verifies the selected local
// Prebuilt artifacts remain caller-owned and are not removed. Both paths // tag and hosted source, then creates or finds its release page and adds any
// validate source identity and artifact contents before hosted writes. // missing declared build assets. Prebuilt artifacts remain caller-owned. Local
// artifact contents are verified after preflight and before hosted writes.
// Module selection and declaration links resolve from the captured commit. // Module selection and declaration links resolve from the captured commit.
// Page-only delivery can use a sparse checkout with available committed objects; // Page-only delivery can use a sparse checkout with available committed objects;
// managed builds require their selected source files in the working tree. // managed builds require their selected source files in the working tree.
// Preflight failures return a [DeliveryPreflightError] and leave State at
// [DeliveryNotAttempted].
func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, error) { func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, error) {
result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted} result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted}
destination := gitea.Destination{ backend, err := deliveryBackend(request.Destination)
BaseURL: request.Destination.BaseURL, Owner: request.Destination.Owner, if err != nil {
Repository: request.Destination.Repository, Token: request.Destination.Token, return result, err
} }
var prebuilt *internalbuild.Result var prebuilt *internalbuild.Result
if request.Prebuilt != nil { if request.Prebuilt != nil {
@@ -109,15 +174,27 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{ internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
RepositoryDir: request.RepositoryDir, RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir, ModuleDir: request.ModuleDir,
Source: internalSourceSpec(request.Source),
Product: request.Product, Product: request.Product,
Version: request.Version, Version: request.Version,
ExpectedTag: request.ExpectedTag, ExpectedTag: request.ExpectedTag,
Destination: destination, Backend: backend,
Build: internalBuildSpec(request.Build), Build: internalBuildSpec(request.Build),
Prebuilt: prebuilt, Prebuilt: prebuilt,
Output: request.Output, Output: request.Output,
}) })
return publicDeliveryResult(internalResult, request.Version), publicPreflightError(err)
}
func publicDeliveryResult(internalResult internaldelivery.Result, version string) DeliveryResult {
result := DeliveryResult{Version: version}
result.RepositoryDir = internalResult.RepositoryDir result.RepositoryDir = internalResult.RepositoryDir
result.SourceDir = internalResult.Identity.SourceDir
result.SourceSubdir = internalResult.Identity.SourceSubdir
result.GoEnabled = internalResult.Identity.GoEnabled
result.Publication = PublicationMode(internalResult.Identity.Publication)
result.VersionFormat = VersionFormat(internalResult.Identity.VersionFormat)
result.VersionPrefix = internalResult.Identity.VersionPrefix
result.ModuleDir = internalResult.ModuleDir result.ModuleDir = internalResult.ModuleDir
result.ModulePath = internalResult.ModulePath result.ModulePath = internalResult.ModulePath
result.Tag = internalResult.Tag result.Tag = internalResult.Tag
@@ -129,10 +206,65 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
result.Pending = deliveryAssets(internalResult.Pending) result.Pending = deliveryAssets(internalResult.Pending)
result.Conflicting = deliveryAssets(internalResult.Conflicting) result.Conflicting = deliveryAssets(internalResult.Conflicting)
result.Uncertain = deliveryAssets(internalResult.Uncertain) result.Uncertain = deliveryAssets(internalResult.Uncertain)
return result, err return result
} }
func deliveryAssets(assets []gitea.AssetIdentity) []DeliveryAsset { // PreflightDelivery checks destination credentials and repository access using
// read-only backend operations. It does not require a checkout or published tag.
// The result verifies only the access and permission evidence exposed by the
// selected backend; it does not guarantee that a later write will succeed.
// Failures are returned as [DeliveryPreflightError] values when classified by
// the backend, and retain their underlying cause for errors.Is and errors.As.
func PreflightDelivery(ctx context.Context, destination DeliveryDestination) error {
backend, err := deliveryBackend(destination)
if err != nil {
return err
}
return publicPreflightError(backend.Preflight(ctx))
}
func deliveryBackend(destination DeliveryDestination) (forge.Backend, error) {
selection := Forge(strings.TrimSpace(string(destination.Forge)))
switch selection {
case ForgeGitea:
return gitea.NewBackend(gitea.Destination{
BaseURL: destination.BaseURL, Owner: destination.Owner,
Repository: destination.Repository, Token: destination.Token,
}, nil), nil
case "":
return nil, errors.New("delivery forge must be selected explicitly")
default:
return nil, fmt.Errorf("unsupported delivery forge %q", destination.Forge)
}
}
func publicPreflightError(err error) error {
if err == nil {
return nil
}
var failure *forge.PreflightFailure
if !errors.As(err, &failure) {
return err
}
kind := DeliveryPreflightUnavailable
switch failure.Kind {
case forge.PreflightInvalidDestination:
kind = DeliveryPreflightInvalidDestination
case forge.PreflightMissingCredential:
kind = DeliveryPreflightMissingCredential
case forge.PreflightInvalidCredential:
kind = DeliveryPreflightInvalidCredential
case forge.PreflightInsufficientPermissions:
kind = DeliveryPreflightInsufficientPermissions
case forge.PreflightInaccessibleDestination:
kind = DeliveryPreflightInaccessibleDestination
case forge.PreflightUnavailable:
kind = DeliveryPreflightUnavailable
}
return &DeliveryPreflightError{Kind: kind, Err: failure.Err}
}
func deliveryAssets(assets []internaldelivery.AssetIdentity) []DeliveryAsset {
result := make([]DeliveryAsset, 0, len(assets)) result := make([]DeliveryAsset, 0, len(assets))
for _, asset := range assets { for _, asset := range assets {
result = append(result, DeliveryAsset{Filename: asset.Filename, SHA256: asset.SHA256}) result = append(result, DeliveryAsset{Filename: asset.Filename, SHA256: asset.SHA256})

63
delivery_causes_test.go Normal file
View File

@@ -0,0 +1,63 @@
package releasekit_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"runtime"
"strings"
"testing"
releasekit "go.maximumdirect.net/releasekit"
)
func TestDeliveryPreservesAssetInspectionCauses(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
})
if err != nil {
t.Fatal(err)
}
filename := prebuilt.Artifacts[0].Filename
for _, cause := range []error{context.Canceled, io.ErrUnexpectedEOF} {
t.Run(cause.Error(), func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
state := &facadeDeliveryServer{data: facadeDeliveryData{
t: t, commit: prebuilt.CandidateCommit, tag: prebuilt.Tag, version: prebuilt.Version,
noteBody: "# Fixture v1.2.3\n\nDelivery fixture.\n",
pages: map[string]bool{prebuilt.Tag: true}, assets: map[string][]byte{filename: []byte("data")},
}}
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/files/") {
if cause == context.Canceled {
cancel()
<-r.Context().Done()
return
}
w.Header().Set("Content-Length", "100")
_, _ = w.Write([]byte("truncated"))
return
}
state.serveHTTP(w, r)
}))
state.data.url = "http://" + server.Listener.Addr().String()
server.Start()
defer server.Close()
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &prebuilt,
})
if !errors.Is(err, cause) || !strings.Contains(err.Error(), filename) {
t.Fatalf("Deliver() error = %v, want cause %v and asset context", err, cause)
}
if result.State != releasekit.DeliveryNotAttempted || len(result.Uncertain) != 1 || result.Uncertain[0].Filename != filename || state.snapshot().writes != 0 {
t.Fatalf("result = %#v, want read-only uncertain asset without write", result)
}
})
}
}

View File

@@ -0,0 +1,53 @@
package releasekit_test
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
releasekit "go.maximumdirect.net/releasekit"
)
func TestInvalidDestinationFailsStandaloneAndAutomaticPreflight(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("invalid destination made a hosted request: %s", r.URL.Path)
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
for _, test := range []struct {
name, setting string
change func(*releasekit.DeliveryDestination)
}{
{"URL", "base URL", func(d *releasekit.DeliveryDestination) { d.BaseURL = "ssh://forge.example" }},
{"owner", "owner", func(d *releasekit.DeliveryDestination) { d.Owner = "owner/child" }},
{"repository", "repository", func(d *releasekit.DeliveryDestination) { d.Repository = "repo/child" }},
} {
t.Run(test.name, func(t *testing.T) {
destination := facadeDeliveryDestination(server.URL)
test.change(&destination)
assertFailure := func(err error) {
t.Helper()
var preflight *releasekit.DeliveryPreflightError
if !errors.As(err, &preflight) || preflight.Kind != releasekit.DeliveryPreflightInvalidDestination || preflight.Err == nil {
t.Fatalf("error = %#v, want invalid destination with cause", err)
}
if !strings.Contains(err.Error(), test.setting) {
t.Fatalf("error = %v, want invalid setting %q", err, test.setting)
}
}
assertFailure(releasekit.PreflightDelivery(context.Background(), destination))
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: destination,
Build: &releasekit.BuildSpec{MainPackage: "./missing", BinaryName: "fixture", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}}},
})
assertFailure(err)
if result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("delivery state = %s, want not attempted", result.State)
}
})
}
}

View File

@@ -1,67 +0,0 @@
package releasekit_test
import (
"encoding/binary"
"errors"
"net/http"
"net/http/httptest"
"syscall"
"testing"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
)
func TestDeliverReadsLocalBinaryOnceForVerificationAndOnceForUpload(t *testing.T) {
repository, build, expected := newDeliveryBenchmarkFixture(t)
watcher, err := syscall.InotifyInit1(syscall.IN_NONBLOCK | syscall.IN_CLOEXEC)
if err != nil {
t.Fatal(err)
}
defer syscall.Close(watcher)
// Close events separate successive opens so inotify cannot coalesce them.
if _, err := syscall.InotifyAddWatch(watcher, build.Artifacts[0].Path, syscall.IN_OPEN|syscall.IN_CLOSE_NOWRITE); err != nil {
t.Fatal(err)
}
state := &deliveryBenchmarkServer{commit: build.CandidateCommit, assets: expected}
state.reset(false)
server := httptest.NewUnstartedServer(http.HandlerFunc(state.serveHTTP))
state.baseURL = "http://" + server.Listener.Addr().String()
server.Start()
defer server.Close()
result, err := releasekit.Deliver(t.Context(), releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Sample App", Version: build.Version,
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &build,
})
if err != nil || result.State != releasekit.DeliveryComplete || len(result.Uploaded) != len(expected) {
t.Fatalf("delivery = %#v, error = %v", result, err)
}
state.verifyUploads(t)
opens := 0
var events [256]byte
for {
n, err := syscall.Read(watcher, events[:])
if errors.Is(err, syscall.EAGAIN) {
break
}
if errors.Is(err, syscall.EINTR) {
continue
}
if err != nil {
t.Fatal(err)
}
for offset := 0; offset < n; {
mask := binary.NativeEndian.Uint32(events[offset+4:])
if mask&syscall.IN_Q_OVERFLOW != 0 {
t.Fatal("artifact event queue overflowed")
}
if mask&syscall.IN_OPEN != 0 {
opens++
}
nameLength := binary.NativeEndian.Uint32(events[offset+12:])
offset += syscall.SizeofInotifyEvent + int(nameLength)
}
}
if opens != 2 {
t.Fatalf("local binary opened %d times; want one verification read and one upload read", opens)
}
}

View File

@@ -16,9 +16,178 @@ import (
"sync" "sync"
"testing" "testing"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit" releasekit "go.maximumdirect.net/releasekit"
) )
func TestDeliveryForgeSelectionIsExplicit(t *testing.T) {
var requests int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
for _, forge := range []releasekit.Forge{"", " \t", "unknown"} {
t.Run(string(forge), func(t *testing.T) {
destination := releasekit.DeliveryDestination{
Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example", Token: "fixture-token",
}
if err := releasekit.PreflightDelivery(context.Background(), destination); err == nil || !strings.Contains(err.Error(), "forge") {
t.Fatalf("PreflightDelivery() error = %v, want explicit forge selection error", err)
}
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
Version: "v1.2.3", Destination: destination,
})
if err == nil || !strings.Contains(err.Error(), "forge") || result.State != releasekit.DeliveryNotAttempted || result.Version != "v1.2.3" {
t.Fatalf("Deliver() = %#v, %v; want selection error before delivery", result, err)
}
})
}
if requests != 0 {
t.Fatalf("hosted requests = %d, want 0 for invalid forge selection", requests)
}
}
func TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout(t *testing.T) {
var requests, writes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writes++
t.Errorf("preflight method = %q, want GET", r.Method)
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
return
}
if got, want := r.Header.Get("Authorization"), "token fixture-token"; got != want {
t.Errorf("authorization = %q, want %q", got, want)
}
requests++
switch r.URL.Path {
case "/api/v1/repos/owner/example":
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
case "/api/v1/repositories/31":
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
default:
t.Errorf("preflight path = %q", r.URL.Path)
http.NotFound(w, r)
}
}))
defer server.Close()
if err := releasekit.PreflightDelivery(context.Background(), facadeDeliveryDestination(server.URL)); err != nil {
t.Fatalf("PreflightDelivery() error = %v", err)
}
if requests != 2 || writes != 0 {
t.Fatalf("preflight requests=%d writes=%d, want two reads and no writes", requests, writes)
}
}
func TestPreflightDeliveryPreservesPublicFailureKindsAndCauses(t *testing.T) {
cases := []struct {
name string
token string
status int
wantKind releasekit.DeliveryPreflightFailureKind
wantReads int
canceled bool
}{
{name: "missing credential", wantKind: releasekit.DeliveryPreflightMissingCredential},
{name: "invalid credential", token: "fixture-token", status: http.StatusUnauthorized, wantKind: releasekit.DeliveryPreflightInvalidCredential, wantReads: 1},
{name: "inaccessible destination", token: "fixture-token", status: http.StatusForbidden, wantKind: releasekit.DeliveryPreflightInaccessibleDestination, wantReads: 1},
{name: "unavailable service", token: "fixture-token", status: http.StatusServiceUnavailable, wantKind: releasekit.DeliveryPreflightUnavailable, wantReads: 1},
{name: "canceled request", token: "fixture-token", wantKind: releasekit.DeliveryPreflightUnavailable, canceled: true},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
reads := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reads++
if test.status != 0 {
http.Error(w, "controlled failure", test.status)
return
}
t.Errorf("unexpected request to %q", r.URL.Path)
http.Error(w, "unexpected request", http.StatusInternalServerError)
}))
defer server.Close()
destination := facadeDeliveryDestination(server.URL)
destination.Token = test.token
ctx := context.Background()
if test.canceled {
canceled, cancel := context.WithCancel(ctx)
cancel()
ctx = canceled
}
err := releasekit.PreflightDelivery(ctx, destination)
var preflight *releasekit.DeliveryPreflightError
if !errors.As(err, &preflight) || preflight.Kind != test.wantKind || preflight.Err == nil {
t.Fatalf("PreflightDelivery() error = %#v, want kind %q with cause", err, test.wantKind)
}
if test.canceled && !errors.Is(err, context.Canceled) {
t.Fatalf("PreflightDelivery() error = %v, want cancellation identity", err)
}
if reads != test.wantReads {
t.Fatalf("preflight reads = %d, want %d", reads, test.wantReads)
}
})
}
}
func TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
Version: "v1.2.3",
Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app",
BinaryName: "fixture",
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
},
OutputDir: t.TempDir(),
})
if err != nil {
t.Fatalf("Build() error = %v", err)
}
contents, err := os.ReadFile(prebuilt.Artifacts[0].Path)
if err != nil {
t.Fatal(err)
}
contents[0] ^= 0xff
if err := os.WriteFile(prebuilt.Artifacts[0].Path, contents, 0o600); err != nil {
t.Fatal(err)
}
var reads, writes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writes++
http.Error(w, "unexpected write", http.StatusMethodNotAllowed)
return
}
reads++
if r.URL.Path == "/api/v1/repos/owner/example" {
_ = json.NewEncoder(w).Encode(map[string]any{"id": 31, "name": "example", "full_name": "owner/example", "owner": map[string]string{"login": "owner"}})
return
}
http.Error(w, "verification unavailable", http.StatusServiceUnavailable)
}))
defer server.Close()
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository,
Product: "Fixture",
Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL),
Prebuilt: &prebuilt,
})
var preflight *releasekit.DeliveryPreflightError
if !errors.As(err, &preflight) || preflight.Kind != releasekit.DeliveryPreflightUnavailable || result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("Deliver() = %#v, %v; want unavailable preflight before tamper verification", result, err)
}
if reads != 2 || writes != 0 {
t.Fatalf("preflight reads=%d writes=%d, want two reads and no writes", reads, writes)
}
}
func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.T) { func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.T) {
repository := newTaggedDeliveryConsumer(t) repository := newTaggedDeliveryConsumer(t)
temporaryRoot := t.TempDir() temporaryRoot := t.TempDir()
@@ -138,6 +307,34 @@ func TestDeliverPrebuiltArtifactsRemainCallerOwned(t *testing.T) {
} }
} }
func TestDeliverRejectsOversizedExistingPrebuiltAsset(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
})
if err != nil {
t.Fatal(err)
}
content, err := os.ReadFile(prebuilt.Artifacts[0].Path)
if err != nil {
t.Fatal(err)
}
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
remote.update(func(data *facadeDeliveryData) {
data.pages["v1.2.3"] = true
data.assets[prebuilt.Artifacts[0].Filename] = append(content, 'x')
})
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &prebuilt,
})
if err == nil || result.State != releasekit.DeliveryConflict || len(result.Conflicting) != 1 || result.Conflicting[0].Filename != prebuilt.Artifacts[0].Filename || remote.snapshot().writes != 0 {
t.Fatalf("delivery = %#v, error = %v, writes = %d", result, err, remote.snapshot().writes)
}
}
func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T) { func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T) {
repository := newTaggedDeliveryConsumer(t) repository := newTaggedDeliveryConsumer(t)
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{ prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
@@ -177,8 +374,8 @@ func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T)
if err == nil || !strings.Contains(err.Error(), "verify build assets") || result.State != releasekit.DeliveryNotAttempted { if err == nil || !strings.Contains(err.Error(), "verify build assets") || result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("Deliver() = %#v, %v; want local asset verification failure", result, err) t.Fatalf("Deliver() = %#v, %v; want local asset verification failure", result, err)
} }
if remote.snapshot().requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none before local verification", remote.snapshot().requests) t.Fatalf("hosted writes = %d, want none before local verification", remote.snapshot().writes)
} }
} }
@@ -233,6 +430,29 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
} }
} }
func TestDeliverUsesOriginalNoteWithBlobReplacement(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
original := buildGit(t, repository, "rev-parse", "HEAD:docs/releases/v1.2.3.md")
replacementPath := filepath.Join(t.TempDir(), "note.md")
if err := os.WriteFile(replacementPath, []byte("# Fixture v1.2.3\n\nReplacement note.\n"), 0o600); err != nil {
t.Fatal(err)
}
replacement := buildGit(t, repository, "hash-object", "-w", replacementPath)
buildGit(t, repository, "replace", original, replacement)
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL),
})
if err != nil || result.State != releasekit.DeliveryComplete {
t.Fatalf("delivery = %#v, error = %v", result, err)
}
if got := remote.snapshot().createdBody; got != "# Fixture v1.2.3\n\nDelivery fixture.\n" {
t.Fatalf("delivered note = %q", got)
}
}
func TestDeliverUsesCommittedModuleIdentityForSeparatePages(t *testing.T) { func TestDeliverUsesCommittedModuleIdentityForSeparatePages(t *testing.T) {
repository := newTwoModuleDeliveryConsumer(t) repository := newTwoModuleDeliveryConsumer(t)
server, remote := newFacadeDeliveryServer(t, repository) server, remote := newFacadeDeliveryServer(t, repository)
@@ -323,7 +543,7 @@ func newTwoModuleDeliveryConsumer(t *testing.T) string {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } } func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
`) `)
@@ -463,8 +683,8 @@ func TestDeliverManagedBuildRejectsCheckoutMutationBeforeHostedWrites(t *testing
if err == nil || !strings.Contains(err.Error(), "build source") || result.State != releasekit.DeliveryNotAttempted { if err == nil || !strings.Contains(err.Error(), "build source") || result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("Deliver() = %#v, %v; want build-source eligibility failure", result, err) t.Fatalf("Deliver() = %#v, %v; want build-source eligibility failure", result, err)
} }
if remote.snapshot().requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests) t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
} }
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 { if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err) t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err)
@@ -492,8 +712,8 @@ func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *te
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit { if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
t.Fatalf("Deliver() = %#v, %v; want managed build failure before hosted writes", result, err) t.Fatalf("Deliver() = %#v, %v; want managed build failure before hosted writes", result, err)
} }
if remote.snapshot().requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests) t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
} }
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 { if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err) t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err)
@@ -525,8 +745,8 @@ func TestDeliverManagedBuildCancellationCleansTemporaryOutput(t *testing.T) {
if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted { if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err) t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err)
} }
if remote.snapshot().requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests) t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
} }
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 { if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err) t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err)
@@ -564,7 +784,7 @@ func newTaggedDeliveryConsumerWithNote(t *testing.T, note string) string {
import ( import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } } func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
`) `)
@@ -575,8 +795,8 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fix
return repository return repository
} }
func facadeDeliveryDestination(baseURL string) releasekit.GiteaDestination { func facadeDeliveryDestination(baseURL string) releasekit.DeliveryDestination {
return releasekit.GiteaDestination{BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"} return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
} }
type deliveryCancelWriter struct{ cancel context.CancelFunc } type deliveryCancelWriter struct{ cancel context.CancelFunc }
@@ -586,6 +806,33 @@ func (writer deliveryCancelWriter) Write(content []byte) (int, error) {
return len(content), nil return len(content), nil
} }
func TestDeliverExistingPageWithoutReleaseID(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, Version: "v1.2.3", OutputDir: t.TempDir(),
Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}},
})
if err != nil {
t.Fatal(err)
}
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
remote.update(func(data *facadeDeliveryData) { data.pages[data.tag] = true; data.omitReleaseID = true })
request := releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Destination: facadeDeliveryDestination(server.URL)}
page, err := releasekit.Deliver(context.Background(), request)
if err != nil || page.State != releasekit.DeliveryComplete {
t.Fatalf("page result = %#v, error = %v", page, err)
}
request.Prebuilt = &prebuilt
result, err := releasekit.Deliver(context.Background(), request)
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "release ID") {
t.Fatalf("asset result = %#v, error = %v", result, err)
}
if snapshot := remote.snapshot(); snapshot.writes != 0 {
t.Fatalf("unexpected hosted writes: %#v", snapshot)
}
}
type facadeDeliveryServer struct { type facadeDeliveryServer struct {
mu sync.Mutex mu sync.Mutex
data facadeDeliveryData data facadeDeliveryData
@@ -616,15 +863,18 @@ func (state *facadeDeliveryServer) snapshot() facadeDeliveryData {
} }
type facadeDeliveryData struct { type facadeDeliveryData struct {
t *testing.T t *testing.T
commit string commit string
tag string tag string
version string version string
noteBody string noteBody string
pages map[string]bool createdBody string
requests int pages map[string]bool
assets map[string][]byte requests int
url string writes int
omitReleaseID bool
assets map[string][]byte
url string
} }
func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) { func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) {
@@ -642,11 +892,19 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
data := &state.data data := &state.data
if strings.HasPrefix(r.URL.Path, "/api/") { if strings.HasPrefix(r.URL.Path, "/api/") {
data.requests++ data.requests++
if r.Method != http.MethodGet {
data.writes++
}
if r.Header.Get("Authorization") != "token fixture-token" { if r.Header.Get("Authorization") != "token fixture-token" {
data.t.Errorf("authorization = %q", r.Header.Get("Authorization")) data.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
} }
} }
switch r.URL.EscapedPath() { switch r.URL.EscapedPath() {
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
case "/api/v1/repos/owner/example/tags/" + url.PathEscape(data.tag): case "/api/v1/repos/owner/example/tags/" + url.PathEscape(data.tag):
_, _ = fmt.Fprintf(w, `{"name":%q,"commit":{"sha":%q}}`, data.tag, data.commit) _, _ = fmt.Fprintf(w, `{"name":%q,"commit":{"sha":%q}}`, data.tag, data.commit)
case "/api/v1/repos/owner/example/releases/tags/" + url.PathEscape(data.tag): case "/api/v1/repos/owner/example/releases/tags/" + url.PathEscape(data.tag):
@@ -670,6 +928,7 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
if payload.Tag != data.tag || payload.Target != data.commit || payload.Name != "Fixture "+data.version { if payload.Tag != data.tag || payload.Target != data.commit || payload.Name != "Fixture "+data.version {
data.t.Errorf("release payload = %#v", payload) data.t.Errorf("release payload = %#v", payload)
} }
data.createdBody = payload.Body
data.pages[data.tag] = true data.pages[data.tag] = true
state.writeRelease(w) state.writeRelease(w)
case "/api/v1/repos/owner/example/releases/10/assets": case "/api/v1/repos/owner/example/releases/10/assets":
@@ -716,11 +975,15 @@ func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
// The request handler holds state.mu. // The request handler holds state.mu.
data := &state.data data := &state.data
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{ release := map[string]any{
"id": 10, "html_url": data.url + "/releases/10", "tag_name": data.tag, "html_url": data.url + "/releases/10", "tag_name": data.tag,
"target_commitish": data.commit, "name": "Fixture " + data.version, "target_commitish": data.commit, "name": "Fixture " + data.version,
"body": data.noteBody, "draft": false, "prerelease": false, "body": data.noteBody, "draft": false, "prerelease": false,
}) }
if !data.omitReleaseID {
release["id"] = 10
}
_ = json.NewEncoder(w).Encode(release)
} }
func mapKeys(values map[string][]byte) []string { func mapKeys(values map[string][]byte) []string {

View File

@@ -2,7 +2,9 @@
## Status ## Status
Accepted. Accepted; partially superseded by [ADR 0007](0007-general-source-release-identity.md)
for releases that do not select Go module publication. Its module-scoped
validation and Go module publication conventions continue to apply.
## Date ## Date

View File

@@ -0,0 +1,92 @@
# ADR 0006: Separate delivery policy from forge protocols
## Status
Accepted.
## Date
2026-11-01
## Context
ReleaseKit's delivery workflow handles release-page matching and creation
recovery, remote asset comparison, upload ordering, retries, and partial or
uncertain outcomes. Those policies are useful independently of the Gitea HTTP
protocol, but the earlier client-owned flow coupled them to Gitea types and
operations.
Delivery also benefits from checking credentials and repository access before
managed builds, dependency preparation, or complete artifact hashing. Gitea
exposes authenticated repository reads, but its `permissions.push` metadata and
basic token evidence do not establish permission to write release pages or
assets. A read-only check must represent that evidence limit without claiming
that later writes are guaranteed.
The root `releasekit` facade owns public types, while implementation packages
remain internal. The CLI owns credential loading and process exit status.
Source publication has separate Git authentication and completion semantics.
## Decision
The root facade owns `Forge`, `DeliveryDestination`, explicit backend selection,
and public preflight errors. `internal/forge` defines the internal backend
contract and neutral release, asset, failure, and write-evidence values.
`internal/delivery` owns shared delivery coordination and policy.
`internal/gitea` owns Gitea destination rules, authenticated preflight requests,
protocol operations, codecs, handles, streaming, and conversion to neutral
failures. `internal/artifact` owns local asset declarations and verification.
Shared delivery, forge, and artifact packages have no production dependency
path to the Gitea adapter.
Delivery selection is explicit. The supported value is `gitea`; neither a URL
nor an omitted selection chooses a backend. There is no compatibility alias for
the removed public Gitea destination type.
The facade exposes `PreflightDelivery` and runs the same read-only backend
preflight automatically during `Deliver`. Gitea preflight authenticates through
repository-scoped reads and classifies missing or rejected credentials,
inaccessible destinations, and unavailable verification. It does not issue a
test release or upload, require extra user/admin token scopes, or treat
unexposed write permission evidence as a failure. Success confirms only the
authentication, repository access, and permission evidence available through
that check; ordinary writes remain authoritative. Preflight failures preserve
their causes and leave delivery `not_attempted`.
The CLI requires `delivery.forge` only for `deliver` and `ci-deliver`. Binary
CI delivery performs a standalone preflight after checkout/profile/token
preparation and before application dependency downloads, then `Deliver`
rechecks. Page-only CI relies on automatic delivery preflight. `check`,
`build`, and source `publish` do not require delivery configuration or hosted
credentials. Local artifact verification follows preflight but completes before
hosted writes.
## Alternatives considered
- Keep delivery policy in the Gitea client. This retains protocol coupling and
makes shared recovery behavior harder to exercise without the adapter.
- Select Gitea from the URL or preserve the old Gitea-specific facade type.
This hides backend selection and keeps the public contract tied to one
adapter.
- Probe permissions with a test release or asset, or require additional user
scopes. Those operations can create remote state or demand evidence unrelated
to release delivery; the repository read does not expose the required
release-write proof.
- Skip preflight and let the first write discover credential problems. That
delays a known failure until after costly local work and provides no
standalone check for callers preparing their own delivery.
## Consequences
- Shared policy can be tested with controlled backends, while local HTTP tests
focus on Gitea protocol behavior and assembled integration flows.
- Consumers must replace the removed Gitea-specific destination type, set
`ForgeGitea` in API calls, and add `"forge": "gitea"` to delivery profiles.
- Delivery may make additional authenticated read requests before local
artifact hashing. It still verifies full local content before any hosted
write.
- Credential, access, and availability failures have distinct public error
kinds and CLI classifications. Successful preflight does not certify future
release or asset writes.
- Source publication retains native Git authentication and is not gated by
hosted delivery preflight.

View File

@@ -0,0 +1,102 @@
# ADR 0007: Identify source releases independently of Go module publication
## Status
Accepted. Supersedes the requirement in
[ADR 0005](0005-module-release-scope.md) that every release selects a Go module.
Its module-scoped validation and Go module publication conventions continue
to apply to those uses.
## Date
2026-12-05
## Context
ReleaseKit manages releases from Git repositories. A Git commit identifies
the source revision; a release tag gives that revision a published name.
Release notes describe the release, and a hosting service can present those
notes with downloadable files. Continuous integration (CI) runs automated
build and delivery jobs for the selected source.
Repositories contain different kinds of products. A configuration repository
may contain only YAML or JSON. A Go application may be distributed as compiled
executables. A Go library publishes versions that other Go programs download
through Go's module system. These products share tagging, validation, hosted
pages, and recovery needs.
ReleaseKit's existing model requires a Go module, a unit of Go source declared
in a `go.mod` file. It also applies Go module version rules to application
releases. Those rules connect published major versions to module import paths.
An application's product version can evolve independently when users obtain
binaries or build a checked-out source revision.
[ADR 0002](0002-routine-releases.md) prioritizes shared release mechanics and
small consumer integrations. A common source-release model supports these
products while preserving Go's requirements where they apply.
## Decision
A release identifies a Git repository, exact committed revision, selected
source scope (the directory being released), version, complete tag, and
release note. ReleaseKit carries that identity consistently through validation,
publication, builds, hosted delivery, diagnostics, and recovery.
Configuration expresses three distinct choices: the source being released,
Go validation and build capabilities, and publication through Go's module
system. Go module publication adds its version and tag rules to the common
source-release model.
Go applications derive their source scope from the selected module, keeping
one directory setting for builds and validation. Source-only repositories
default to the repository root. File checks and release notes follow the
selected source scope. Common Git and publication checks apply to both.
General source releases support Semantic Versioning and the selected calendar
formats. Callers supply the version. General source tags use the selected
source directory as their default prefix, with a product-prefix override.
Go module publication uses Go's module tag conventions.
Module-path major-version compatibility applies when Go module publication
is selected. Go builds and tests use the selected module independently of
that choice. For example, an application can retain `example.com/myapp` as
its module path while distributing binaries under the product tag `v2.0.0`.
Publishing versions for import by Go programs or installation through
`go install …@VERSION` selects Go module publication and its compatibility
rules.
Source-only repositories receive tagging, publication, hosted pages,
readiness checks, recovery, and delivery rehearsals through the shared
workflow. Applicable file checks and configured product checks validate their
contents. Go modules retain their Go test suite.
Existing profiles retain documented module-publication defaults. New examples
state the publication choice explicitly. Module-backed consumers retain the
tool-version selection in [ADR 0004](0004-module-selected-tooling.md).
Source-only repositories record the ReleaseKit version in one committed file
read by both the maintained local launcher and CI tool setup.
## Alternatives considered
- Requiring a Go module for every release preserves one existing path but
gives configuration repositories an unrelated dependency declaration.
- Applying Go publication rules to every Go application couples product
versions to import paths even for binary distribution.
- Separate release engines for each product type duplicate tagging,
validation, hosted delivery, and recovery mechanics.
## Consequences
Configuration repositories and Go applications can share ReleaseKit's release
workflow while selecting capabilities appropriate to their distribution.
Consumers maintain product facts and one tool-version declaration for local
and CI use.
The API, configuration, validation, and saved release evidence must distinguish
source scope, Go capabilities, and module publication. Existing Go consumers
retain their established module conventions, and general source releases gain
independent product versioning.
Exact fields, version grammars, and stored formats belong in the public
contracts as implementation lands. ReleaseKit's own releases continue to
follow its adopted Semantic Versioning policy.

View File

@@ -0,0 +1,114 @@
# ADR 0008: Rehearse Woodpecker delivery with recorded temporary resources
## Status
Accepted. The implementation plan adopts this lifecycle for explicitly
temporary diagnostic resources; production release immutability is unchanged.
## Date
2026-12-05
## Context
A successful Git tag push can be followed by failed delivery. Missing
credentials, build failures, or upload errors can leave a release without its
hosted page or expected downloads. Woodpecker is the continuous integration
(CI) service that runs the delivery workflow after receiving the tag event.
A ReleaseKit profile records the product, selected source, build targets,
and delivery destination.
Read-only readiness checks establish available configuration and access
evidence. Developers also need to exercise the actual workflow, including
building executables and uploading their contents, before publishing a
production version.
A rehearsal creates real remote resources. A workstation can disconnect while
Woodpecker continues running, and a failed request can leave the outcome of a
remote write uncertain. ReleaseKit needs an explicit lifecycle for observing
the attempt, verifying its result, and removing its temporary resources.
## Decision
ReleaseKit provides an optional end-to-end delivery rehearsal. One local
invocation records an attempt, pushes a uniquely named diagnostic tag, observes
the actual Woodpecker delivery workflow, and coordinates verification and
cleanup. Production releases retain their immutable tags and contents.
The attempt records its exact commit, selected source and profile, diagnostic
tag, and diagnostic version used by builds. ReleaseKit supplies this identity
and a temporary release note through its maintained workflow. The identity
connects the tag event, CI execution, verification result, and recovery record.
Woodpecker runs the same configured tool setup, builds, credential mapping,
and shared delivery mechanics used for production. The job creates a clearly
marked temporary hosted page in the configured repository and uploads the
declared artifacts, such as executables and their checksums. Source-only
profiles exercise page-only delivery.
Content verification runs inside the delivery job, where the generated files
are available for comparison with uploaded contents. The job emits a structured
result associated with the recorded rehearsal. The ReleaseKit process on the
workstation coordinates the attempt. It confirms both successful execution of the expected workflow and its matching result.
Page-only results verify the hosted page and identify that scope.
Local Git operations use native Git authentication. Operations against the
repository hosting service (the forge) and Woodpecker read their respective
local credential files directly. Woodpecker supplies
the delivery credential from its stored secret to the job. This exercises the
job's actual credential configuration while keeping workstation setup persistent.
Cleanup follows successful and failed attempts. It targets the recorded
diagnostic tag, hosted page, and uploaded assets by their exact identities.
ReleaseKit establishes completion of the relevant CI job before deleting
resources, so an active job cannot recreate them after cleanup is reported
complete. Uncertain CI or remote state leaves cleanup pending or unknown,
with the attempt record and recovery instructions available.
Interrupting local observation preserves the record and lets the CI job
continue independently. Explicit resume-observation and cleanup operations
recover the same attempt. Cleanup uses bounded attempts that can run after
the original local operation has been canceled. ReleaseKit observes uncertain
remote writes before classifying their outcome.
Reports distinguish workflow execution, artifact generation, hosted-content
verification, and cleanup. They identify remaining resources and provide
instructions for continued observation or cleanup. The coordinator retains
enough evidence to recover after interruption or service unavailability.
Rehearsals are explicitly requested diagnostics. Ordinary source publication
continues to complete at the successful production tag push, with hosted
delivery tracked separately. A rehearsal waits for CI because its purpose is
to verify that workflow.
## Alternatives considered
- Direct local API exercises verify local write capabilities while leaving
CI credential injection and application builds unexercised.
- A separate sandbox repository isolates events but exercises that
repository's permissions and workflow configuration.
- Canceling CI when the workstation command stops couples the job's lifetime
to the local connection and requires CI cancellation permissions.
- Deleting resources immediately on local interruption allows an active job
to recreate them after cleanup.
## Consequences
Developers gain repeatable evidence for the selected source, profile, CI
environment, and delivery destination without consuming a production version.
The rehearsal uses shared build and delivery behavior and preserves existing
releases.
The coordinator needs Woodpecker observation access and permission to remove
diagnostic forge resources. ReleaseKit owns attempt tracking, verification,
and recovery; consumers adopt the maintained workflow and supply product
configuration and credentials.
Successful cleanup removes temporary release resources. CI history,
notifications, and webhook effects can persist. Evidence applies to the
diagnostic tag namespace and the services exercised at that time; production
tag rules and future availability remain separate considerations.
The lifecycle requires public outcomes for partial verification and pending
cleanup. Exact command names, record formats, and result transport belong in
the implementation's public contracts.

View File

@@ -1,9 +1,11 @@
# Command line # Command line
ReleaseKit currently provides six commands. The exit statuses below belong The exit statuses below belong
to the native executable. `go run` examples are convenient for source execution, to the native executable. `go run` examples are convenient for source execution,
but the Go driver maps a nonzero child exit status to 1. Use the built executable but the Go driver maps a nonzero child exit status to 1. Use the built executable
or `./scripts/release` for publication when distinct statuses are needed. or `./scripts/release` for publication when distinct statuses are needed.
For the `go run` examples, [select the Go host target](consumers/adoption.md#select-the-go-host-target)
before running from a shell set to cross-compile.
Print the executable version: Print the executable version:
@@ -20,26 +22,28 @@ Check a local candidate:
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
``` ```
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the `VERSION` must match the profile's selected identifier format. Options must precede the
version. The repository argument defaults to the current directory. ReleaseKit version. The repository argument defaults to the current directory. ReleaseKit
resolves its containing Git checkout root before selecting the module or profile; resolves its containing Git checkout root before selecting the module or profile;
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
captured module, version, full tag, and commit. It checks the committed release note and captured module, version, full tag, and commit. It checks the committed release note and
local Git state, runs the standard offline Go test suite (with `-race` when local Git state, runs the standard offline Go test suite when Go is selected (with `-race` when
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...` `validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
pass after successful tests when `validation.go.full_vet` is true. It then runs pass after successful tests when `validation.go.full_vet` is true. It then runs
selected package compilation and committed Go formatting, followed by selected package compilation and committed Go formatting, followed by
configured additional checks in profile order. It does not inspect remote configured additional checks in profile order. It does not inspect remote
availability or publish a tag. availability or publish a tag.
The profile's optional `module_dir` selects a repository-relative physical For legacy profiles, `module_dir` selects a repository-relative physical
module directory; omission selects the root module. Validation and configured module directory; omission selects the root module. Explicit profiles select
product checks use that module selection. Additional check commands run with source and Go capabilities as described in the [configuration reference](config.md).
the selected module as their working directory and receive Additional check commands run with
the selected source as their working directory and receive
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`, `RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
`RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their `RELEASEKIT_SOURCE_DIR`, `RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
environment. These values are added to each child environment without changing environment. These values are added to each child environment without changing
the ReleaseKit process environment. the ReleaseKit process environment. Module values are empty for source-only
selections.
When `validation.go.compile_targets` is selected, `check` compiles all packages When `validation.go.compile_targets` is selected, `check` compiles all packages
for each configured `GOOS/GOARCH` pair after tests and full vet, using static for each configured `GOOS/GOARCH` pair after tests and full vet, using static
@@ -75,23 +79,24 @@ Unsupported argument sequences print usage to standard error.
Publish a source tag: Publish a source tag:
```sh ```sh
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] VERSION go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--expected-source DIR] [--record-dir DIR] VERSION
``` ```
`publish` reads the same product, remote, validation, and additional-check `publish` reads the same product, remote, validation, and additional-check
settings as `check`. It checks the authoritative remote and validates the settings as `check`. It checks the authoritative remote and validates the
candidate: the single standard offline Go test suite runs first, with `-race` candidate: when Go is selected, the standard offline Go test suite runs first, with `-race`
when `validation.go.race` is true. When `validation.go.full_vet` is true, when `validation.go.race` is true. When `validation.go.full_vet` is true,
test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful
tests. Selected package compilation and committed Go formatting follow. The tests. Selected package compilation and committed Go formatting follow. The
selected file checks then run in order: workspace files, local replacements, selected file checks then run in order: workspace files, local replacements,
file size, and Markdown. Configured checks run afterward in profile order. It file size, and Markdown. Configured checks run afterward in profile order. It
then creates an annotated local tag then creates an annotated local tag
and pushes only its exact full tag object. It prints the confirmed semantic and pushes only its exact full tag object. It prints the confirmed identifier,
version, full tag, candidate commit, and tag object full tag, candidate commit, and tag object
on success. Validation on success. Validation
progress and failed publication state, including the captured publication progress and failed publication state, including the captured publication
endpoint for recovery, are written to standard error. A signal endpoint for recovery, are written to standard error. HTTP(S) endpoint
userinfo is masked in diagnostics. A signal
cancels the active operation; if it arrives during a push, the library's cancels the active operation; if it arrives during a push, the library's
bounded reconciliation determines whether the exact tag was accepted. bounded reconciliation determines whether the exact tag was accepted.
Shared validation failures use the same check and finding presentation as Shared validation failures use the same check and finding presentation as
@@ -126,10 +131,11 @@ It reports outside-checkout links to standard error unless boundary enforcement
is selected; submodule contents remain out of scope. Markdown failures stop is selected; submodule contents remain out of scope. Markdown failures stop
publication before product checks or tag creation. publication before product checks or tag creation.
`--expected-module DIR` optionally checks a launcher's selected physical module `--expected-module DIR` and `--expected-source DIR` optionally check a
against the profile's `module_dir` before candidate work. Both paths are launcher's selected physical directory against the profile's source selection
normalized relative to the repository; the profile remains the source of module before candidate work. Paths are normalized relative to the repository; the
selection. The root selection is `.`. profile remains the source of selection. If both flags are supplied, both must
match. The root selection is `.`.
The optional profile field `expected_push_url` applies only to `publish`. A The optional profile field `expected_push_url` applies only to `publish`. A
nonempty value must exactly match the effective push URL resolved by Git; nonempty value must exactly match the effective push URL resolved by Git;
@@ -137,13 +143,78 @@ mismatches fail during preflight before Go validation or tag creation. Git URL
rewrites are resolved first, and the push URL is used when fetch and push URLs rewrites are resolved first, and the push URL is used when fetch and push URLs
differ. `check` ignores this field. differ. `check` ignores this field.
The command automatically saves available publication evidence in the repository's
private attempt store. Use `--record-dir DIR` to select another directory; a
relative override is resolved from the source repository root. Standard error
reports the absolute saved record path or a recording warning separately from
the publication result. Recording failure does not change publication status.
When publication fails and a record was saved, the CLI also prints a copyable
`reconcile --record` command for that exact record. The command selects the
consumer module's registered Go tool when available. API-only consumers receive
a Go-tool invocation with durable private module files; see
[recovery storage](consumers/publish.md#retain-and-reconcile-publication-evidence).
Consumers without a module-selected ReleaseKit dependency use the running
executable's absolute path. A module-preparation failure reports a warning and
uses a persistent native executable when available. Recognized temporary Go-build
executables provide no native fallback after their driver exits. Command
preparation has its own bounded context after a failed publication, so publication
cancellation permits preparing the later invocation. Each entry point preserves
the recovery exit status. Run a generated Go-tool handoff in a POSIX shell.
When it runs, it sets `GOOS` and `GOARCH` to the selected Go toolchain's
`GOHOSTOS` and `GOHOSTARCH`.
If the selected entry point becomes unavailable, use another supported ReleaseKit
CLI with the saved record.
The command returns status 0 for confirmed publication, 1 for a known The command returns status 0 for confirmed publication, 1 for a known
publication failure or conflict, 2 for usage, profile, or invalid-version publication failure or conflict, 2 for usage, profile, or invalid-version
errors, and 3 when the push outcome remains unknown. Unknown status must be errors, and 3 when the push outcome remains unknown. Unknown status must be
resolved against the authoritative remote before retrying. The resolved with the explicit-record recovery operation below before retrying. The
[maintainer procedure](release.md) selects the repository profile and gives [maintainer procedure](release.md) selects the repository profile and gives
the source-release workflow. the source-release workflow.
## Recover a saved publication attempt or discover local attempts
```sh
releasekit reconcile --record FILE [--json]
releasekit publication-attempts [--repo DIR] [--record-dir DIR] [--json]
```
`reconcile` requires one explicitly selected record and reads a relative `FILE`
from the invoking directory. It observes the endpoint and tag stored in that
record; it does not load a profile, inspect the current candidate or local tag,
run checks, or change repository state. `publication-attempts` lists records in
the selected store without querying remotes or choosing an attempt. An omitted
`--repo` means the current directory. Its relative `--record-dir` is resolved
from the selected repository root; an absolute directory can be listed outside
a checkout. The selected directory must already exist. Discovery reports usable
records and per-record diagnostics together when some records cannot be read.
By default, both operations print human-readable output. `--json` writes one
structured document to standard output after valid arguments, including for
reconciliation and discovery failures. Recovery does not run candidate checks
or make hosted delivery requests. It reads the record's captured endpoint, while
using current supported transport settings for its recorded remote name.
| Recovery command result | Status |
| --- | --- |
| Reconciliation observes the intended publication | 0 |
| Reconciliation observes absence or conflict | 1 |
| Reconciliation cannot read or decode the selected record, or has an invocation error | 2 |
| Reconciliation remains unknown, including missing evidence or cancellation | 3 |
| Discovery completes without record diagnostics, including an existing empty store | 0 |
| Discovery is incomplete or fails, including cancellation | 1 |
| Discovery argument or usage error | 2 |
| Either command cannot write its JSON output | 1 |
A JSON write failure reports a local output diagnostic on standard error. This
status describes reporting failure and leaves the observed publication state
unchanged.
The CLI JSON schema and safe evidence fields are documented in the
[publication record format](integrations/publication-records.md). Recovery
guidance for storage, older evidence, and retry decisions is in the
[maintainer procedure](release.md#resolve-publication-failures).
Build selected application targets: Build selected application targets:
```sh ```sh
@@ -162,20 +233,37 @@ output directory are invalidated; no new receipt is written. An
empty target list returns the source commit without building or writing a empty target list returns the source commit without building or writing a
receipt. receipt.
The current receipt format carries the selected source and release identity;
receipts from older formats must be regenerated with `build`.
The command returns status 0 on completion, 1 for build or output failure, and The command returns status 0 on completion, 1 for build or output failure, and
2 for usage, profile, or invalid-version errors. It builds the current source 2 for usage, profile, or invalid-version errors. It builds the current source
tree and does not perform candidate validation or remote publication. `check` tree and does not perform candidate validation or remote publication. `check`
and `publish` run the same configured build after their one candidate and `publish` run the same configured build after their one candidate
validation, using temporary output outside the worktree. validation, using temporary output outside the worktree.
Deliver a tagged source release to Gitea: Inspect working release configuration without creating a release:
```sh
releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]
```
Validation defaults to local credentials and read-only remote access. Operation
flags narrow the selected capabilities; `--offline` omits remote observations.
See the [readiness guide](consumers/readiness.md) for scope, evidence, and exit
statuses.
Deliver a tagged source release:
```sh ```sh
go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION
``` ```
`deliver` requires a `delivery` profile object and its configured token `deliver` requires a `delivery` profile object with an explicit
environment variable, which defaults to `RELEASEKIT_GITEA_TOKEN`. It verifies `"forge": "gitea"` selection and a token loaded from its configured local
credential file. The destination URL does not select a forge. Selection
errors are reported before token access or delivery work. Credential selection
and errors are defined in the [configuration reference](config.md). It verifies
the local tag, clean tagged checkout, hosted tag, and committed release note, the local tag, clean tagged checkout, hosted tag, and committed release note,
then creates or finds the release page and reports delivery state separately then creates or finds the release page and reports delivery state separately
from source publication. Historical lightweight tags and detached checkouts from source publication. Historical lightweight tags and detached checkouts
@@ -194,16 +282,28 @@ Profiles without targets use page-only delivery
and need no receipt, binary build, or manifest. `deliver` never runs candidate and need no receipt, binary build, or manifest. `deliver` never runs candidate
checks or publishes a tag. checks or publishes a tag.
After cheap local checks, delivery performs authenticated, read-only repository
preflight before a managed build or full artifact size and digest verification.
An unavailable preflight leaves delivery `not_attempted`; after preflight
succeeds, local artifact verification still finishes before any hosted write.
Use one `deliver` invocation for the normal workflow. To build without delivery Use one `deliver` invocation for the normal workflow. To build without delivery
credentials, or to retain build output across retries, run `build --output DIR` credentials, or to retain build output across retries, run `build --output DIR`
first and then run `deliver --assets DIR` with the token available. The ordinary first and then run `deliver --assets DIR` with the token available. The ordinary
`deliver` command does not download application dependencies or change the `deliver` command does not download application dependencies or change the
checkout. checkout.
The command returns 0 for complete delivery, 1 for a known failure, conflict, The command returns 0 for complete delivery without a local error, 1 for an
or partial delivery, 2 for usage, profile, or missing-credential errors, and 3 unavailable preflight, a known delivery failure, conflict, partial delivery, or
when a remote write remains uncertain. The result lists matching, uploaded, local cleanup failure after hosted completion, and 2 for usage,
pending, conflicting, and uncertain assets as disjoint current observations; profile, forge-selection, local credential-loading, or classified preflight
configuration/access errors. A remote write whose outcome remains uncertain
returns 3, including when cancellation prevents reconciliation. Cancellation
without an unresolved write returns 1, including during preflight or
preparation. Later authorization failures follow
the delivery outcome: known failure returns 1; an unresolved write returns 3.
The result lists matching, uploaded, pending, conflicting, and uncertain assets
as disjoint current observations;
early failures may leave some declared assets unreported. On failure, the CLI early failures may leave some declared assets unreported. On failure, the CLI
prints state-based recovery guidance. Fix local or preflight failures before prints state-based recovery guidance. Fix local or preflight failures before
retrying; fix the reported cause before retrying partial delivery; resolve an retrying; fix the reported cause before retrying partial delivery; resolve an
@@ -218,22 +318,26 @@ known missing assets are added. See the
Prepare a tagged CI checkout and deliver it: Prepare a tagged CI checkout and deliver it:
```sh ```sh
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG
``` ```
`TAG` is the complete Git tag name, including any module path prefix. Its last `TAG` is the complete Git tag name, including any source path prefix. Its last
path component must be a stable semantic version; other commands continue to component is validated against the profile's selected version format after
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from checkout. By default, `ci-deliver` fetches the exact `TAG` from
the selected Git remote (default `origin`), requires its peeled commit to match the selected Git remote (default `origin`), requires its peeled commit to match
the required full `--commit` object ID, checks out that commit detached, then the required full `--commit` object ID, checks out that commit detached, then
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
checks read-only against the existing checkout and does not fetch or check out. checks read-only against the existing checkout and does not fetch or check out.
In either mode, it loads the profile from the verified source. `--expected-module` Preparation diagnostics mask userinfo in HTTP(S) remote URLs.
optionally checks that the profile selects the module chosen by a launcher; In either mode, it loads the profile from the verified source. The optional
module selection itself remains profile-owned. The command validates delivery `--expected-module` and `--expected-source` checks verify the launcher's
settings and the configured token, then downloads application dependencies only selected directory against the profile. The command compares the selected
when the profile selects build targets. Binary profiles are built and delivered source's derived release tag with the full event tag before forge access or
through the same facade path as `deliver`; source-only profiles skip dependency dependency preparation, then validates explicit forge selection and resolves
the configured CI environment token. For binary profiles, it performs a read-only repository
preflight before downloading application
dependencies; delivery performs a fresh check after dependency preparation.
Source-only profiles rely on delivery's automatic preflight and skip dependency
downloads and binary builds. downloads and binary builds.
`--config` follows the existing profile path rules: relative paths are resolved `--config` follows the existing profile path rules: relative paths are resolved
from `--repo`, and absolute paths are used as-is. The default mode prepares and from `--repo`, and absolute paths are used as-is. The default mode prepares and
@@ -247,17 +351,57 @@ tag arguments. The event ID may identify an annotated tag object; see the
[delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for resolution [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for resolution
and workflow preparation. The CLI does not read and workflow preparation. The CLI does not read
provider-specific environment variable names. Checkout and dependency provider-specific environment variable names. Checkout and dependency
preparation failures return status 1; usage, profile, credential, and invalid preparation failures, unavailable preflight, and cancellation during those
version errors return status 2. Final delivery uses the same statuses as steps return status 1. Usage, profile, forge-selection, local credential-loading,
`deliver`: 0 for complete, 1 for known failure, conflict, or partial delivery, classified preflight configuration/access, and invalid-version errors return
and 3 for uncertain remote state. status 2. Final delivery uses the same statuses as `deliver`: 0 for complete,
1 for known failure, conflict, or partial delivery, and 3 for uncertain remote
state, including when cancellation prevents reconciliation.
The maintained module-based tag workflow verifies and checks out the event tag The maintained module-based tag workflow verifies and checks out the event tag
before resolving the consumer module. It builds the ReleaseKit version already before resolving the consumer module. It invokes the ReleaseKit tool by its full
selected by that tagged `go.mod`, using temporary alternate module files outside package path for the version already selected by that tagged `go.mod`, using
the source checkout. This tool bootstrap is separate from `ci-deliver`'s temporary alternate module files outside the source checkout. This tool bootstrap
application dependency preparation for binary profiles. ReleaseKit's own is separate from `ci-deliver`'s application dependency preparation for binary
source workflow self-bootstraps `./cmd/releasekit`; consumers without a declared profiles. ReleaseKit's own source workflow self-bootstraps `./cmd/releasekit`;
consumers without a declared
ReleaseKit module dependency can use the separately installed-tool command. ReleaseKit module dependency can use the separately installed-tool command.
See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for
compatible Go environments, retries, and preparation details. compatible Go environments, retries, and preparation details.
## Rehearsal and recovery
```sh
releasekit test [--repo DIR] [--config FILE] [--ref REF] [--record-dir DIR] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]
releasekit test-resume --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]
releasekit test-cleanup --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--cleanup-timeout DURATION] [--json]
```
`test` captures `HEAD` or `--ref`, reads the profile from that commit, and
pushes a temporary annotated diagnostic tag. It observes the selected
Woodpecker delivery step, verifies its recorded page and artifact evidence,
and attempts cleanup only after matching CI runs are quiescent. It does not
require a clean checkout, choose a production version, or cancel CI. The
observation timeout defaults to 30 minutes; `--timeout 0` waits until the
context is canceled. Cleanup defaults to two minutes and its timeout must be
positive.
The command reports the exact private record path. Recovery always requires
that explicit path; it never selects a newest attempt. Local credentials come
from the recorded commit's profile unless file overrides are supplied. With
both overrides, recovery can load credentials without the recorded profile;
the checkout remains necessary for Git operations. `test-resume` observes and
then cleans; `test-cleanup` reports cleanup independently of prior verification.
Human output uses the current durable executable in its recovery commands when
available. If it was a temporary Go-run executable, use a supported ReleaseKit
tool with the same record after that executable disappears.
The [rehearsal guide](consumers/rehearsal.md) covers permissions and the limits
of the result.
With `--json`, each command emits one `schema_version: 1` object with safe
identity, workflow, build, verification and cleanup outcomes, resource links,
remaining resources and diagnostics. Status 0 means verification and cleanup
succeeded for `test` or `test-resume`, or cleanup succeeded for `test-cleanup`.
Status 2 denotes usage, configuration or required input failure before effects;
1 denotes a known failure or reporting error; 3 denotes unresolved CI or
remote state or pending cleanup. An error can accompany useful partial results.

View File

@@ -10,21 +10,50 @@ The current profile fields are:
| Field | Required | Behavior | | Field | Required | Behavior |
| --- | --- | --- | | --- | --- | --- |
| `product` | Yes | Product name used by release operations. | | `product` | Yes | Product name used by release operations. |
| `module_dir` | No | Repository-relative physical Go module directory with its own `go.mod`; omission selects `.` (the repository root). | | `module_dir` | No | Repository-relative physical directory; in the legacy model it selects a Go module and defaults to `.`. |
| `source` | No | Explicit source selection with optional `dir` and `tag_prefix`. |
| `go` | No | A non-null object selects Go capability in the explicit model. |
| `publication` | No | Explicit publication `mode`: `source` or `go-module`. |
| `version` | No | Explicit identifier `format` and `prefix`. |
| `remote` | No | Selected Git remote; defaults to `origin`. | | `remote` | No | Selected Git remote; defaults to `origin`. |
| `expected_push_url` | No | Exact effective push URL required by `publish`; ignored by local `check`. | | `expected_push_url` | No | Exact effective push URL required by `publish`; ignored by local `check`. |
| `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. | | `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. |
| `validation` | No | Optional shared checks selected by ReleaseKit. | | `validation` | No | Optional shared checks selected by ReleaseKit. |
| `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. | | `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. |
| `delivery` | No | Optional Gitea `base_url`, `owner`, `repository`, and `token_env` settings for tagged-source delivery. | | `delivery` | No | Optional selected forge and destination fields for tagged-source delivery. |
| `readiness` | No | Optional explicit files to check during readiness. |
| `rehearsal` | No | Diagnostic selector and Woodpecker observation settings, required for a rehearsal. |
`module_dir` names the selected module's physical location in the repository; When Go is selected, `module_dir` names the module's physical location;
ReleaseKit reads its declared import path from that module's own `go.mod`. The ReleaseKit reads its declared import path from that module's own `go.mod`. The
physical directory and declared path are distinct: a declared `/v2` module can physical directory and declared path are distinct: a declared `/v2` module can
live either at `integrations/core` or `integrations/core/v2`, while both use the live either at `integrations/core` or `integrations/core/v2`, while both use the
same full release tag. Root-only profiles can omit `module_dir` and do not need same full release tag. Root-only profiles can omit `module_dir` and do not need
a module map. a module map.
When all four selection objects are absent or null, the legacy selection uses
Go module publication and prefixed stable semantic versions. Any non-null
selection object chooses the explicit model: `source.dir` defaults to `.` or
the supplied `module_dir`, `go` defaults to disabled, and `publication.mode`
defaults to `source`. If both directory fields are supplied they must resolve
to the same physical directory. Go module publication requires `go: {}`.
`version.format` defaults to `semver` and also accepts `date` and `year-month`;
`version.prefix` accepts `v` or an empty string, defaulting to `v` for SemVer
and empty for calendar formats. `source.tag_prefix` overrides the physical
source directory used as the source-tag prefix; an explicit empty string
selects an unprefixed tag. Go module publication requires prefixed SemVer and
rejects tag-prefix overrides that conflict with Go's module tag rules. The Go
facade's `Check`, `Publish`, `Build`, and `Deliver` and the CLI candidate and
delivery commands use the selected format. See the [command reference](cli.md)
for invocation details.
After its selected prefix, `semver` accepts stable `MAJOR.MINOR.PATCH` with
no leading zeroes in numeric components. `date` accepts `YYYY-MM-DD` or
`YYYY-MM-DD.R` with a valid Gregorian date and positive, unpadded revision;
the first release has no suffix. `year-month` accepts `YYYY.MM.R`, with a
two-digit month and a required nonnegative, unpadded revision. Years range
from 0001 through 9999. ReleaseKit preserves the selected identifier spelling.
Each check requires a nonempty `args` array whose first element names the Each check requires a nonempty `args` array whose first element names the
executable. Arguments are passed directly to the child process; ReleaseKit does executable. Arguments are passed directly to the child process; ReleaseKit does
not parse a shell command string. Select a shell explicitly when a check needs not parse a shell command string. Select a shell explicitly when a check needs
@@ -45,9 +74,11 @@ exist in the candidate, even when no file checks are enabled. Paths are literal,
repository-relative files with no glob semantics and may select a file outside repository-relative files with no glob semantics and may select a file outside
the chosen module. ReleaseKit deduplicates them with module inputs by path. This the chosen module. ReleaseKit deduplicates them with module inputs by path. This
field does not enable any checks or expand Go test, vet, or package-compilation field does not enable any checks or expand Go test, vet, or package-compilation
scope. Automatic file inputs stop at independent nested-module boundaries; scope. For Go selections, automatic file inputs stop at independent
vendored files remain included. Reference inspection can read destinations nested-module boundaries; source-only selections treat nested `go.mod` files
elsewhere in the captured repository without adding them to those inputs. as data. Vendored files remain included. Reference inspection can read
destinations elsewhere in the captured repository without adding them to those
inputs.
`validation.go.race` enables the race detector for the single standard Go test `validation.go.race` enables the race detector for the single standard Go test
suite. `validation.go.full_vet` runs a separate native `go vet` pass after that suite. `validation.go.full_vet` runs a separate native `go vet` pass after that
suite succeeds; ReleaseKit disables test-time vet for that suite to avoid suite succeeds; ReleaseKit disables test-time vet for that suite to avoid
@@ -59,6 +90,8 @@ This source compatibility check does not name or produce binaries, run a target
executable, or create an artifact manifest. Omitted or empty `compile_targets` executable, or create an artifact manifest. Omitted or empty `compile_targets`
selects no package-compilation pass. When `full_vet` is omitted or false, the selects no package-compilation pass. When `full_vet` is omitted or false, the
test command keeps its existing vet behavior. These settings are independent. test command keeps its existing vet behavior. These settings are independent.
For source-only selections, Go execution checks and nonempty build targets are
configuration errors; explicitly selected file checks remain available.
`validation.go_format` checks regular committed Go blobs with the Go formatter `validation.go_format` checks regular committed Go blobs with the Go formatter
used to build ReleaseKit. It uses the selected file inputs, including vendor and used to build ReleaseKit. It uses the selected file inputs, including vendor and
explicit shared files, and ignores explicit shared files, and ignores
@@ -141,12 +174,70 @@ symlink size is the committed link text. Gitlinks have no measured size. Only
the captured candidate is checked, one offending file is reported at a time, the captured candidate is checked, one offending file is reported at a time,
and historical or aggregate repository size is not measured. and historical or aggregate repository size is not measured.
The `delivery` object contains `base_url`, `owner`, `repository`, and optional `validation.forbidden_files` is an optional list of literal repository-relative
`token_env`. Its values are required when running `deliver`, but credentials are file paths that must be absent from the captured commit. It runs after the Go
not required for `check`, `publish`, or `build`. `token_env` names the checks and before other file checks, using the `forbidden-files` identity and
environment variable containing the Gitea token; it defaults to reporting selected committed paths. Omission, `null`, or `[]` disables it.
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and Paths use slash separators and ordinary relative normalization and must stay
passes its value explicitly to the library operation. within the repository. They are checked against the whole captured repository,
independently of the selected module and `shared_files`. The check reads path
metadata only; it does not read token contents, follow symlink targets, require
local files to exist, or inspect Git history. Existing clean-index/worktree
requirements still apply to candidate operations. An ignore rule alone does
not remove a previously committed file from the candidate.
`readiness.required_files` optionally lists literal repository-root-relative or
absolute files whose readability `validate` checks. These are explicit local
inputs, not inferred SSH authentication requirements; see the
[readiness guide](consumers/readiness.md).
A `rehearsal` object can select a dispatch `selector` (default `root`) and a
`woodpecker` object with `base_url`, numeric `repository_id`, exact `workflow`
and `step` names, and a local `token_file`. These settings are required only
for rehearsal operations. Relative token paths resolve from the checkout root;
the file is read separately from the forge credential and its token is never
stored in the attempt record. See the
[rehearsal record format](integrations/rehearsal-records.md) for captured
identity and recovery evidence.
The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and
context-specific `credentials`. A delivery request must set `forge` to
`"gitea"`; a missing or unsupported selection is an error for delivery. These
requirements do not apply to `check`, `publish`, or `build`.
`delivery.credentials.local.token_file` selects the local delivery token file.
Relative paths resolve from the Git repository root; absolute paths are used as
supplied. `delivery.credentials.ci.token_environment_variable` selects the job
environment variable, defaulting to `RELEASEKIT_DELIVERY_TOKEN` when the `ci`
object is present without a name. `deliver` requires local credentials and
`ci-deliver` requires CI credentials. Neither context falls back to the other.
Missing, unreadable, or blank selected credentials fail with status 2. Token
contents are trimmed. The obsolete `delivery.token_file` and `delivery.token_env`
fields must be moved to their corresponding context-specific locations.
Ignore the local token file in Git. Optionally select the same path in
`validation.forbidden_files` to reject candidates that include it; an ignore
rule does not remove an already tracked file.
After resolving the token, delivery performs an authenticated, read-only
repository access check. Invalid destination settings, missing or rejected
credentials, known insufficient permissions, and inaccessible destinations are
configuration/credential failures. An unavailable service or canceled check is
an operational failure.
See the [CLI contract](cli.md) for exact exit statuses. Successful preflight
confirms authentication and repository access and accounts for any exposed
delivery-permission deficiency. It does not guarantee later release or asset
writes. Local artifact size and digest checks follow preflight and still finish
before hosted writes.
`validate` loads only credentials for selected operations. `test` and recovery
commands load their selected local credentials; `check`, `publish`, and `build`
do not read a delivery token. The CLI passes the
resolved value explicitly to the library operation. `ci-deliver` checks the
destination before downloading application dependencies for a binary build;
the later delivery performs a fresh check. Page-only CI relies on delivery's
automatic check. Selecting a token file and selecting the optional
forbidden-file validator are independent settings.
`expected_push_url`, when nonempty, is compared exactly with Git's resolved `expected_push_url`, when nonempty, is compared exactly with Git's resolved
effective push URL during `publish`, before candidate validation. It applies effective push URL during `publish`, before candidate validation. It applies
@@ -155,16 +246,17 @@ such as `insteadOf` are resolved before comparison. A mismatch fails preflight;
omitting the field keeps the selected remote's existing behavior. `check` is omitting the field keeps the selected remote's existing behavior. `check` is
local-only and ignores this publication expectation. local-only and ignores this publication expectation.
The `check` and `publish` commands run one When Go capability is selected, `check` and `publish` run one
`go test -mod=readonly -count=1 ./...` suite with Go module and toolchain network `go test -mod=readonly -count=1 ./...` suite with Go module and toolchain network
access disabled, adding `-race` when `validation.go.race` is true. When access disabled, adding `-race` when `validation.go.race` is true. When
`validation.go.full_vet` is true, they add `-vet=off` to that test command and `validation.go.full_vet` is true, they add `-vet=off` to that test command and
run native `go vet -mod=readonly ./...` after successful tests. They then run run native `go vet -mod=readonly ./...` after successful tests. They then run
`go build -mod=readonly -o <os.DevNull> ./...` in static mode for each `go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
`validation.go.compile_targets` entry, in profile order. Compile failures use `validation.go.compile_targets` entry, in profile order. Compile failures use
the `package-compile` identity and include the selected target. When selected, the `package-compile` identity and include the selected target.
`validation.go_format` checks regular committed Go source with go/format after
package compilation; unformatted paths use the `go-format` identity. When File checks apply to either source kind. When selected, `validation.go_format`
checks regular committed Go source with go/format after any Go execution checks; unformatted paths use the `go-format` identity. When
`validation.module_distribution.workspace_files` is true, shared validation `validation.module_distribution.workspace_files` is true, shared validation
also reports committed go.work and go.work.sum blobs after Go formatting, using also reports committed go.work and go.work.sum blobs after Go formatting, using
the workspace-files identity. Uncommitted workspace files are not inspected. the workspace-files identity. Uncommitted workspace files are not inspected.
@@ -196,9 +288,11 @@ retained for retries or when build and delivery credentials need separate
invocations. Ordinary `deliver` does not download application dependencies or invocations. Ordinary `deliver` does not download application dependencies or
change the checkout. change the checkout.
`ci-deliver` takes a full Git `TAG`; its final path component is the stable `ci-deliver` takes a full Git `TAG`. A production tag ends in the identifier
semantic version and the complete value is checked against the profile's accepted by the profile's selected version format, and the complete value is
derived tag. By default it fetches the selected tag, confirms its peeled commit checked against its derived tag. Diagnostic tags use their separate
[rehearsal identity and manifest](integrations/rehearsal-records.md). By default
it fetches the selected tag, confirms its peeled commit
matches the provider-supplied commit ID, checks it out detached, and verifies matches the provider-supplied commit ID, checks it out detached, and verifies
the tag, HEAD, and clean worktree. With `--prepared`, it performs the same the tag, HEAD, and clean worktree. With `--prepared`, it performs the same
checks against an existing checkout without fetching or checking out. It then checks against an existing checkout without fetching or checking out. It then

View File

@@ -1,8 +1,22 @@
# Adopt ReleaseKit # Adopt ReleaseKit
Use a versioned Go tool dependency when ReleaseKit provides the repository's Use a versioned Go tool dependency when a Go module provides the repository's
release commands. This records the CLI in `go.mod` and keeps it available to release commands. Source-only repositories can instead use the installed-tool
maintainers without adding imports to application or library code. launcher described below.
## Source-only repositories
The [source-only example](../../examples/source-only/README.md) provides a
profile, local launcher, and tag-verified Woodpecker workflow without requiring
an application `go.mod`. Commit a root `.releasekit-version` containing one
stable ReleaseKit module version. The example selects v0.11.0, which supplies
the source-only profile and workflow interfaces.
The maintained installer uses the same committed pin locally and in CI,
installs the host executable in the ignored `.releasekit/tools` directory,
and preserves Go proxy and checksum settings. A failed install does not leave a
usable partial executable. The durable executable also supports the exact
publication-recovery command printed after an uncertain push.
## CLI tool dependency ## CLI tool dependency
@@ -10,12 +24,15 @@ From the consumer module's root, select the ReleaseKit version to adopt:
```sh ```sh
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}" : "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
go get -tool "gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}" go get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
go mod tidy go mod tidy
go tool releasekit version
``` ```
Select a release that implements the API, profile, and workflow you are adopting. Select a release that implements the API, profile, and workflow you are adopting.
The [v0.11.0 release note](../releases/v0.11.0.md) covers
the new source selections, credential contexts, and rehearsal workflow.
The vanity module path starts with v0.5.0. Versions through v0.4.2 declare the
original module path and use their corresponding historical instructions.
The module-release interface requires a release containing that feature; The module-release interface requires a release containing that feature;
pre-feature versions through v0.3.0 use their corresponding historical interface. pre-feature versions through v0.3.0 use their corresponding historical interface.
Go records the executable package in Go records the executable package in
@@ -25,15 +42,42 @@ declaration retains the dependency through `go mod tidy`. Commit the resulting
version and review the module changes. version and review the module changes.
The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit
module declares a Go 1.26.0 minimum, so use Go 1.26.0 or later for the current module declares a Go 1.27.0 minimum, so use Go 1.27.0 or later for the current
release. Tool dependencies share the consumer's module graph: their requirements source. Tool dependencies share the consumer's module graph: their requirements
participate in dependency version selection and can raise the consumer module's participate in dependency version selection and can raise the consumer module's
Go minimum. See the Go minimum. See the
[Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool). [Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool).
Run `go tool releasekit` from within the consumer module to use its selected ### Select the Go host target
version. Follow the [CLI contract](../cli.md) for commands and exit statuses,
and the [configuration reference](../config.md) for the release profile. Invoke the ReleaseKit tool by its full package path from within the consumer
module to use its selected version. Go builds and caches the executable and
preserves its exit status. The full path distinguishes tools with the same
short name. A launcher can forward commands directly:
```sh
#!/bin/sh
releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
exec go tool go.maximumdirect.net/releasekit/cmd/releasekit "$@"
```
Save this launcher as `releasekit` and run `sh ./releasekit version` from the
selected module to verify registration. It preserves the consumer's workspace
and toolchain settings while selecting the host for the executable.
For a launcher callable from other directories, first change to its consumer
module directory. Follow the [CLI contract](../cli.md) for commands and exit
statuses.
Configured product checks inherit the launcher's host `GOOS` and `GOARCH`.
If a check needs an application target, set it in that check's `env` map or
command. The [configuration reference](../config.md) describes
check environments and the separate target selection for built-in builds.
For consumers using vendoring, register the CLI before running `go mod vendor`
so the vendor tree includes its dependencies. `go tool` follows Go's normal
vendor selection.
## Go API consumers ## Go API consumers
@@ -43,21 +87,60 @@ required imports and select the module version:
```sh ```sh
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}" : "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
go get "gitea.maximumdirect.net/eric/ReleaseKit@${RELEASEKIT_TOOL_VERSION}" go get "go.maximumdirect.net/releasekit@${RELEASEKIT_TOOL_VERSION}"
go mod tidy go mod tidy
``` ```
API consumers can also register the CLI with `go get -tool` as above. Both uses API consumers can also register the CLI with `go get -tool` as above. Both uses
share the module-selected ReleaseKit version. share the module-selected ReleaseKit version.
## Migrating from the original module path
Starting with v0.5.0, ReleaseKit's module is `go.maximumdirect.net/releasekit`.
Earlier releases declare `gitea.maximumdirect.net/eric/ReleaseKit`. The migration
is a direct cutover with the existing facade roles and command behavior.
For API consumers, update imports of the root facade and `buildinfo` to
`go.maximumdirect.net/releasekit` and
`go.maximumdirect.net/releasekit/buildinfo`, including generated code and tests.
Select v0.5.0 or a later compatible release using the package-dependency command
above. Packages imported through the old and new paths have distinct Go
identities; coordinate updates in packages that exchange ReleaseKit facade
types. Builders and applications using `buildinfo` should adopt the new path
together so version injection addresses the runtime implementation they use.
For CLI tool consumers, remove the old tool declaration before registering the
new CLI package with the tool-dependency command above:
```sh
go mod edit -droptool=gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit
```
Update copied release launchers and Woodpecker workflows so their
`releasekit_module` value is `go.maximumdirect.net/releasekit`. Use the maintained
examples matching the selected tool version. Run `go mod tidy` after updating
imports and tool declarations, review any old-path dependencies retained
transitively, and commit the resulting module files with the workflow changes.
Existing consumer tags retain their recorded module files, tool selection, and
matching workflows for retries. Apply these migration steps to new consumer
revisions. Source repository and hosted release URLs use
`https://forge.maximumdirect.net/base-layer/releasekit`; the vanity path is the
Go module identity.
## CI adoption ## CI adoption
The maintained [consumer tag-delivery workflow](delivery.md#woodpecker-tag-workflows) The maintained [consumer tag-delivery workflow](delivery.md#woodpecker-tag-workflows)
supports both tool and ordinary package dependencies. It builds ReleaseKit from supports both tool and ordinary package dependencies. It runs the ReleaseKit
the tagged consumer's module selection, so the committed module files also tool by its full package path with temporary metadata derived from the tagged
govern CI delivery and retries. Registering the CLI as a tool is sufficient for module, so the committed module files also govern CI delivery and retries.
Registering the CLI as a tool is sufficient for
consumers that use ReleaseKit only for maintainer commands. consumers that use ReleaseKit only for maintainer commands.
Update copied launchers and workflow templates separately when upgrading the
module dependency. ReleaseKit tests the generic bootstrap; consumer wiring tests
can focus on selectors and profile mapping. Profiles continue to select
application build targets.
Upgrade the module-selected tool and workflow together. For a tag created before Upgrade the module-selected tool and workflow together. For a tag created before
that upgrade, retry with the workflow matching the tool recorded at that tag. that upgrade, retry with the workflow matching the tool recorded at that tag.
Keep its immutable module files and tag intact. See the Keep its immutable module files and tag intact. See the

View File

@@ -8,7 +8,7 @@ import (
"context" "context"
"fmt" "fmt"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit" releasekit "go.maximumdirect.net/releasekit"
) )
func build(ctx context.Context) error { func build(ctx context.Context) error {
@@ -36,9 +36,9 @@ func build(ctx context.Context) error {
} }
``` ```
`Build` resolves `ModuleDir` and the selected module's working-tree declaration `Build` resolves the selected source and module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected stable once, records the repository's current `HEAD`, injects the selected identifier
version into `buildinfo.Version`, and returns repository/module identity, the into `buildinfo.Version`, and returns repository/source and module identity, the
derived tag, compiler identity, normalized targets, artifact paths, filenames, derived tag, compiler identity, normalized targets, artifact paths, filenames,
and SHA-256 digests. It does not require a release note, unused tag, clean and SHA-256 digests. It does not require a release note, unused tag, clean
`main`, or publication. Names follow `main`, or publication. Names follow
@@ -47,13 +47,19 @@ target pair is built once, at its first position. Local builds may use modified
source. `SourceVerified` is true only after a complete build observes clean source. `SourceVerified` is true only after a complete build observes clean
source and the same HEAD before and after compilation; binary delivery requires source and the same HEAD before and after compilation; binary delivery requires
that fact. This observation is not a source snapshot or attestation guarantee. that fact. This observation is not a source snapshot or attestation guarantee.
An explicit `Source` with `GoEnabled` can select general source publication and
a calendar format or a product major independent of the module import path.
The optional [rehearsal](rehearsal.md) uses its own diagnostic version and
verifies temporary artifacts through the actual CI delivery job.
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
module. The default output directory is `<module>/dist`; a relative `OutputDir` module. The default output directory is `<module>/dist`; a relative `OutputDir`
is resolved from the module, while an absolute path is used as supplied. is resolved from the module, while an absolute path is used as supplied.
Selected artifact filenames are regenerated. Other files in the output Selected artifact filenames are regenerated. Other files in the output
directory are left in place. A failed later build or native version check directory are left in place. A failed later build or native version check
returns the binaries already generated in `BuildResult.Artifacts`. returns completed, hashed binaries in `BuildResult.Artifacts`. If hashing a
newly built file fails, the error identifies its path and earlier completed
artifacts remain in the result.
Builds use the available compatible Go toolchain selected locally; ReleaseKit Builds use the available compatible Go toolchain selected locally; ReleaseKit
does not download a different toolchain automatically. It disables workspace does not download a different toolchain automatically. It disables workspace

View File

@@ -33,13 +33,26 @@ example, both `integrations/core/v2` and `integrations/core` can declare
`<module>/docs/releases/<version>.md`. `<module>/docs/releases/<version>.md`.
The repository must have a clean index and worktree on `main`, and the selected The repository must have a clean index and worktree on `main`, and the selected
version must be stable `vMAJOR.MINOR.PATCH`. The module-local committed version must match the selected format. With the module shorthand it must be
stable `vMAJOR.MINOR.PATCH`. The module-local committed
`<module>/docs/releases/<version>.md` note must have a first Markdown H1 containing the `<module>/docs/releases/<version>.md` note must have a first Markdown H1 containing the
product name and exact version as complete title elements. No local tag with product name and exact version as complete title elements. No local tag with
the derived complete tag may already exist. Different modules may use the same the derived complete tag may already exist. Different modules may use the same
semantic version with distinct notes and tags. semantic version with distinct notes and tags.
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite from the For an explicit source release, set `Source` on the request. A zero-valued
`SourceSpec` selects the repository root without Go capability; `Dir` selects
a nested physical source directory. Set `GoEnabled` for Go checks, and select
`PublicationGoModule` only when distributing a Go module. `VersionFormat` and
`VersionPrefix` select the production identifier grammar. A source-only check
needs no `go.mod` or Go toolchain, and its automatic file inputs include nested
`go.mod` files as data. The candidate reports its source scope and selection;
module fields are empty when Go is disabled.
An optional [rehearsal](rehearsal.md) checks the tagged CI delivery workflow
independently of this local candidate validation.
When Go is selected, ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite from the
selected module directory with the available compatible local Go toolchain. selected module directory with the available compatible local Go toolchain.
Set `Validation.Go.Race` to run that Set `Validation.Go.Race` to run that
suite with `-race`; set `Validation.Go.FullVet` to run suite with `-race`; set `Validation.Go.FullVet` to run
@@ -93,11 +106,18 @@ standard suite, selected vet/format/distribution checks, or Markdown navigation
checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and
consumer-specific assertions—such as tests of maintained examples—in those consumer-specific assertions—such as tests of maintained examples—in those
product-owned checks. product-owned checks.
The `Candidate` supplies both `RepositoryDir` and `ModuleDir`, plus the declared The `Candidate` supplies `RepositoryDir` and `SourceDir`, plus optional module
`ModulePath`, semantic `Version`, and full `Tag`; use its module directory for fields, the selected `Version`, and full `Tag`; use its source directory for
module-local product checks. ReleaseKit calls `AdditionalChecks` once after source-local product checks. ReleaseKit calls `AdditionalChecks` once after
shared validation when supplied. shared validation when supplied.
For local token files, set `Validation.ForbiddenFiles` to the repository-relative
paths that should stay out of the committed candidate, such as
`[]string{".releasekit/gitea-token"}`. Failures use `forbidden-files` and carry the
selected committed paths in `ValidationError.Findings`. This selection is
independent of module and shared-file inputs; see [GoDoc](../../check.go) for
the API contract and the [configuration reference](../config.md) for CLI use.
`ValidationSpec.SharedFiles` adds committed, repository-relative files to `ValidationSpec.SharedFiles` adds committed, repository-relative files to
ReleaseKit's optional file checks without enabling any checks. A nil slice ReleaseKit's optional file checks without enabling any checks. A nil slice
selects the optional defaults `COPYRIGHT`, `LICENSE`, and selects the optional defaults `COPYRIGHT`, `LICENSE`, and

View File

@@ -1,18 +1,24 @@
# Deliver a tagged source release # Deliver a tagged source release
Use `releasekit.Deliver` or the `deliver` command after a source tag exists. Use `releasekit.Deliver` or the `deliver` command after a source tag exists.
Select the delivery backend explicitly in the profile or
`DeliveryDestination`; the destination URL does not infer a backend.
Delivery status is separate from source publication: a delivery problem does Delivery status is separate from source publication: a delivery problem does
not move or remove the tag, and a retry can use the same immutable version. not move or remove the tag, and a retry can use the same immutable version.
The operation accepts historical lightweight and annotated tags, including a The operation accepts historical lightweight and annotated tags, including a
detached checkout, when the checked-out `HEAD` identifies the selected tag detached checkout, when the checked-out `HEAD` identifies the selected tag
commit. It does not require the old remote `main` to match. commit. It does not require the old remote `main` to match.
Delivery resolves the selected module's declaration and release note from the Delivery resolves the selected source and release note from the captured commit;
captured commit. `Version` remains the semantic version; the full tag includes it reads a module declaration only when Go is enabled. `Version` follows the
the selected module's repository-relative physical path when it is nested. The selected identifier format, and the full tag follows the selected publication
profile or API request selects the physical module directory. The optional API mode. The profile or API request selects the physical source directory. The optional API
`ExpectedTag` checks that a CI event's literal tag agrees with the derived tag `ExpectedTag` checks that a CI event's literal tag agrees with the derived tag
before any build or hosted request. before any build or hosted request. Page-only source delivery does not require a
Go module or compiler.
The optional [rehearsal](rehearsal.md) runs this delivery machinery in the
tag-triggered CI job with a diagnostic identity and read-back verification.
## CI preparation ## CI preparation
@@ -39,9 +45,15 @@ For binary profiles, call `PrepareBuildDependencies` with a
`DependencyPreparationRequest` selecting the repository and module after `DependencyPreparationRequest` selecting the repository and module after
checkout preparation and before delivery. It runs `go mod download` in that checkout preparation and before delivery. It runs `go mod download` in that
module with workspace discovery disabled and the available compatible local Go module with workspace discovery disabled and the available compatible local Go
toolchain. toolchain. Inside a Git checkout, `RepositoryDir` can name a subdirectory;
The operation may use the network and updates the Go module cache while `ModuleDir` is interpreted relative to the containing checkout root, and an
preserving the caller's proxy, private-module, credential, and cache settings. empty selection chooses that root. Previously, a supplied checkout subdirectory
acted as the selection base. Outside a checkout, the supplied directory remains
the base for `ModuleDir`.
Preparation overrides an alternate module file selected by `GOFLAGS`, while
retaining other effective Go settings. The operation may use the network and
updates the Go module cache while preserving the caller's proxy, private-module,
credential, and cache settings.
If checksums are missing, Go may update `go.sum`. For binary CI delivery, prepare If checksums are missing, Go may update `go.sum`. For binary CI delivery, prepare
and commit the selected module's `go.sum` before tagging: delivery verifies the and commit the selected module's `go.sum` before tagging: delivery verifies the
tagged source remains clean after dependency preparation. See the tagged source remains clean after dependency preparation. See the
@@ -62,10 +74,14 @@ Add a Gitea destination to the profile:
{ {
"product": "Example", "product": "Example",
"delivery": { "delivery": {
"forge": "gitea",
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",
"token_env": "RELEASEKIT_GITEA_TOKEN" "credentials": {
"local": {"token_file": ".releasekit/gitea-token"},
"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}
}
} }
} }
``` ```
@@ -74,14 +90,40 @@ Fetch and check out the immutable tag, then deliver it:
```sh ```sh
git checkout --detach v1.2.3 git checkout --detach v1.2.3
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3 releasekit deliver v1.2.3
``` ```
The CLI reads the named token variable only for `deliver`; its default name is The CLI resolves the local token file for `deliver` and the CI environment
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before variable for `ci-deliver`. It verifies the local checkout and hosted tag before
creating or accepting a hosted release page. The full checked-in note is the creating or accepting a hosted release page. The full checked-in note is the
hosted body. A retry accepts an identical page and matching attachments, adds hosted body. A retry accepts an identical page and matching attachments, adds
only missing assets, and reports conflicts without replacing content. only missing assets, and reports conflicts without replacing content.
For local delivery, save a Gitea personal access token in a git-ignored file such
as `.releasekit/gitea-token` and configure:
```json
{
"product": "Example",
"validation": {
"forbidden_files": [".releasekit/gitea-token"]
},
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "example",
"credentials": {"local": {"token_file": ".releasekit/gitea-token"}}
}
}
```
Add `.releasekit/` to the consumer's ignore rules and use owner-only file
permissions for the saved token. Then run `releasekit deliver v1.2.3` from the
tagged checkout. CI supplies the variable selected in its own credential declaration. See the
[configuration reference](../config.md) for context selection, path resolution, and the
optional candidate check. The validator checks the selected committed paths;
it does not scan for secrets in other files or past commits.
For nested modules, the note comes from that module's committed For nested modules, the note comes from that module's committed
`docs/releases/<version>.md`, and the hosted page is keyed by its complete tag. `docs/releases/<version>.md`, and the hosted page is keyed by its complete tag.
@@ -96,16 +138,18 @@ separate credentials between build and delivery, use two invocations:
```sh ```sh
releasekit build --output dist v1.2.3 releasekit build --output dist v1.2.3
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3 releasekit deliver --assets dist v1.2.3
``` ```
The build command does not need delivery credentials. The `--assets DIR` The build command does not need delivery credentials. The `--assets DIR`
directory must contain the private `.releasekit-build.json` receipt created by directory must contain the private `.releasekit-build.json` receipt created by
`build`. ReleaseKit checks its schema, repository, commit, version, resolved `build`. ReleaseKit checks its schema, repository, commit, source selection,
module directory and path, full tag, normalized build settings, and artifact identity kind, version, module directory and path, full tag, normalized build
declarations. Old receipts must be regenerated with the updated `build` settings, and artifact declarations. Old receipts must be regenerated with the
command. Delivery verifies the artifact bytes and sizes before making a hosted updated `build` command. Delivery verifies the artifact bytes and sizes after read-only
request; caller-owned files remain available for retries. preflight and before any hosted write; caller-owned files remain available for
retries. See the [receipt format](../integrations/build-receipts.md) for its
identity and compatibility rules.
Ordinary `deliver` does not download application dependencies or change the Ordinary `deliver` does not download application dependencies or change the
checkout. checkout.
@@ -118,6 +162,10 @@ an upload was confirmed during this invocation; `Pending` means known missing
work; `Conflicting` means different hosted content was found; `Uncertain` means work; `Conflicting` means different hosted content was found; `Uncertain` means
the remote state could not be resolved. the remote state could not be resolved.
An error can accompany `complete` when hosted delivery succeeded but removal
of managed build files failed. Address the reported local cleanup failure;
the completed hosted delivery does not need to be repeated.
Fix local or preflight failures before retrying. For partial delivery, fix the Fix local or preflight failures before retrying. For partial delivery, fix the
reported cause and retry the same version. Resolve an unknown remote outcome reported cause and retry the same version. Resolve an unknown remote outcome
before retrying. Investigate conflicts and use a new version if the source or before retrying. Investigate conflicts and use a new version if the source or
@@ -125,24 +173,74 @@ published content needs correction. If rebuilding could change bytes already
on the server, retain the original build output and retry with `--assets DIR`. on the server, retain the original build output and retry with `--assets DIR`.
The command does not run candidate checks or publish tags. The command does not run candidate checks or publish tags.
## Credential preflight
Both `Deliver` and the CLI perform a read-only destination preflight after
cheap local request and source checks. It happens before managed builds and
full artifact size and digest verification. If it succeeds, delivery verifies
the local artifact contents before making any hosted write. A failed preflight
leaves delivery `not_attempted`, including when the service is unavailable.
Call `PreflightDelivery` directly when another caller-controlled operation
should follow credential verification. The check needs no checkout or published
tag and performs no test release or upload. For Gitea it verifies authenticated
repository access; exposed metadata can identify known deficiencies, but
successful preflight does not guarantee later release or asset writes. A
`DeliveryPreflightError` identifies invalid destination settings, missing or
rejected credentials, known insufficient permissions, an inaccessible
destination, or unavailable verification. Its `Unwrap` method preserves the
cause for `errors.Is` and
`errors.As`. A 403 means access was denied, not necessarily that a token
expired; a 404 can mean a missing repository or hidden access.
```go
err := releasekit.PreflightDelivery(ctx, releasekit.DeliveryDestination{
Forge: releasekit.ForgeGitea,
BaseURL: "https://gitea.example",
Owner: "example",
Repository: "example",
Token: token,
})
if err != nil {
var preflight *releasekit.DeliveryPreflightError
if errors.As(err, &preflight) {
log.Printf("delivery preflight %s: %v", preflight.Kind, preflight.Err)
}
return err
}
```
The CLI performs the same check automatically. For binary `ci-deliver`, it
checks access before application dependency downloads, then `Deliver` checks
again after preparation. Page-only CI needs no separate preflight call.
`check`, `build`, and source `publish` remain independent of hosted delivery
credentials. Calling preflight before source publication is optional and does
not add a publication gate.
## Go API ## Go API
Pass the Gitea credential explicitly. Set `Build` to a `BuildSpec` to compile Pass the Gitea credential explicitly and select `ForgeGitea`. Set `Build` to a
selected targets as part of delivery. The facade verifies the local tag, clean `BuildSpec` to compile selected targets as part of delivery. The facade verifies
checkout, and committed release note before compiling. Managed output is stored the local tag, clean checkout, and committed release note before compiling.
outside the checkout and removed when delivery returns. `Output` receives build Managed output is stored outside the checkout and removed when delivery
progress. With no build, or with an empty target set, delivery is page-only. returns. `Output` receives build progress. With no build, or with an empty
target set, delivery is page-only.
To deliver binaries built separately, set `Prebuilt` to the `BuildResult`. To deliver binaries built separately, set `Prebuilt` to the `BuildResult`.
ReleaseKit checks its repository, module directory, declared module path, full ReleaseKit checks its repository, module directory, declared module path, full
tag, semantic version, tagged commit, normalized settings, and artifact evidence tag, semantic version, tagged commit, normalized settings, and artifact evidence
against the selected committed module. Binary results must record verified against the selected committed module. Binary results must record verified
source. The current files are checked against their recorded digests before any source. After cheap local and source checks, delivery performs read-only
hosted request. The files remain caller-owned, so callers can retain the credential preflight, verifies the local artifacts in full, and then makes
original bytes for retries and are responsible for cleanup. With neither hosted writes. The current files are checked against their recorded digests
artifact source, an empty managed target set, or a matching empty prebuilt before those writes. Preflight confirms only the access evidence available from
result, delivery is page-only. Do not set both `Build` and `Prebuilt` in one the service, as described above. The files remain caller-owned, so callers can
request. retain the original bytes for retries and are responsible for cleanup. With
neither artifact source, an empty managed target set, or a matching empty
prebuilt result, delivery is page-only. A prebuilt result with no targets or artifacts
must still identify the matching repository, module directory and path, tag,
commit, and version; a zero `BuildResult` does not. Do not set both `Build` and
`Prebuilt` in one request.
```go ```go
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{ result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
@@ -151,7 +249,8 @@ result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
Product: "Example", Product: "Example",
Version: "v1.2.3", Version: "v1.2.3",
ExpectedTag: "integrations/example/v1.2.3", // optional CI event check ExpectedTag: "integrations/example/v1.2.3", // optional CI event check
Destination: releasekit.GiteaDestination{ Destination: releasekit.DeliveryDestination{
Forge: releasekit.ForgeGitea,
BaseURL: "https://gitea.example", BaseURL: "https://gitea.example",
Owner: "example", Owner: "example",
Repository: "example", Repository: "example",
@@ -202,11 +301,15 @@ identify an annotated tag object or a commit. The template requires the resolved
commits to match, checks out that commit detached, and confirms the source tree commits to match, checks out that commit detached, and confirms the source tree
is clean. It then copies the tagged `go.mod` and any `go.sum` to a temporary is clean. It then copies the tagged `go.mod` and any `go.sum` to a temporary
directory outside the checkout. `go list -m` confirms that the module selects directory outside the checkout. `go list -m` confirms that the module selects
ReleaseKit; Go uses ReleaseKit. The template selects the host Go target before preparing and running
an alternate `-modfile` to prepare dependencies and build the selected the CLI. The template adds its CLI tool declaration to that temporary copy
`cmd/releasekit` package without changing the tagged module files. The template and prepares tool dependencies with `go list -deps`. It then uses
invokes that executable with `CI_WORKSPACE`, the resolved event commit, and `go tool -modfile=... go.maximumdirect.net/releasekit/cmd/releasekit` to build,
`CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable. cache, and run the selected tool with `CI_WORKSPACE`, the resolved event commit,
and `CI_COMMIT_TAG`. The tagged module files stay unchanged, including for
consumers with an ordinary package
dependency. A cleanup trap removes the temporary metadata; Go manages the
cached executable. The command preserves the tool's exit status.
Tool bootstrap and application artifact preparation are separate. The bootstrap Tool bootstrap and application artifact preparation are separate. The bootstrap
resolves and builds ReleaseKit from the tagged consumer's module configuration. resolves and builds ReleaseKit from the tagged consumer's module configuration.
@@ -243,10 +346,21 @@ and application artifact compilation retain their separate environments.
The normal Go module and build caches are sufficient. Cache mounts may be added The normal Go module and build caches are sufficient. Cache mounts may be added
as deployment configuration when they help the runner; they are not needed by as deployment configuration when they help the runner; they are not needed by
the template. A separately installed executable can be installed with the template. For a standalone installation, replace `PIN` with the desired
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run version and [select the Go host target](adoption.md#select-the-go-host-target)
with the same arguments. With the event object available in the CI checkout, for `go install`:
resolve it to its source commit before invocation:
```sh
(
releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
go install go.maximumdirect.net/releasekit/cmd/releasekit@PIN
)
```
With the event object available in the CI checkout, resolve it to its source
commit before invoking the installed executable:
```sh ```sh
expected_commit=$(git -C "$CI_WORKSPACE" rev-parse --verify "${CI_COMMIT_SHA}^{commit}") expected_commit=$(git -C "$CI_WORKSPACE" rev-parse --verify "${CI_COMMIT_SHA}^{commit}")
@@ -286,7 +400,9 @@ describes these checks.
To isolate a public ReleaseKit download from application settings and the To isolate a public ReleaseKit download from application settings and the
existing module cache, run the following with a compatible local Go toolchain. existing module cache, run the following with a compatible local Go toolchain.
Replace `v0.2.0` with the affected version. This diagnostic accesses the public Replace `v0.5.0` with the affected vanity-path version. For an earlier release,
use its original `gitea.maximumdirect.net/eric/ReleaseKit` module path instead.
This diagnostic accesses the public
Go proxy and checksum database and retains its temporary directory for inspection. Go proxy and checksum database and retains its temporary directory for inspection.
```sh ```sh
@@ -298,7 +414,7 @@ Go proxy and checksum database and retains its temporary directory for inspectio
GOPRIVATE= GONOPROXY= GONOSUMDB= \ GOPRIVATE= GONOPROXY= GONOSUMDB= \
GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \ GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \
GOMODCACHE="$checksum_dir/modules" \ GOMODCACHE="$checksum_dir/modules" \
go mod download -json gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0 go mod download -json go.maximumdirect.net/releasekit@v0.5.0
) )
``` ```

View File

@@ -31,6 +31,13 @@ physical location. `Version` remains the stable semantic version. The note is
the note path but is removed from the tag prefix only when the module path ends the note path but is removed from the tag prefix only when the module path ends
in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared
`ModulePath`, complete `Tag`, and existing commit and tag-object evidence. `ModulePath`, complete `Tag`, and existing commit and tag-object evidence.
For general source publication, set `Source` as described in the
[candidate check guide](check.md#local-candidate-check). `PublicationResult`
also reports the selected source directory and capabilities.
Publication does not require a hosted delivery rehearsal. The optional
[rehearsal](rehearsal.md) uses separately recorded temporary resources and does
not change the production tag's completion or immutability rules.
The optional `ValidationSpec.SharedFiles` selects additional committed files The optional `ValidationSpec.SharedFiles` selects additional committed files
for enabled file checks. Its nil and empty-slice behavior is described in the for enabled file checks. Its nil and empty-slice behavior is described in the
@@ -44,7 +51,7 @@ when fetch and push URLs differ. A mismatch fails preflight before Go validation
callbacks, or tag creation; detect it with callbacks, or tag creation; detect it with
`errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this `errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this
publication-only field. publication-only field.
It runs one `go test -mod=readonly -count=1 ./...` suite with the available When Go is selected, it runs one `go test -mod=readonly -count=1 ./...` suite with the available
compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with
`-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after `-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after
successful tests, with test-time vet disabled for that suite. The zero values successful tests, with test-time vet disabled for that suite. The zero values
@@ -114,9 +121,81 @@ candidate and remote guards, creates an annotated tag for the captured commit,
and pushes only that tag object. and pushes only that tag object.
A successful result means Git confirmed the push or an exact authoritative tag A successful result means Git confirmed the push or an exact authoritative tag
query confirmed it after a push error. The local tag is retained after a failed query confirmed it after a push error. A failed inspection after local tag
push. `PublicationState` distinguishes a known failure, conflict, confirmed creation can leave the tag ref even when its object ID is unavailable; when
publication, and unresolved outcome. Resolve an unknown result against the the ID was established it remains in `TagObject`. The local tag is retained
captured endpoint before retrying; see the [maintainer procedure](../release.md) after a failed push. `PublicationState` distinguishes a known failure, conflict,
for the recovery steps. The [CLI contract](../cli.md) documents command output confirmed publication, and unresolved outcome. Resolve an unknown result
and exit statuses. against the captured endpoint before retrying; see the [maintainer procedure](../release.md)
for the recovery steps. The result's endpoint is the exact URL and can contain
credentials; handle it accordingly. The [CLI contract](../cli.md) documents
command output and exit statuses.
## Retain and reconcile publication evidence
`Publish` automatically attempts to save one private record for each invocation.
The default store is under the repository's Git common directory, so linked
worktrees share it. `ReleaseRequest.PublicationRecordDir` can override the
directory; relative overrides resolve from the source repository root. The CLI
equivalent is `publish --record-dir DIR`. ReleaseKit creates its owned storage
directories privately and creates record files with owner-only permissions;
existing directory permissions are left as they are. The caller owns storage
retention and removal.
The CLI prepares a recovery entry point when a failed publication has a saved
record. Registered-tool consumers use their selected module's Go tool directly.
Command preparation uses a separate bounded context after publication failure,
including cancellation. A module-preparation warning can accompany a persistent
native executable fallback; the saved record and publication result retain their
original meaning.
For API-only consumers, ReleaseKit retains private bootstrap module and checksum files
under `<Git common directory>/releasekit/publication-recovery/`, with private
directory and file permissions. These files add the CLI tool declaration and
prepare its module graph without changing consumer source. The bootstrap has
its own module root, so tool resolution is independent of consumer vendoring;
local replacements retain their original source locations. These files survive
a launcher's temporary module-file cleanup. Registered-tool commands run from
the selected module; API-only commands run from the private bootstrap root.
Retain the source checkout and private recovery files while the entry point is
needed. Remove the private recovery directories when
their recovery value expires. Another supported CLI can read the saved record
independently of these launch files.
The saved endpoint is retained exactly for later observation and may include
credentials. Treat records, `PublicationEvidence`, and `PublicationResult` as
sensitive. Store overrides in a location with suitable access controls, avoid
printing raw endpoint values, and remove records when their recovery value has
expired. Diagnostic errors and CLI output apply credential redaction; the
private record and typed evidence preserve the raw endpoint.
Recording failure is reported in `PublicationResult.RecordError`, separately
from `Publish`'s return error and publication state. A successful push remains
successful if storage fails, but the saved handoff is unavailable. Callers can
still pass `result.Evidence` directly to `ReconcilePublication` when it contains
the required identity. For example:
```go
func observe(ctx context.Context, result releasekit.PublicationResult) (releasekit.PublicationReconciliationResult, error) {
return releasekit.ReconcilePublication(ctx, result.Evidence)
}
```
The evidence is populated as publication identity becomes available, including
partial evidence on some earlier failures. An abrupt process termination before
the save point can leave no record; removed storage also removes the handoff.
Records from older attempts may lack the tag object, endpoint, or other identity
needed for a conclusive observation.
Use `LoadPublicationEvidence(path)` to read one explicit record,
`ListPublicationAttempts(ctx, request)` to discover readable records and
per-record diagnostics in a local directory, or `ReconcilePublication(ctx,
evidence)` to observe a selected endpoint. Listing does not query remotes, and
neither listing nor reconciliation changes saved records. Recovery does not
infer the attempt from current HEAD, local tags, module files, or profiles.
`ReconcilePublication` returns a nil error for a completed `published`,
`not_published`, or `conflict` observation; unresolved `unknown` results include
a typed error that retains the underlying cause. See the
[GoDoc](../../recovery.go) for the exported fields and error kinds, the
[CLI guide](../cli.md) for command statuses, and the
[record format guide](../integrations/publication-records.md) for supported
stored and structured formats.

View File

@@ -0,0 +1,53 @@
# Readiness validation
`releasekit validate` inspects the working profile and source inputs before a
release candidate is ready. It does not run product checks, build, download
dependencies, change the checkout, or write to a remote. It does not require a
version or release note. Its results are optional setup evidence, not a release
gate or proof of later write permission.
```sh
releasekit validate
releasekit validate --context ci --operation delivery --json
releasekit validate --offline --operation publication
```
By default, the command selects publication, configured Go and build work, and
delivery when declared. Repeated `--operation` flags select only the named
operations: `publication`, `go`, `build`, `delivery`, and `rehearsal`.
Rehearsal is explicit. The selected `local` or `ci` context controls credential
loading independently of network scope. Online validation reads authoritative
Git `main` from the effective push endpoint and performs hosted delivery
preflight. Offline mode omits those remote reads and identifies the omitted
checks. Local publication readiness also checks Git's configured tagger
identity. Native Git and SSH authentication remain in use; no conventional
private-key filename is required.
Rehearsal readiness also checks read access to the configured Woodpecker
repository using the separate local Woodpecker token file. Offline validation
checks the local settings but leaves that remote observation unchecked; it
does not read or register CI job secrets.
To require a specific local input, list it in `readiness.required_files` in the
profile. Paths are literal repository-root-relative or absolute filenames. This
checks readability, not Git authentication. `--assets DIR` selects an existing
build receipt and artifacts for identity and digest checks; delivery must be
selected. Build outputs are otherwise not required to exist. Dependency-cache
completeness and actual build execution remain unchecked.
Go package patterns and external package inputs report resolution as unchecked;
literal local package directories retain their input checks.
JSON output is one document with `schema_version: 1`, `command: "validate"`,
the working-input scope, selected operations, context, safe credential sources,
destinations, and ordered check results. Check statuses are `passed`, `failed`,
`skipped`, and `unchecked`; reasons distinguish configuration, input, remote,
dependency, offline, and unexecuted evidence. A selected failed or incomplete
check makes the command unsuccessful; an offline omission alone does not. Status
2 reports usage, configuration, or required-input errors; status 1 reports
other failures, cancellation, or output failure. Actual CI secret injection
requires a job or rehearsal result and is not established by local readiness.
See the [rehearsal guide](rehearsal.md) for that separate live diagnostic.
The Go facade's `Validate` accepts explicit selections and tokens and returns a
`ValidationReport` with a `ReadinessError` when selected checks fail. The CLI
loads its own credentials; the library does not load ambient tokens.

View File

@@ -0,0 +1,76 @@
# Rehearse tagged delivery
A rehearsal exercises the real tag-triggered Woodpecker delivery workflow before
choosing a production version. It creates a temporary diagnostic tag and page,
verifies the job's page and any binary and checksum contents, and removes only
recorded diagnostic resources after CI is quiescent. Routine `publish` remains
complete when its production source tag is confirmed; rehearsal is an optional,
explicit diagnostic.
Configure `delivery` with both local and CI credential selections. Configure
`rehearsal.woodpecker` with the CI server URL, its numeric repository ID, the
exact workflow and delivery step names, and a separate local Woodpecker API
token file. The `rehearsal.selector` defaults to `root`; multi-product
repositories select the corresponding maintained mapping row. The
[configuration reference](../config.md) defines the fields. The
[root workflow](../../examples/woodpecker/tag-delivery.yml),
[self-bootstrap workflow](../../examples/woodpecker/releasekit-source-delivery.yml),
[multi-product example](../../examples/multi-module/README.md), and
[source-only example](../../examples/source-only/README.md) show the dispatch
and CI secret injection.
The local forge credential must be able to read and delete the diagnostic
release and its assets, the CI delivery credential must be able to create them,
and native Git authentication must permit creating and deleting the diagnostic tag. The separate Woodpecker credential needs read
access to the repository, pipelines, workflows, steps, and logs. CI must inject
the configured delivery token into the actual tagged job; local readiness
cannot establish that injection. Keep local token files private and ignored by
Git. Do not register them as CI secrets through ReleaseKit.
```sh
releasekit validate --operation rehearsal
releasekit test --json
releasekit test --ref HEAD~1 --timeout 45m
```
The selected profile must be committed in the checkout at the captured commit.
The branch, index, and worktree need not be a final release candidate and are
not changed by capture. The diagnostic version and tag identify a random
attempt; neither is a production release identifier. The actual CI job builds
and delivers through the selected profile, then reads back its page and declared
assets while build output remains available. A page-only profile generates no
binary artifacts.
The output separates workflow execution, build, hosted verification, and
cleanup. It records a private attempt under the Git common directory, or in an
explicit ignored/private `--record-dir`. If observation fails or cleanup cannot
establish quiescence, retain the exact printed record and use:
```sh
releasekit test-resume --record /path/to/attempt.json
releasekit test-cleanup --record /path/to/attempt.json
```
Recovery reads the committed profile selected by the record, using current local
credential files. `--token-file` and `--woodpecker-token-file` override those
paths. The library's `Rehearse`, `ResumeRehearsal`, and `CleanupRehearsal`
accept credentials explicitly and do not load ambient tokens. Their result and
error may both contain useful information. `RehearsalTimeout` values use the
same nanosecond units as `time.Duration`; a zero observation timeout waits for
context cancellation, and a zero cleanup timeout selects the two-minute default.
The facade's `DeliverRehearsal` operation owns diagnostic delivery inside the
prepared CI checkout: tag verification, selected backend construction,
credential preflight, dependency preparation, shared delivery, and content
read-back. Callers supply explicit credentials and selections from the captured
profile. The CLI owns profile decoding and result framing; the operation returns
partial delivery outcomes and safe phase diagnostics.
Cleanup rechecks every matching pipeline and the recorded tag and page identity.
An active or unobservable job, missing pipeline evidence, or a conflicting
resource leaves cleanup pending or reports a conflict. Cancellation stops local
observation and does not cancel the CI job. A fresh bounded cleanup context may
still clean resources when quiescence is established. CI history, notifications,
webhooks, and later operator-initiated reruns are outside the cleanup result.
See the [record and result formats](../integrations/rehearsal-records.md) for
transport and retained evidence.

View File

@@ -4,7 +4,7 @@ Applications can read their embedded version through the public `buildinfo`
package: package:
```go ```go
import "gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" import "go.maximumdirect.net/releasekit/buildinfo"
version := buildinfo.Version() version := buildinfo.Version()
``` ```

View File

@@ -0,0 +1,22 @@
# Build receipts
The CLI writes a private `.releasekit-build.json` receipt after a successful
nonempty build. It lets a later `deliver --assets` invocation bind the retained
files to the selected source and release identity. The
[delivery guide](../consumers/delivery.md) describes the workflow and ownership
of those files.
The current receipt uses `schema_version: 2`. Its identity includes the
repository and physical source directories, repository-relative source scope,
Go capability and module identity, publication mode, version format and prefix,
identity kind, exact version, full tag, production note path when applicable,
and captured commit. It also records source verification, compiler and build
settings, output directory, targets, artifact paths, filenames, and SHA-256
digests. A diagnostic identity has a diagnostic version and tag rather than a
production note path.
Readers accept additive unknown fields in schema 2. Older or unsupported
schemas require a new build and receipt. Loading a receipt checks its structure
and declared identity; delivery verifies the selected source and actual artifact
bytes before making hosted writes. A receipt is local coordination evidence, not
a source attestation.

View File

@@ -1,9 +1,10 @@
# Gitea release pages # Gitea release pages
ReleaseKit's public `Deliver` operation and `deliver` command verify tagged ReleaseKit's public `Deliver` operation and `deliver` command select Gitea
source, find or create the selected module's release page, inspect existing assets, and explicitly, verify tagged source, find or create the selected module's release
upload missing assets through the internal Gitea client. Page-only and page, inspect existing assets, and upload missing assets. Shared delivery code
binary-producing profiles use the same delivery path. The owns content comparison and recovery; the Gitea adapter owns the HTTP protocol.
Page-only and binary-producing profiles use the same delivery path. The
[consumer delivery guide](../consumers/delivery.md) covers caller workflows; [consumer delivery guide](../consumers/delivery.md) covers caller workflows;
this guide describes the Gitea protocol and its failure behavior. this guide describes the Gitea protocol and its failure behavior.
@@ -13,6 +14,23 @@ the `Authorization: token …` request header and is not included in errors or
results. The base URL must use HTTP or HTTPS and cannot contain URL credentials, results. The base URL must use HTTP or HTTPS and cannot contain URL credentials,
a query, or a fragment. a query, or a fragment.
Before a build or full local artifact verification, Gitea preflight makes two
authenticated, read-only repository requests: `GET /api/v1/repos/{owner}/{repo}`
resolves the repository, then `GET /api/v1/repositories/{id}` confirms access
through the authenticated repository route. The response identity must match
the configured owner and repository. This check also works without a checkout
or a published tag and makes no release or asset writes.
A 401 response identifies a rejected credential. A 403 identifies denied
access but does not establish that the credential is invalid. A 404 can mean a
missing repository or access hidden by the service. Network failures, service
errors, and malformed responses that prevent verification are reported as
unavailable. Repository `permissions.push` describes Git code-push access; it
does not establish permission to create release pages or upload assets. Gitea
does not expose enough evidence through this probe to verify those write scopes,
so they remain unverified and later writes remain authoritative. Preflight does
not request unrelated user scopes or create a test release or asset.
The selected module derives a complete tag from its semantic version, declared The selected module derives a complete tag from its semantic version, declared
module path, and physical repository-relative directory. For example, version module path, and physical repository-relative directory. For example, version
`v1.2.3` in `integrations/ckconfig` uses `v1.2.3` in `integrations/ckconfig` uses
@@ -22,39 +40,49 @@ declared module stored at `integrations/core` derives the same tag. ReleaseKit
removes a final physical `/v2` directory from the tag prefix only when the removes a final physical `/v2` directory from the tag prefix only when the
module declaration has that `/v2` suffix. A module-local note stays at module declaration has that `/v2` suffix. A module-local note stays at
`<module>/docs/releases/<version>.md`, including a physical `/v2` directory. `<module>/docs/releases/<version>.md`, including a physical `/v2` directory.
General source releases instead derive the tag from their selected source
directory or explicit product prefix and the selected identifier; the source
note remains under `<source>/docs/releases/`. See the
[configuration reference](../config.md) for selection and version formats.
The default shared validation convention uses repository-root `COPYRIGHT`, The default shared validation convention uses repository-root `COPYRIGHT`,
`LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license `LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license
layout and release-note links. Use the complete derived tag as the immutable layout and release-note links. Use the complete derived tag as the immutable
source ref and the actual repository-relative file paths in those links. source ref and the actual repository-relative file paths in those links.
Shared-file selection controls validation inputs; delivery preserves the Shared-file selection controls validation inputs; delivery preserves the
committed note and its footer links. The client first reads committed note and its footer links. After successful preflight, the Gitea
adapter reads
`/api/v1/repos/{owner}/{repo}/tags/{tag}` and requires the hosted tag's commit `/api/v1/repos/{owner}/{repo}/tags/{tag}` and requires the hosted tag's commit
SHA to equal the captured source commit. It then reads SHA to equal the captured source commit. It then reads
`/api/v1/repos/{owner}/{repo}/releases/tags/{tag}`. A matching existing page `/api/v1/repos/{owner}/{repo}/releases/tags/{tag}`. A matching existing page
must have that tag, the complete committed release note as its body, and stable is accepted by shared delivery policy only when it has that tag, the complete
committed release note as its body, and stable
non-draft state. Its existing title is retained. ReleaseKit does not edit a non-draft state. Its existing title is retained. ReleaseKit does not edit a
conflicting page. Slash-containing tags are escaped as one URL path segment. conflicting page. Slash-containing tags are escaped as one URL path segment.
Page-only delivery does not require a release ID in this lookup response. Asset
operations require a positive release ID; a missing or nonpositive ID is
reported as a malformed service observation before an asset request is made.
If the page is absent, the client posts to `/api/v1/repos/{owner}/{repo}/releases` If the page is absent, the adapter posts to
with the selected full tag and commit, the release note's H1 as title, the complete `/api/v1/repos/{owner}/{repo}/releases` with the selected full tag and commit,
note as body, and draft and prerelease disabled. A create conflict, interrupted the release note's H1 as title, the complete note as body, and draft and
response, or malformed create response (including inconsistent decoded fields) prerelease disabled. A create conflict, interrupted response, or malformed
triggers one lookup. An exact page found create response (including inconsistent decoded fields) triggers one lookup by
there confirms the existing content; a differing page is a conflict. If that the shared workflow. An exact page found there confirms the existing content;
lookup cannot determine the result after a possibly successful write, the a differing page is a conflict. If that lookup cannot determine the result
client returns an unknown outcome. Other HTTP failures retain their structured after a possibly successful write, delivery returns an unknown outcome. Other
failure kind and status code. A recovered create retains its write history; HTTP failures retain their structured failure kind and status code. A recovered
a later asset-inspection failure reports partial page progress. create retains its write history; a later asset-inspection failure reports
partial page progress.
For a binary-producing release, the client can build a deterministic For a binary-producing release, shared delivery builds a deterministic
`SHA256SUMS` file from the declared artifact names and SHA-256 digests. Entries `SHA256SUMS` file from the declared artifact names and SHA-256 digests. Entries
are sorted by filename and use the standard two-space separator. A source-only are sorted by filename and use the standard two-space separator. A source-only
release produces no manifest. release produces no manifest.
Asset inspection lists the release attachments, streams each declared existing The adapter lists release attachments and opens their download streams. Shared
file, and compares its SHA-256 digest. It reports each asset as matching, delivery compares each declared existing file by SHA-256 digest and reports it
missing, conflicting, or unverifiable. Same-name attachments with different as matching, missing, conflicting, or unverifiable. Same-name attachments with
bytes are conflicts even when their reported size matches. An existing different bytes are conflicts even when their reported size matches. An existing
`SHA256SUMS` must exactly match the complete expected manifest; a subset or `SHA256SUMS` must exactly match the complete expected manifest; a subset or
different manifest is a conflict. An unreadable attachment is unverifiable, different manifest is a conflict. An unreadable attachment is unverifiable,
not missing. A failed read-only inspection reports `not_attempted`; if this not missing. A failed read-only inspection reports `not_attempted`; if this
@@ -63,12 +91,15 @@ Unknown-write outcomes are reserved for unresolved writes. Unrelated attachments
Attachment downloads and redirects carry the Gitea authorization token only Attachment downloads and redirects carry the Gitea authorization token only
when their scheme, host, and port match the configured service. Cross-origin when their scheme, host, and port match the configured service. Cross-origin
content is downloaded without that token and verified by its digest. content is downloaded without that token and verified by its digest. Downloads
follow at most ten redirects; an additional redirect is unverifiable.
Comparison reads no more than the declared local size plus one byte; shorter
or longer content conflicts, regardless of the server's reported size.
The upload operation accepts only an inspection result without conflicts or Shared delivery uploads only after inspection finds no conflicts or
unverifiable assets. It uploads missing binaries in filename order and then the unverifiable assets. It uploads missing binaries in filename order and then the
missing `SHA256SUMS`, using multipart field `attachment` and the filename query missing `SHA256SUMS`, using the adapter's multipart field `attachment` and
parameter `name`. Matching attachments are retained; unrelated and existing filename query parameter `name`. Matching attachments are retained; unrelated and existing
attachments are never overwritten or deleted. Results use disjoint current attachments are never overwritten or deleted. Results use disjoint current
observations: matching, uploaded, pending, conflicting, and uncertain. An asset observations: matching, uploaded, pending, conflicting, and uncertain. An asset
moved from known missing work to another category is removed from `pending`; moved from known missing work to another category is removed from `pending`;

View File

@@ -0,0 +1,132 @@
# Publication records and recovery output
This guide describes the supported private publication-record envelope and the
versioned JSON documents emitted by the recovery CLI. The
[publication consumer guide](../consumers/publish.md) owns storage placement,
permissions, retention, and sensitive-data handling. The
[CLI reference](../cli.md) owns command behavior, path selection, and exit
statuses; the exported Go contract is documented in [GoDoc](../../recovery.go).
## Private attempt record
Each saved attempt is one complete JSON document with this versioned envelope:
```json
{
"format_version": 3,
"evidence": {
"repository_dir": "/work/project",
"source_dir": "/work/project",
"source_subdir": ".",
"go_enabled": true,
"publication_mode": "go-module",
"version_format": "semver",
"version_prefix": "v",
"identity_kind": "production",
"note_path": "docs/releases/v1.2.3.md",
"module_dir": "/work/project",
"module_path": "example.com/project",
"version": "v1.2.3",
"tag": "v1.2.3",
"candidate_commit": "<full Git object ID>",
"tag_object": "<full Git object ID>",
"endpoint": "ssh://git.example/owner/project.git",
"remote": "origin",
"recorded_at": "2026-11-02T12:00:00Z"
}
}
```
The format version is an integer. Evidence fields may be absent when publication
stopped before they were captured; loading preserves that partial evidence and
does not fill fields from the current checkout. Additional fields in a
supported version are ignored. A missing or unsupported version, malformed or
multiple JSON documents, or fields with invalid structural types are reported
as record-format errors. The codec reads versions 1, 2, and 3; no migration from
an unsupported version is performed.
New records use version 3, including source and selection evidence. Legacy
versions 1 and 2 retain only the evidence they captured. Version 2 and version 3
may include an `evidence_bytes` object for non-UTF-8 string values. Each entry
in `evidence_bytes` uses an evidence field
name and a standard base64 string containing its exact bytes. That entry
supplies the field's value when loading; the writer omits its lossy string form
from `evidence`. Invalid known-field types or base64 encodings produce a
record-format error with the available decoding cause. Unknown field names are
ignored. This representation applies
to string evidence fields and preserves the same identity as typed Go evidence.
Older CLIs report an unsupported version for records they cannot read.
The `endpoint` value is stored exactly as captured and may contain credentials.
Private records are sensitive. Do not copy them into public logs or source
control. For their location, permissions, and lifecycle, see the
[publication consumer guide](../consumers/publish.md#retain-and-reconcile-publication-evidence).
## Recovery CLI JSON
After valid command arguments, `--json` emits one JSON document to standard
output for both successful and failed recovery operations. Each document has
`schema_version: 1` and a `command` name. These are CLI presentation documents,
not private attempt records or a Go serialization of public structs.
`reconcile` includes `record_path`, safe `evidence`, and `state` when a record
was read. Available `observed_tag_object` and `observed_commit` fields are
included when present. A `diagnostic` is included for unresolved observation
or record loading failure. Loading failure omits evidence, state, and observed
IDs. Safe evidence may include source, capability, publication, and version
selection fields when those were captured.
`publication-attempts` includes `record_dir`, an `attempts` array with each
`record_path` and safe `evidence`, and a `diagnostics` array. A top-level
`diagnostic` describes enumeration or cancellation failure. Both arrays are
present when empty so consumers can decode the same shape for empty stores.
For example, an unresolved reconciliation can have this shape:
```json
{
"schema_version": 1,
"command": "reconcile",
"record_path": "/private/attempt-abc.json",
"evidence": {
"repository_dir": "/work/project",
"module_path": "example.com/project",
"version": "v1.2.3",
"tag": "v1.2.3",
"candidate_commit": "<full Git object ID>",
"tag_object": "<full Git object ID>",
"endpoint": "ssh://git.example/owner/project.git",
"remote": "origin"
},
"state": "unknown",
"diagnostic": {
"kind": "remote_observation",
"message": "<credential-safe diagnostic>"
}
}
```
A discovery document always contains both arrays, including for an empty store:
```json
{
"schema_version": 1,
"command": "publication-attempts",
"record_dir": "/private/publication-attempts",
"attempts": [],
"diagnostics": []
}
```
CLI evidence uses the private record's snake-case field names. Endpoint strings
in CLI output are credential-redacted; the private record and typed
`PublicationEvidence` retain the exact endpoint. A diagnostic contains `kind`
and safe `message`, with `record_path` and `missing_fields` when applicable.
Raw Go errors and private record contents are not emitted as JSON fields.
Consumers should select attempts by their returned record paths and evidence.
The listing order is deterministic by path, not a recommendation to choose the
first or newest attempt. Unknown fields may be added in later CLI schema
versions; reject unsupported `schema_version` values rather than interpreting
them as version 1. See the [CLI reference](../cli.md#recover-a-saved-publication-attempt-or-discover-local-attempts)
for invocation and status behavior.

View File

@@ -0,0 +1,89 @@
# Rehearsal identity and records
A diagnostic annotated tag carries the exact source and profile identity for a
single rehearsal. Its message begins with `ReleaseKit rehearsal v1`, followed
by a newline and one compact JSON object. `schema_version: 1` identifies the
manifest. Its fields include the attempt ID, selector, captured commit, profile
path and SHA-256, source directory, Go capability and optional module path,
publication and version selection, diagnostic version, and full tag. A
16-byte random attempt ID is represented by 32 lowercase hexadecimal digits;
the tag and injected version include the same ID.
The manifest fields are `schema_version`, `attempt_id`, `selector`, `commit`,
`profile_path`, `profile_sha256`, `source_dir`, `go_enabled`, optional
`module_path`, `publication_mode`, `version_format`, `version_prefix`,
`diagnostic_version`, and `tag`. The diagnostic ref has the form
`releasekit-test/<selector>/<attempt-id>`; the injected version is
`releasekit-test-<attempt-id>`.
The manifest is verified against the actual annotated tag target, the event
commit, the selected dispatch row, the exact committed profile bytes, and the
normalized selection decoded from those bytes. The tag namespace alone is not
proof of ownership or permission to delete anything. A profile is read from the
captured commit rather than the current working tree.
Private attempt records use `format_version: 1` and retain the manifest, Git
endpoint and remote, the explicit `forge` selector and forge/Woodpecker
destinations, planned page and asset identities, tag object, observed resource
IDs, timestamps, and outcomes. They do not store resolved forge or Woodpecker
tokens. Endpoints and paths may themselves contain
sensitive information, so treat records as private. By default they are stored
under the Git common directory in `releasekit/rehearsals/<attempt-id>.json`.
An explicit record-directory override follows the same worktree ignore rules as
publication records. The initial record is created exclusively; updates use a
private temporary file and rename. Records remain available for explicit
recovery and operator retention.
Manifest and record strings that contain non-UTF-8 bytes are omitted in their
lossy JSON form and represented by standard base64 values in `identity_bytes`.
A recognized override supplies the exact bytes on decoding; unknown override
names are ignored. Supported versions tolerate additive unknown fields.
## CI result
After verifying a diagnostic tag, the delivery job emits one line beginning
`RELEASEKIT_REHEARSAL_RESULT_V1 ` and a JSON object. It includes the manifest
identity and exact-byte overrides, delivery scope and outcomes, the observed
page ID, and each verified artifact's filename, size, and SHA-256. A failed job
emits the evidence it has reached; an earlier bootstrap failure can leave no
result. The observer reads complete log lines, accepts identical retransmissions,
and rejects malformed, conflicting, or mismatched evidence without echoing the
raw log. The page and declared assets are read back before managed build output
is removed.
The result uses the manifest fields plus `scope` (`page` or
`page-and-assets`), `build`, `delivery`, `verification`, `page_id`,
`artifacts` entries with `name`, `size`, and `sha256`, and optional safe
`diagnostics`. A successful result requires complete delivery and verification
and a positive page ID. For asset scope it also requires the planned artifacts,
including the checksum manifest.
The start coordinator records tag creation and push intent before dispatch. It
keeps matching pipeline numbers, workflow and step observations, the job result,
and partial outcomes in the selected attempt record. A timeout or cancellation
leaves those observations available for explicit recovery; it does not cancel
the independent CI job or establish that cleanup is safe.
## Cleanup and recovery
Recovery selects one explicit record and uses its captured destinations with
current explicitly supplied credentials. A recorded `push: "not_dispatched"`
means Git supplied definite rejection or failure-before-dispatch evidence;
cleanup removes the owned local tag without requiring CI completion. A started
or uncertain dispatch is
eligible for cleanup only after every matching observed pipeline and relevant
job is terminal and the CI search is checked again. Missing, active, or
unavailable CI evidence leaves cleanup pending. Cleanup verifies the recorded
tag object and page identity, then removes the page and its assets, the remote
tag, and the matching local tag. It records intent before each deletion and
reobserves ambiguous outcomes. A canceled observation does not cancel CI;
cleanup uses an independent bounded context.
A known matching page can be removed when its tag is already confirmed absent.
Adopting a page whose ID was not recorded still requires its tag target to be
verified.
A completed result describes the recorded resources and the CI runs observed
at cleanup time. Later operator-initiated reruns, CI history, notifications, and
webhook effects are outside that result. Records remain available for operator
retention.

View File

@@ -8,21 +8,42 @@ Standalone and delivery builds create their own owners. The package uses
`internal/process` for cancellation, the working directory, output, and wrapped `internal/process` for cancellation, the working directory, output, and wrapped
errors. errors.
For CLI publication recovery, the package selects a registered module tool or
prepares a durable private module root for an API-only consumer. Go's module
graph query includes transitive dependencies; preparation retains module
requirements, versioned replacements, and checksums. Local replacements resolve
against their original module directory before relocation. Each relocation
updates the directive's destination and retains its path and version selector.
The original main module remains a local replacement, including when releasing
ReleaseKit itself.
The private root provides tool resolution independently of consumer vendoring.
API-only preparation discovers the host target for dependency inspection. The
returned invocation carries its directory and tool arguments; the CLI's later
shell command selects the host again when it runs.
The CLI formats the later invocation using a separate bounded context after
publication failure. It falls back to a persistent native executable when module
selection is unavailable or preparation fails, and excludes recognized temporary
Go-work executables from that fallback. The
[publication consumer guide](../consumers/publish.md#retain-and-reconcile-publication-evidence)
owns recovery-file placement and retention.
## Command output ownership ## Command output ownership
`Tool.Run` executes a status-only command. It forwards combined stdout and `Tool.Run` executes a status-only command. It forwards combined stdout and
stderr to the optional writer while the child runs, then releases its capture stderr to the optional writer while the child runs, retaining only the last
on success. Failures include the captured diagnostic text and preserve the 1,048,576 bytes for failure diagnostics. A truncation notice identifies omitted
underlying process or forwarding error. earlier bytes. Successful calls release their capture; failures preserve the
underlying process or forwarding error. Dependency preparation uses the same
bounded diagnostic capture.
`Tool.Output` returns combined stdout and stderr for commands whose output is `Tool.Output` returns combined stdout and stderr for commands whose output is
needed by the caller, such as compiler identification. After the child stops, needed by the caller, such as compiler identification. After the child stops,
the capture's backing bytes transfer to the caller without a second copy. A the capture's backing bytes transfer to the caller without a second copy. A
failed output command returns both those bytes and an error containing the failed output command returns both those bytes and an error containing the
diagnostic text. The capture remains in memory for the duration of the child; diagnostic text. The capture remains in memory for the duration of the child;
the component benchmark compares one 8 MiB write with the same output in the component benchmark compares full and bounded capture for modest output,
32 KiB writes, forwarding to `io.Discard`. Smaller writes incur buffer-growth one 8 MiB write, and 8 MiB in 32 KiB writes, forwarding to `io.Discard`.
allocations. The [output benchmark](../../internal/gotool/performance_test.go) The [output benchmark](../../internal/gotool/performance_test.go)
measures total allocated bytes per operation, excluding subprocess overhead and measures total allocated bytes per operation, excluding subprocess overhead and
diagnostic strings. These totals count all allocations, including superseded diagnostic strings. These totals count all allocations, including superseded
buffers. The returned slice retains the final buffer holding the complete output. buffers. The returned slice retains the final buffer holding the complete output.
@@ -33,8 +54,10 @@ coexist. Disk-backed diagnostics could reduce large failure peaks, but add file
lifecycle and cleanup work and remain a follow-up option. lifecycle and cleanup work and remain a follow-up option.
Dependency preparation uses a separate command environment so proxy, private Dependency preparation uses a separate command environment so proxy, private
module, checksum, and cache settings remain available. Its completed capture module, checksum, cache, and other effective settings remain available. Its
uses the same ownership transfer when formatting a failure. `go mod download -modfile=` command overrides an alternate module file selected
through `GOFLAGS`, preserving ordinary module discovery. Its bounded capture
is formatted into the error on failure.
## Configuration discovery ## Configuration discovery

View File

@@ -3,54 +3,66 @@
Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports
two Go facades and a command-line interface: two Go facades and a command-line interface:
- The root `releasekit` package is the orchestration facade. `Check` validates - The root `releasekit` package is the orchestration facade. `Validate` inspects
working setup and read-only access, `Check` validates
one local candidate, `Publish` validates and publishes its exact annotated one local candidate, `Publish` validates and publishes its exact annotated
source tag, `Build` compiles selected application targets, and `Deliver` source tag, `Build` compiles selected application targets, and `Deliver`
delivers a tagged note page and any declared assets. `PrepareTaggedCheckout` delivers a tagged note page and any declared assets. `Rehearse`,
`ResumeRehearsal`, and `CleanupRehearsal` coordinate explicitly recorded
temporary diagnostics. `PrepareTaggedCheckout`
and `PrepareBuildDependencies` provide explicit local CI preparation. and `PrepareBuildDependencies` provide explicit local CI preparation.
- `buildinfo` is the small runtime facade. `Version` reports the injected - `buildinfo` is the small runtime facade. `Version` reports the injected
application version, the main-module version when available, or `dev`. application version, the main-module version when available, or `dev`.
- `cmd/releasekit` is the executable interface. Its `version`, `check`, - `cmd/releasekit` is the executable interface. Its `version`, `validate`, `check`,
`publish`, `build`, `deliver`, and `ci-deliver` commands adapt profiles and `publish`, `reconcile`, `publication-attempts`, `build`, `deliver`,
command output to the supported library operations. `ci-deliver`, `test`, `test-resume`, and `test-cleanup` commands adapt
profiles and command output to the supported library operations.
See the [CLI contract](../cli.md), [configuration reference](../config.md), See the [CLI contract](../cli.md), [configuration reference](../config.md),
[candidate check guide](../consumers/check.md), [candidate check guide](../consumers/check.md),
[source publication guide](../consumers/publish.md), [source publication guide](../consumers/publish.md),
[publication record format](../integrations/publication-records.md),
[build guide](../consumers/build.md), [build guide](../consumers/build.md),
[delivery guide](../consumers/delivery.md), and [delivery guide](../consumers/delivery.md),
[readiness guide](../consumers/readiness.md),
[rehearsal guide](../consumers/rehearsal.md), and
[runtime version guide](../consumers/runtime-version.md) for task-oriented use. [runtime version guide](../consumers/runtime-version.md) for task-oriented use.
Go declarations and GoDoc remain the owners of exact exported contracts. Go declarations and GoDoc remain the owners of exact exported contracts.
## Module and dependencies ## Module and dependencies
The module is `gitea.maximumdirect.net/eric/ReleaseKit`, with Go language The module is `go.maximumdirect.net/releasekit`, with Go language
version `1.26.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal version `1.27.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
validation; public facades do not expose either dependency. `go list ./...` validation; public facades do not expose either dependency. `go list ./...`
reports these implemented packages: reports these implemented packages:
| Package | Responsibility | | Package | Responsibility |
| --- | --- | | --- | --- |
| `releasekit` | Public orchestration facade and consumer-owned request/result types. | | `releasekit` | Public orchestration facade and facade-owned request/result types. |
| `buildinfo` | Public runtime version accessor. | | `buildinfo` | Public runtime version accessor. |
| `cmd/releasekit` | Executable entry point, command routing, output, and exit status. | | `cmd/releasekit` | Executable entry point, command routing, output, and exit status. |
| `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. | | `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. |
| `internal/apicheck` | Compiled-export and import-boundary checks run during development. | | `internal/apicheck` | Compiled-export and import-boundary checks run during development. |
| `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. | | `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. |
| `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. | | `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. |
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. | | `internal/candidate` | Release identifier and note validation, repository-state checks, candidate capture, and post-validation checks. |
| `internal/delivery` | Captured-commit module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, structural artifact declaration, manifest assembly, one local digest-and-size preflight before hosted requests, and delivery coordination. | | `internal/delivery` | Read-only backend preflight, captured-commit source and optional module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, artifact declaration, manifest assembly, shared page and asset policy, streamed comparisons, write recovery, and delivery outcomes. |
| `internal/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. |
| `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. | | `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
| `internal/gitea` | Gitea API transport, full-tag hosted release pages, asset inspection, manifests, and uploads. | | `internal/gitea` | Gitea destination rules, authenticated repository preflight, HTTP operations and codecs, opaque handle interpretation, response validation, redirects, multipart streaming, and protocol-to-neutral failure conversion. |
| `internal/gotool` | Operation-local Go configuration discovery and reuse, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). | | `internal/gotool` | Operation-local Go configuration discovery and reuse, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
| `internal/tempdir` | Disposable system temporary storage outside source worktrees. | | `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
| `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. | | `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. |
| `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. | | `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. |
| `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. | | `internal/readiness` | Working/committed input inspection and read-only setup observations for explicitly selected capabilities. |
| `internal/recordstore` | Shared private-record location and worktree safety checks. |
| `internal/rehearsal` | Diagnostic tag manifests, private attempt evidence, dispatch, and exact CI job observation for rehearsal recovery. |
| `internal/releaseidentity` | Committed and working source and optional Go module selection, declaration reading, and production/diagnostic tag and note identity. |
| `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. | | `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, and recovery state. | | `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. |
| `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. | | `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. |
| `internal/versioncontract` | Shared stable-version rules and linker-symbol identity. | | `internal/versioncontract` | Shared SemVer and calendar identifier rules and linker-symbol identity. |
| `internal/woodpecker` | Authenticated read-only CI repository, pipeline, workflow, step, and streamed log observation. |
The `buildinfo` facade depends only on its small runtime implementation. The The `buildinfo` facade depends only on its small runtime implementation. The
root facade forwards to internal implementation packages. The CLI adapter is root facade forwards to internal implementation packages. The CLI adapter is
@@ -74,11 +86,28 @@ it does not consult neighboring files or traverse submodule checkouts.
See the [shared validation guide](validation.md) for checker, Go command, and See the [shared validation guide](validation.md) for checker, Go command, and
candidate-file integration mechanics. candidate-file integration mechanics.
Delivery verifies all local binary sizes and digests before hosted requests. Publication records and recovery follow a separate path from candidate
Its Gitea upload path reuses that verification and streams missing files once validation. `internal/publish` captures and saves attempt evidence before the
for transport. Independent calls to the internal client's `UploadMissing` tag push, lists local records, and observes explicitly selected evidence through
verify missing local files before writing. Both paths share remote inspection, `internal/git`; the root facade owns the reusable Go evidence and result types.
conflict handling, and reconciliation. The CLI's `reconcile` and `publication-attempts` commands load, present, and
select records without loading a profile or choosing an attempt automatically.
These operations do not rerun candidate checks or hosted delivery and do not
change local or remote state. The [publication consumer guide](../consumers/publish.md)
owns storage and API use; the [record format guide](../integrations/publication-records.md)
owns the private and CLI JSON formats; the [CLI contract](../cli.md) owns command
semantics and statuses.
The root facade selects the backend explicitly and passes a configured
`internal/forge.Backend` into `internal/delivery`. Delivery performs cheap
request and source checks, then read-only backend preflight before managed
builds or full local artifact verification. Artifact size and digest
verification completes before hosted writes and is reused for upload streams.
Shared delivery code owns release-page matching and creation recovery, remote
asset comparison, upload sequencing, and partial or uncertain outcomes.
`internal/gitea` implements only the Gitea protocol operations behind the
neutral contract. `internal/artifact` and `internal/forge` do not depend on the
adapter.
## Capability owners and behavioral evidence ## Capability owners and behavioral evidence
@@ -88,19 +117,21 @@ not a separate release matrix:
| Capability | Implementation owner | Existing evidence | | Capability | Implementation owner | Existing evidence |
| --- | --- | --- | | --- | --- | --- |
| Runtime version lookup and injected application version | `buildinfo`, `internal/runtimeinfo`, `internal/versioncontract`, `internal/build` | `TestVersionInConsumerExecutable`, `TestVersion` | | Runtime version lookup and injected application version | `buildinfo`, `internal/runtimeinfo`, `internal/versioncontract`, `internal/build` | `TestVersionInConsumerExecutable`, `TestVersion` |
| Candidate capture, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithSelectedRaceSetting`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` | | Candidate capture, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithGoValidationSettings`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` |
| Committed-file validation: formatting, workspace files, local replacements, and file size | `internal/validation`, `internal/candidate`, `releasekit.Check`, `releasekit.Publish`, CLI profile conversion | `TestCheckGoFormatUsesCapturedRegularGoBlobs`, `TestCheckWorkspaceFilesReportsCommittedBlobNames`, `TestCheckLocalReplacementsParsesCommittedModuleDeclarations`, `TestCheckLocalReplacementsFollowsCommittedModuleSymlinks`, `TestCheckFileSizeUsesStrictLimitsAndDefault`, `TestCheckFileSizeAppliesLiteralPathExclusions`, `TestCheckFileSizeUsesCommittedBlobSizes`, `TestCheckFileSizeUsesOnlyCandidateFilesIndividually` | | Committed-file validation: formatting, workspace files, local replacements, and file size | `internal/validation`, `internal/candidate`, `releasekit.Check`, `releasekit.Publish`, CLI profile conversion | `TestCheckGoFormatUsesCapturedRegularGoBlobs`, `TestCheckWorkspaceFilesReportsCommittedBlobNames`, `TestCheckLocalReplacementsParsesCommittedModuleDeclarations`, `TestCheckLocalReplacementsFollowsCommittedModuleSymlinks`, `TestCheckFileSizeUsesStrictLimitsAndDefault`, `TestCheckFileSizeAppliesLiteralPathExclusions`, `TestCheckFileSizeUsesCommittedBlobSizes`, `TestCheckFileSizeUsesOnlyCandidateFilesIndividually` |
| Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownCacheKeepsParsedDocumentsPerCandidatePath`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` | | Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownDocumentsParseIdenticalAndDistinctBlobs`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` |
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestOwnerReusesSettingsUntilInheritedEnvironmentChanges`, `TestOwnerRefreshesWhenPersistentSettingsChange`, `TestCheckSharesGoDiscoveryWithAfterValidateCallback`, `TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree`, `TestRunValidatesOnlyTheSelectedModule`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` | | Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestOwnerReusesSettingsUntilInheritedEnvironmentChanges`, `TestOwnerRefreshesWhenPersistentSettingsChange`, `TestCheckSharesGoDiscoveryWithAfterValidateCallback`, `TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree`, `TestRunValidatesOnlyTheSelectedModule`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
| Batched local Git blob reads | `internal/git`, `internal/process` | `TestBlobReaderReadsLooseAndPackedObjects`, `TestBlobReaderMissingObjectKeepsBatchSessionUsable`, `TestCandidateObjectReadsStayLocalInPartialClones` | | Batched local Git blob reads | `internal/git`, `internal/process` | `TestBlobReaderReadsLooseAndPackedObjects`, `TestBlobReaderMissingObjectKeepsBatchSessionUsable`, `TestCandidateObjectReadsStayLocalInPartialClones` |
| Piped child-process exchanges and cancellation cleanup | `internal/process` | `TestStartPipedExchangesBeforeInputEOFAndPreservesSettings`, `TestStartPipedCancellationAfterReadinessReapsChild`, `TestStartPipedPreservesNonzeroExit` | | Piped child-process exchanges and cancellation cleanup | `internal/process` | `TestStartPipedExchangesBeforeInputEOFAndPreservesSettings`, `TestStartPipedCancellationAfterReadinessReapsChild`, `TestStartPipedPreservesNonzeroExit` |
| Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishRejectsUnexpectedPushURLBeforeValidation`, `TestPublishComparesExpectedURLWithResolvedInsteadOfDestination`, `TestPublishExpectedPushURLUsesPushURLWhenFetchAndPushDiffer`, `TestCheckIgnoresExpectedPushURL`, `TestResolveUsesPushURLAndQueriesWithoutMutation` | | Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishRejectsUnexpectedPushURLBeforeValidation`, `TestPublishComparesExpectedURLWithResolvedInsteadOfDestination`, `TestPublishExpectedPushURLUsesPushURLWhenFetchAndPushDiffer`, `TestCheckIgnoresExpectedPushURL`, `TestResolveUsesPushURLAndQueriesWithoutMutation` |
| Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` | | Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` |
| Saved attempt recording, discovery, explicit later reconciliation, and read-only recovery | `releasekit`, `internal/publish`, `internal/git`, `cmd/releasekit` | `TestLostPublicationOutputCanBeRecoveredFromExplicitRecords`, `TestBuiltPublishRecoveryCommandSelectsItsRecordAmongOtherAttempts`, `TestRecoveryFacadeLoadsPartialEvidenceAndPreservesCause`, `TestRecoveryFacadeErrorUnwrapsCancellation`, `TestListPublicationAttemptsReadsExplicitExternalStore` |
| Cross-builds, version smoke checks, module paths, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `internal/artifact`, `internal/tempdir`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure`, `TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets`, `TestOutsideFallsBackWhenTemporaryDirectoryIsInsideWorktree` | | Cross-builds, version smoke checks, module paths, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `internal/artifact`, `internal/tempdir`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure`, `TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets`, `TestOutsideFallsBackWhenTemporaryDirectoryIsInsideWorktree` |
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages`, `TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites`, `TestEnsureReleaseEscapesSlashContainingTag` | | Explicit destination selection, standalone and automatic preflight, and delivery ordering | `releasekit`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliveryForgeSelectionIsExplicit`, `TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout`, `TestPreflightDeliveryPreservesPublicFailureKindsAndCauses`, `TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing`, `TestDeliverUnavailablePreflightStopsBeforeManagedBuild`, `TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation`, `TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne` |
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages`, `TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` | | Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
| Shared module identity and tag derivation | `internal/releaseidentity`, `internal/candidate`, `internal/build`, `internal/delivery` | `TestDeriveUsesModuleDeclarationAndPhysicalLayout`, `TestCommittedAndWorkingTreeDeclarationsUseTheirOwnSources`, `TestSelectedNestedModuleDoesNotRequireRootDeclaration`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages` | | Shared module identity and tag derivation | `internal/releaseidentity`, `internal/candidate`, `internal/build`, `internal/delivery` | `TestDeriveUsesModuleDeclarationAndPhysicalLayout`, `TestCommittedAndWorkingTreeDeclarationsUseTheirOwnSources`, `TestSelectedNestedModuleDoesNotRequireRootDeclaration`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages` |
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` | | Shared page, manifest, asset comparison, and additive retry policy | `internal/delivery` | `TestCoordinateReleaseCreatesWithFullNoteAndVerifiesRequestedTitle`, `TestCoordinateReleaseReconcilesCreateOutcomes`, `TestInspectRemoteAssetsComparesContentAndPreservesUnrelatedAssets`, `TestUploadMissingAssetsReconcilesOnceAndKeepsLaterAssetsPending` |
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/`, `examples/multi-module/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout`, `TestMultiModuleSelectorMapsSelectorsAndTags`, `TestMultiModuleLauncherUsesSelectedModuleAndProfile`, `TestMultiModuleWoodpeckerDelivery` | | CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/`, `examples/multi-module/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout`, `TestMultiModuleSelectorMapsSelectorsAndTags`, `TestMultiModuleLauncherUsesSelectedModuleAndProfile`, `TestMultiModuleWoodpeckerDelivery` |
Run the complete suite with `go test ./...`. The public API and import boundary Run the complete suite with `go test ./...`. The public API and import boundary

View File

@@ -19,11 +19,12 @@ artifact or executing a target binary. Test, vet, and package-compilation
failures retain their `go-test`, `go-vet`, and `package-compile` identities, failures retain their `go-test`, `go-vet`, and `package-compile` identities,
selected target where applicable, and underlying causes. Its selected target where applicable, and underlying causes. Its
request carries the captured repository directory and commit, output writer, request carries the captured repository directory and commit, output writer,
and internal settings. When selected, the Go-format check loads the candidate and internal settings. The Go commands run before the committed-tree sequence,
tree once, reads regular Go blobs from the captured commit, and compares them which owns its reader's lifetime and close-error attribution. When selected,
with go/format output. It uses the selected inputs, including vendor and explicit the Go-format check loads the candidate tree once, reads regular Go blobs from
shared files, and skips the captured commit, and compares them with go/format output. It uses the
symlink blobs, reports all unformatted paths, and stops with a contextual cause selected inputs, including vendor and explicit shared files, skips symlink
blobs, reports all unformatted paths, and stops with a contextual cause
on parse or inspection errors. It runs before product checks and build callbacks. on parse or inspection errors. It runs before product checks and build callbacks.
`Request.ReadCandidateTree` lets selected file checks request candidate `Request.ReadCandidateTree` lets selected file checks request candidate
contents; the Go-only path does not enumerate the tree. contents; the Go-only path does not enumerate the tree.
@@ -59,6 +60,10 @@ workspace-file check using the same candidate inventory. Resolved module bodies
are parsed once per blob object ID; only owned filesystem-replacement targets are parsed once per blob object ID; only owned filesystem-replacement targets
and line numbers remain cached. Each declaration path receives findings from and line numbers remain cached. Each declaration path receives findings from
that summary in its own path context. that summary in its own path context.
The optional forbidden-file check uses the captured tree's full path lookup
before the other file checks. It normalizes the explicitly selected
repository-relative names and reports matching entries through `forbidden-files`
without loading their blobs. Candidate-tree cleanup covers this failure path.
The optional file-size check applies normalized literal file/directory The optional file-size check applies normalized literal file/directory
exclusions with path-boundary matching, then requests local Git sizes for the exclusions with path-boundary matching, then requests local Git sizes for the
remaining selected blobs. Sizes include symlink link-text bytes; gitlinks are remaining selected blobs. Sizes include symlink link-text bytes; gitlinks are
@@ -105,9 +110,11 @@ observations remain out of scope under either setting. Observations go to the
provided writer; a nil writer keeps library use quiet. Public selection is provided writer; a nil writer keeps library use quiet. Public selection is
defined in the [configuration reference](../config.md) and GoDoc. defined in the [configuration reference](../config.md) and GoDoc.
Committed-tree metadata and blob reads disable lazy fetching and Git transports ReleaseKit-owned Git commands inspect original objects even when replacement
for those child commands. Missing local objects produce inspection errors; refs exist. Committed-tree metadata and blob reads also disable lazy fetching
source preparation retains its separate network-capable operations. See Git's and Git transports for those child commands. Missing local objects produce
inspection errors; source preparation retains its separate network-capable
operations. See Git's
[lazy-fetch controls](https://git-scm.com/docs/git) for the command mechanism. [lazy-fetch controls](https://git-scm.com/docs/git) for the command mechanism.
Candidate and delivery release-note reads use the same local object boundary. Candidate and delivery release-note reads use the same local object boundary.

View File

@@ -2,28 +2,30 @@
## Go Authors ## Go Authors
Selected module: `golang.org/x/mod` at `v0.40.0`. Selected module: `golang.org/x/mod` at `v0.43.0`.
Copyright 2009 The Go Authors. Copyright 2009 The Go Authors.
SPDX-License-Identifier: BSD-3-Clause SPDX-License-Identifier: BSD-3-Clause
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) | [LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE). License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) |
[LICENSE](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/LICENSE) |
[PATENTS](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde/PATENTS).
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f). [Source](https://go.googlesource.com/mod/+/d4f320b9266480df5ed3d791e0c68e64c58c5dde).
## Goldmark ## Goldmark
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6`. Selected module: `github.com/yuin/goldmark/v2` at `v2.1.16`.
Copyright (c) 2019 Yusuke Inuzuka. Copyright (c) 2019 Yusuke Inuzuka.
SPDX-License-Identifier: MIT SPDX-License-Identifier: MIT
License and notices: [MIT](licenses/MIT.txt) | License and notices: [MIT](licenses/MIT.txt) |
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE). [LICENSE](https://github.com/yuin/goldmark/blob/c3f939122ba4dd6f80e05043ad195b82e77fcb41/LICENSE).
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c). [Source](https://github.com/yuin/goldmark/tree/c3f939122ba4dd6f80e05043ad195b82e77fcb41).
## Standard Repository Policies ## Standard Repository Policies

View File

@@ -77,6 +77,17 @@ and orchestration bookkeeping belong behind that boundary. Additional public
packages and extension interfaces require a deliberate decision grounded in a packages and extension interfaces require a deliberate decision grounded in a
durable consumer need. durable consumer need.
Hosted delivery follows a neutral internal contract. The root facade selects a
backend explicitly and constructs it; `internal/forge` defines the backend
operations and neutral observations, failures, and write evidence;
`internal/delivery` owns shared page and asset policy; and `internal/gitea`
adapts the Gitea protocol. `internal/delivery`, `internal/forge`, and
`internal/artifact` must not depend on the Gitea adapter. Artifact declaration
and local content verification remain independent of delivery policy and forge
protocols. The compiled dependency check protects this transitive boundary.
See [ADR 0006](../adr/0006-neutral-forge-delivery-and-preflight.md) for the
selected delivery and preflight design.
Go declarations and GoDoc own exact API contracts. Compiled-export checks, Go declarations and GoDoc own exact API contracts. Compiled-export checks,
dependency checks, and external-package behavioral tests protect the selected dependency checks, and external-package behavioral tests protect the selected
facade boundaries. facade boundaries.

View File

@@ -1,18 +1,36 @@
# ReleaseKit release procedure # ReleaseKit release procedure
ReleaseKit's deliverables are its source tag and a hosted Gitea page containing ReleaseKit's deliverables are its source tag and a hosted Gitea page containing
the complete checked-in release note. The page is delivered asynchronously by the complete checked-in release note. Deliver the page locally after publication
the prepared [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml); or asynchronously through the prepared
it is not a source-release completion check and carries no binary assets. The [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml).
authoritative repository is `origin` at Hosted-page delivery has a separate status from source-release completion and
`https://gitea.maximumdirect.net/eric/ReleaseKit.git`, and the release branch carries no binary assets. The authoritative repository is `origin` at
is `main`. A release completes when the intended annotated tag is successfully `ssh://git@forge.maximumdirect.net:22222/base-layer/releasekit.git`, and the release
branch is `main`. The hosted Gitea destination is
`https://forge.maximumdirect.net/base-layer/releasekit`. A release completes
when the intended annotated tag is successfully
pushed, or when one exact-object recovery query confirms that the push pushed, or when one exact-object recovery query confirms that the push
succeeded. CI and consumer installation are not completion checks. succeeded. CI and consumer installation are not completion checks.
An optional [delivery rehearsal](consumers/rehearsal.md) exercises the same
tagged CI workflow with temporary diagnostic resources before a release. It is
not a publication gate. Configure the committed profile's Woodpecker settings
and separate local token before invoking it, and retain any reported record
until cleanup is resolved.
## Prepare a candidate ## Prepare a candidate
Use a clean clone on `main`. The chosen build toolchain is Go 1.26.8. Make that For local hosted-page delivery, save a Gitea personal access token in
`.releasekit/gitea-token` with owner-only file permissions. The file contains
only the token. ReleaseKit's profile selects this file for local delivery and
`RELEASEKIT_GITEA_TOKEN` for CI; `.releasekit/` is already ignored. Its optional
`validation.forbidden_files` selection checks that this path is absent from the
committed candidate. Source publication requires no delivery token. The
[configuration reference](config.md) owns credential selection and validator
semantics.
Use a clean clone on `main`. The chosen build toolchain is Go 1.27.4. Make that
local installation the active `go` command for preparation, building the release local installation the active `go` command for preparation, building the release
executable, and candidate validation: executable, and candidate validation:
@@ -28,7 +46,7 @@ The maintained [source-delivery image](../examples/woodpecker/releasekit-source-
and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the
chosen build toolchain; update them together when that selection changes. chosen build toolchain; update them together when that selection changes.
The current consumer minimum is Go 1.26.0, declared in [go.mod](../go.mod). The current consumer minimum is Go 1.27.0, declared in [go.mod](../go.mod).
Keep it for a release unless release preparation deliberately selects a newer Keep it for a release unless release preparation deliberately selects a newer
series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain). series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain).
When increasing it, update `go.mod` to the first stable version of the selected When increasing it, update `go.mod` to the first stable version of the selected
@@ -43,9 +61,9 @@ the exact version. Summarize the change and any compatibility or upgrade impact.
End the note with the three license links at the immutable source tag: End the note with the three license links at the immutable source tag:
```markdown ```markdown
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/COPYRIGHT) | [COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/LICENSE) | [LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/docs/oss/attribution.md) [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/docs/oss/attribution.md)
``` ```
Replace every `vX.Y.Z` with the selected version. These are links to the same Replace every `vX.Y.Z` with the selected version. These are links to the same
@@ -96,59 +114,119 @@ for ReleaseKit's first release before any released ReleaseKit executable
exists. It uses the local Go toolchain. Preparation must finish before the exists. It uses the local Go toolchain. Preparation must finish before the
offline validation begins. offline validation begins.
## Resolve failures ## Deliver the hosted release page
A failed push triggers a URL-resolution check against the captured endpoint, After source publication succeeds, deliver the hosted page locally when
then at most one exact authoritative tag query. If the endpoint no longer Woodpecker automation is inactive. From the same repository root, keep the
resolves to itself, recovery reports `unknown` without querying the rewritten worktree clean and `HEAD` at the published tag's commit. Reuse the executable
destination. An exact tag-object match confirms publication even when Git built by the publication command:
reported an error. A proven absent tag is `not_published`; a different object
is a conflict; an unreadable query is `unknown`. The command retains its local
tag and reports the state, phase,
candidate commit, tag object, and captured publication endpoint when available.
Do not retry an unknown result until you resolve the authoritative ref at that
exact endpoint. Copy the reported endpoint value into the variable below using
normal shell quoting; retain the version and tag object from the same result.
The command checks that Git URL rewriting still resolves this value to itself;
the manual check below applies the same rule before querying:
```sh ```sh
releasekit_endpoint='COPY_CAPTURED_ENDPOINT' .releasekit/bin/releasekit deliver vX.Y.Z
releasekit_version='vX.Y.Z'
test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"
``` ```
A failed URL-equality check or remote query leaves the outcome unresolved. The command uses the configured Gitea destination and token source to deliver
Correct transport configuration before continuing. The reported endpoint may the complete checked-in release note. Report its result separately from the
be different from `origin`'s fetch URL or its current push URL; querying either completed source release. For failed or uncertain delivery, follow the recovery
of those does not establish absence at the captured endpoint. instructions below using the same immutable version.
Compare the returned object ID with the tag object reported by the command. ## Resolve publication failures
An exact match confirms publication. If the ref is absent, the version was not
published; only then may you deliberately remove the unpublished local tag Each publication invocation attempts to save its captured identity before the
with `git tag -d vX.Y.Z` before correcting the candidate or retrying. Do not tag push. The CLI reports the saved record path separately from publication
move, overwrite, or delete a tag that exists remotely. If a different object success or failure and, after a push or immediate-reconciliation error, prints a
uses the version, choose a new version after resolving the conflict. copyable command that selects that exact record. Run that command, or use the
source-built executable prepared above, to make a separate later observation:
```sh
./.releasekit/bin/releasekit reconcile --record '/absolute/path/to/attempt-record.json'
```
The saved evidence fixes the original endpoint and tag identity. Later recovery
uses current supported transport settings for the recorded remote name, but it
does not substitute the current remote URL, inspect the local tag or current
HEAD, load a profile, rerun checks, or change repository state. A completed
observation reports `published`, `not_published`, or `conflict`; an incomplete
observation reports `unknown` with diagnostic context. Resolve an unknown result
by correcting the identified endpoint rewrite, transport configuration, or
missing evidence. For incomplete saved identity, select another record with the
required fields or use complete typed evidence through the Go API.
If command output was lost, list local attempts and explicitly select the
matching record by its module, full tag, and saved identity:
```sh
./.releasekit/bin/releasekit publication-attempts --repo "$PWD"
./.releasekit/bin/releasekit reconcile --record '/absolute/path/from-the-list/attempt-record.json'
```
Discovery only reads the local store. It neither queries remotes nor chooses an
attempt automatically. If the original recovery entry point is unavailable,
select another supported ReleaseKit CLI and pass the same record path explicitly.
An older record may lack the endpoint, tag-object ID, candidate commit, or
another field required for a conclusive result.
A later observation that the tag is absent describes the remote at that time;
it does not prove the version was never published. Never reuse a version known
to have been published, and preserve published tags and contents as immutable.
Keep removal of an unpublished local tag, candidate correction, and retry as
explicit operator decisions after reviewing the record and authoritative
remote state. A conflicting object requires resolving the conflict and selecting
an unused version when appropriate; do not move, overwrite, or delete a
published tag.
If record storage fails, ReleaseKit reports the recording warning separately;
the warning does not change the actual publication outcome. The saved handoff is
then unavailable. A Go caller that retained `PublicationResult.Evidence` can
still pass that typed evidence directly to `ReconcilePublication`. Process
termination before the record is written, removed storage, and older incomplete
records can leave no sufficient saved evidence for later recovery.
Later reconciliation adds no successful-push read-back, polling, CI, consumer
installation, or hosted-delivery gate. Hosted page delivery remains separate.
If validation or a guard fails before this invocation pushes, correct and If validation or a guard fails before this invocation pushes, correct and
commit the candidate, publish `main`, and run the command again. A retained commit the candidate, publish `main`, and run the command again. A retained
local tag still requires the authoritative-state check above before removal; local tag still requires reviewing the selected record and authoritative state
a concurrent publisher may already have published the version. The prepared before deciding whether to remove it. The prepared
Woodpecker workflow builds the CLI from the tagged checkout, then uses Woodpecker workflow builds the CLI from the tagged checkout, then uses
`ci-deliver` for page-only delivery. To activate it after configuring the `ci-deliver` for page-only delivery. To activate it after configuring the
destination and secret, copy it to `.woodpecker/releasekit-source-delivery.yml` destination and secret, copy it to `.woodpecker/releasekit-source-delivery.yml`
and add the Woodpecker repository secret `releasekit_gitea_token`. If page and add the Woodpecker repository secret `releasekit_gitea_token`. If page
delivery fails or is uncertain, inspect the hosted release and retry the same delivery fails or is uncertain, inspect the hosted release and retry the same
immutable version from its tag: immutable version from its tag. The retry requires a clean tagged checkout
before preparing or building the tool:
```sh ```sh
git fetch origin "refs/tags/vX.Y.Z:refs/tags/vX.Y.Z" (
git checkout --detach "vX.Y.Z" set -e
GOTOOLCHAIN=local go mod download version=vX.Y.Z
mkdir -p .releasekit/bin tag_ref="refs/tags/$version"
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit git fetch origin "$tag_ref:$tag_ref"
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z" tag_commit=$(git rev-parse --verify "$tag_ref^{commit}")
git checkout --detach "$tag_commit"
worktree_status=$(git status --porcelain --untracked-files=all)
if [ -n "$worktree_status" ]; then
printf '%s\n' 'Delivery retry requires a clean tagged checkout.' >&2
exit 1
fi
releasekit_host_os=$(GOTOOLCHAIN=local go env GOHOSTOS)
releasekit_host_arch=$(GOTOOLCHAIN=local go env GOHOSTARCH)
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
GOTOOLCHAIN=local go mod download
mkdir -p .releasekit/bin
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
.releasekit/bin/releasekit deliver "$version"
)
```
For an older tag whose CLI predates `token_file`, build the tagged executable
as above, then supply the token through its environment variable when retrying:
```sh
RELEASEKIT_GITEA_TOKEN="$(cat .releasekit/gitea-token)" \
.releasekit/bin/releasekit deliver "vX.Y.Z"
``` ```
The root ignore file excludes `.releasekit/`. Delivery uses the committed note The root ignore file excludes `.releasekit/`. Delivery uses the committed note

35
docs/releases/v0.10.0.md Normal file
View File

@@ -0,0 +1,35 @@
# ReleaseKit v0.10.0
ReleaseKit now requires Go 1.27.0 or later, up from Go 1.26.0. Release builds
and validation use Go 1.27.4, and the maintained Woodpecker templates use
`golang:1.27.4-bookworm`.
## Dependency upgrades
- `github.com/yuin/goldmark/v2`, used for Markdown validation, moves from
v2.1.6 to v2.1.16.
- `golang.org/x/mod`, used for Go module handling, moves from v0.40.0 to
v0.43.0. This selects `golang.org/x/tools` v0.52.0 in the module graph.
## Upgrade guidance
1. Make Go 1.27.0 or newer available wherever you build, test, or run
ReleaseKit through `go tool`. Set the `go` directive to at least `1.27.0`
in each consumer module that upgrades to v0.10.0.
2. Upgrade the dependency to v0.10.0. Use
`go get go.maximumdirect.net/releasekit@v0.10.0` for a Go API dependency or
`go get -tool go.maximumdirect.net/releasekit/cmd/releasekit@v0.10.0` for a
registered CLI tool. Run `go mod tidy`, regenerate `vendor/` if you use it,
and commit the resulting changes. For a standalone CLI, rebuild it with
`go install go.maximumdirect.net/releasekit/cmd/releasekit@v0.10.0`.
3. Update copied Woodpecker templates or custom CI images before delivering
tags that select v0.10.0. For an older tag, use a workflow compatible with
the ReleaseKit version recorded in that tag's module files.
The consumer guides cover tool registration, host target selection, and
tagged delivery workflows. [Adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/docs/consumers/adoption.md) ·
[Delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/docs/consumers/delivery.md)
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/docs/oss/attribution.md)

112
docs/releases/v0.11.0.md Normal file
View File

@@ -0,0 +1,112 @@
# ReleaseKit v0.11.0
ReleaseKit adds general source releases, calendar versions, configuration
readiness checks, and an optional rehearsal of the actual Woodpecker delivery
workflow. This release also separates local and CI delivery credentials and
extends saved evidence to carry the selected source and version identity.
The Go minimum remains 1.27.0; release builds and validation use Go 1.27.4.
## New capabilities
- Release repositories and source directories without an application `go.mod`,
including configuration-only products. Select Go validation and builds
independently from Go module publication. Go applications can publish source
releases whose product version is independent of their module path major.
- Choose stable SemVer, Gregorian date versions, or year-month versions.
Calendar identifiers, optional prefixes, and source tag prefixes flow through
candidate checks, publication, notes, version injection, artifact names,
hosted delivery, and recovery. Go module publication retains Go's prefixed
SemVer and module-major rules. ReleaseKit's own releases continue using SemVer.
- Run `releasekit validate` before selecting a release version or writing a
release note. It inspects selected configuration, source/build inputs,
credentials, and read-only remote access. Operation selection and offline
mode narrow its scope. It does not execute product checks, build binaries,
download dependencies, or establish actual CI secret injection.
- Run `releasekit test` to dispatch a temporary diagnostic tag through the
configured Woodpecker workflow. The actual job delivers and reads back the
page and any declared binary/checksum contents. Separate workflow, build,
verification, and cleanup outcomes retain safe job diagnostics. Private
attempt records support explicit `test-resume` and `test-cleanup` recovery.
Cleanup waits for observable CI quiescence and removes owned diagnostic
resources; CI history, notifications, and webhook effects remain.
- Source-only launchers and CI bootstrap share a committed `.releasekit-version`
pin and retain a host executable for later recovery. The root Go facade adds
`SourceSpec`, `Validate`, `Rehearse`, `ResumeRehearsal`, `CleanupRehearsal`, and
`DeliverRehearsal`, with facade-owned requests, results, and source evidence.
Read the [configuration reference](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/config.md),
[readiness guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/consumers/readiness.md),
and [rehearsal guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/consumers/rehearsal.md)
for the supported settings, version grammars, and operational boundaries.
## Correctness and efficiency
Readiness shares operation-specific configuration checks with execution,
preserves local required files when inspecting captured source, and supports
Go's `gopkg.in` unstable-major paths. Go package patterns remain available to
the builder and are reported as unresolved during readiness rather than
treated as literal directories. Package-input inspection scopes committed
metadata to the selected directory and scans working entries in bounded batches.
Rehearsal recovery distinguishes definite push rejection from uncertain writes,
permits cleanup of a known matching page after its tag is already absent, and
retains the explicit forge selection. Diagnostic CI delivery uses the public
orchestration facade and ordinary delivery error classifications. Production
tags sharing the diagnostic namespace prefix retain their production routing.
CI pagination tolerates consistent overlaps, pipeline membership uses an index,
and result parsing discards ordinary log fragments without retaining entire
long lines.
## Compatibility and upgrade guidance
1. Upgrade each consuming Go module to v0.11.0 with
`go get go.maximumdirect.net/releasekit@v0.11.0`, or register/upgrade its CLI
with `go get -tool go.maximumdirect.net/releasekit/cmd/releasekit@v0.11.0`.
Run `go mod tidy`, regenerate vendored dependencies when applicable, and
commit the module changes. A standalone CLI can use
`go install go.maximumdirect.net/releasekit/cmd/releasekit@v0.11.0`.
2. Move `delivery.token_file` to `delivery.credentials.local.token_file` and
`delivery.token_env` to
`delivery.credentials.ci.token_environment_variable`. The former flat
fields are rejected. Local delivery and rehearsal use the selected token
file; `ci-deliver` uses the selected job environment variable. An empty CI
declaration selects `RELEASEKIT_DELIVERY_TOKEN`. Keep existing secret and
variable names by configuring them explicitly. Neither context falls back
to the other; missing, unreadable, or blank selected credentials are errors.
Go API callers continue supplying tokens explicitly.
3. Existing profiles with all four selection objects (`source`, `go`,
`publication`, and `version`) omitted or null retain Go-module publication
and prefixed stable SemVer. Go API requests with `Source: nil` retain the
`ModuleDir` shorthand. Any non-null profile selection object chooses the
explicit model: declare `go: {}` for Go checks/builds and
`publication.mode: "go-module"` for Go module publication. An explicit
`source: {}` or zero `SourceSpec` selects a root source release with Go
disabled. Update callbacks that handle source-only candidates to use source
identity; their Go module identity is empty.
4. Update copied workflows together with the selected tool. Source-only
repositories can pin `v0.11.0` in `.releasekit-version`. Multi-product
selector maps now have four columns: selector, production tag pattern, tool
module directory, and profile path. The `-` tool-module value selects the
installed pinned tool. Align production tag filters with the selected
version format. To enable rehearsal, add diagnostic dispatch and matching
selector/profile routing, declare CI delivery credentials, and configure
the separate local Woodpecker token and exact repository/workflow/step.
Native Git credentials and the local forge token need diagnostic deletion
permissions. Rehearsal remains optional and does not change production
source-publication completion.
5. Rebuild retained artifacts before `deliver --assets`: build receipts now
use schema 2 and older schemas are rejected. Newly saved publication records
use format 3; versions 1 and 2 remain readable with their captured evidence.
Older tools cannot read the new format. Continue selecting exact records
for recovery; publication records and rehearsal records are separate.
The [adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/consumers/adoption.md)
and maintained examples cover tool registration, source-only installation, and
coordinated workflow upgrades. The
[receipt](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/integrations/build-receipts.md)
and [publication record](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/integrations/publication-records.md)
references describe the evidence formats.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.11.0/docs/oss/attribution.md)

59
docs/releases/v0.5.0.md Normal file
View File

@@ -0,0 +1,59 @@
# ReleaseKit v0.5.0
## Summary
ReleaseKit adopts `go.maximumdirect.net/releasekit` as its Go module identifier.
The vanity path resolves to the Gitea repository at
`https://forge.maximumdirect.net/base-layer/releasekit`.
## Changes
- The orchestration facade is `go.maximumdirect.net/releasekit`, the runtime
facade is `go.maximumdirect.net/releasekit/buildinfo`, and the executable
package is `go.maximumdirect.net/releasekit/cmd/releasekit`.
- Imports, version-injection linkage, compiled API checks, consumer fixtures,
and maintained release launchers and Woodpecker workflows use the new module
identity.
- ReleaseKit's hosted-page delivery profile and maintainer guidance use Gitea
at `forge.maximumdirect.net`, owner `base-layer`, repository `releasekit`.
## Compatibility
This pre-1.0 minor release changes package import paths and requires consumer
migration. Facade roles, command behavior, configuration formats, and the Go
1.26.0 consumer minimum retain their existing definitions. The runtime version
accessor and builder use the new module's runtime implementation for injection.
Packages imported through different module paths have distinct Go identities.
Coordinate import changes in packages that exchange ReleaseKit facade types,
and update builders and applications using `buildinfo` together.
Published versions through v0.4.2 retain the original
`gitea.maximumdirect.net/eric/ReleaseKit` module declaration. Those versions
continue to describe their original source and use their matching historical
instructions. A vanity-path download of an older tag does not change its module
declaration.
## Upgrade guidance
1. Update application, library, test, and generated imports for the root facade
and `buildinfo` to the new paths. Select v0.5.0 or a later compatible release
using the [adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/consumers/adoption.md#migrating-from-the-original-module-path).
2. For CLI tool dependencies, remove the old tool declaration and register
`go.maximumdirect.net/releasekit/cmd/releasekit` at the selected version.
3. Update copied launchers and Woodpecker workflows together with the module
selection. The maintained examples use
`releasekit_module=go.maximumdirect.net/releasekit`.
4. Run `go mod tidy`, review any old-path dependencies retained transitively,
and commit module and workflow changes together. Keep existing consumer tags
intact; their delivery retries use their recorded module files and matching
workflows.
Source repository and hosted release URLs use the Gitea host; Go imports and
tool dependencies use the vanity path. ReleaseKit's source publication and
hosted-page delivery retain their separate outcomes under the
[maintainer procedure](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/release.md).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.5.0/docs/oss/attribution.md)

125
docs/releases/v0.6.0.md Normal file
View File

@@ -0,0 +1,125 @@
# ReleaseKit v0.6.0
## Summary
ReleaseKit adds file-based delivery credentials, optional checks for forbidden
committed files, neutral delivery coordination with explicit Gitea selection, and
authenticated, read-only credential preflight. It also corrects dependency
preparation, publication recovery, and build cancellation handling.
## Changes
- Delivery profiles can select a plain token file through `token_file`.
Relative paths resolve from the checkout root; a nonblank token environment
value takes precedence. The CLI trims file contents and reports unreadable
or blank files as credential-loading failures. Library callers continue to
supply the token explicitly through the destination.
- `ValidationSpec.ForbiddenFiles` and `validation.forbidden_files` select
literal repository-relative paths that must be absent from the committed
candidate. This optional check can protect a local token-file path. It
inspects committed path metadata independently of module/shared-file inputs;
it does not inspect file contents or history.
- `releasekit.DeliveryRequest.Destination` now uses the facade-owned
`releasekit.DeliveryDestination`. Set `Forge: releasekit.ForgeGitea` for
Gitea delivery. The removed `GiteaDestination` type has no compatibility
alias.
- Delivery profiles must include `"forge": "gitea"`. The selection is
required only when `deliver` or `ci-deliver` is requested; the URL does not
infer a backend. `check`, `build`, and source `publish` remain independent of
delivery selection and credentials.
- `releasekit.PreflightDelivery` allows callers to check a destination without
a checkout or tag. `Deliver` performs the same read-only preflight
automatically. For Gitea, the check authenticates through repository-scoped
reads and makes no test release or asset writes.
- `DeliveryPreflightError` exposes classified failures and retains the
underlying cause. Successful preflight confirms authentication and repository
access plus available permission evidence; it does not guarantee future
release or asset writes. Gitea's code-push permission metadata does not
establish release-write or asset-write permission.
- The CLI keeps `RELEASEKIT_GITEA_TOKEN` as its default token environment
setting and preserves configured environment/file precedence. Selection,
local credential-loading, and classified preflight configuration/access
errors return status 2; unavailable preflight and cancellation during
preflight/preparation return status 1. Later authorization failures follow
delivery outcomes. An unresolved write returns status 3, including when
cancellation prevents reconciliation; known delivery failures return 1.
- Binary `ci-deliver` checks credentials before application dependency
downloads and checks again during delivery. The automatic check now precedes
full local artifact size and digest verification; those checks still finish
before hosted writes.
## Correctness and efficiency
- Dependency preparation now resolves the containing checkout root, including
when called from a subdirectory or filesystem alias. `ModuleDir` is relative
to that root, and empty selection prepares the root module. Standalone use
retains the supplied directory as its base, including Go-only use when Git
is unavailable. Damaged checkout metadata and operational discovery failures
remain errors before dependency downloads.
- Preparation overrides alternate module-file selection from inherited or
persistent `GOFLAGS`, while retaining other effective Go settings. Downloads
therefore use the selected module's ordinary metadata.
- Candidate checking rejects a derived release tag that Git cannot create
before running validation. CI delivery also validates the selected module's
complete tag before dependency preparation.
- Publication recovery treats a peeled-only tag observation as unresolved,
retains the original push failure, and reports `PublicationUnknown` with CLI
status 3. Complete tag observations retain their existing recovery behavior.
- Cancellation and deadline expiration during build source inspection remain
identifiable through `errors.Is`; partial results retain completed artifacts.
Local artifact inspection errors also retain their underlying causes through
delivery.
- Gitea asset operations classify a missing or nonpositive service release ID
as a malformed observation before making an asset request. Page-only release
lookup retains its existing minimal response requirements.
- Asset delivery uses linear pending-asset bookkeeping and sorts only missing
assets once, reducing repeated work during uploads and reconciliation.
## Compatibility
This pre-1.0 minor release changes the public destination type and requires
explicit forge selection for delivery. Gitea is the supported backend.
Preparation callers that previously used a checkout subdirectory as their
implicit module selection must now select that module with `ModuleDir`.
Ambient `GOFLAGS` no longer redirects preparation to an alternate module file.
The module identifier remains `go.maximumdirect.net/releasekit`, and the Go
consumer minimum remains 1.26.0. Receipt schemas and the separate source
publication and hosted-delivery outcomes retain their existing definitions.
## Upgrade guidance
Select v0.6.0 for library and CLI dependencies, then update integrations as
follows:
1. Replace `releasekit.GiteaDestination` with
`releasekit.DeliveryDestination` and set
`Forge: releasekit.ForgeGitea` in each API request.
2. Add `"forge": "gitea"` to every profile used for `deliver` or
`ci-deliver`, including profiles loaded from a tagged CI checkout. Keep the
existing `base_url`, owner, repository, token environment, and token file
settings.
3. If handling preflight failures in Go, use `errors.As` to inspect
`*releasekit.DeliveryPreflightError` and use `errors.Is` or `errors.As` on
its unwrapped cause as needed.
4. Continue to treat successful preflight as evidence of repository access,
not a guarantee that a later write will be accepted. Source publication
continues to use Git authentication and does not require hosted delivery
credentials.
5. For dependency preparation of a nested module, supply its repository-relative
path through `DependencyPreparationRequest.ModuleDir`, even when
`RepositoryDir` already points inside that module. Root-module consumers can
keep `ModuleDir` empty.
6. To adopt file-based credentials, store the token in an ignored local file
and configure `delivery.token_file`. Optionally add that same
repository-relative path to `validation.forbidden_files`. Credential loading
and candidate file validation are independent selections; configuring the
file alone does not enable the validator.
See the [delivery guide](../consumers/delivery.md), [configuration reference](../config.md),
[CLI contract](../cli.md), and [Gitea integration guide](../integrations/gitea.md)
for current behavior.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.6.0/docs/oss/attribution.md)

106
docs/releases/v0.7.0.md Normal file
View File

@@ -0,0 +1,106 @@
# ReleaseKit v0.7.0
## Summary
ReleaseKit improves source-publication integrity, cancellation, credential-safe
diagnostics, partial-result reporting, and temporary-file cleanup. It also bounds
retained Go failure diagnostics and remote attachment comparison work while
preserving the existing public facades and configuration formats.
## Publication and Git operations
- Exact tag pushes disable submodule recursion, correcting inherited
`push.recurseSubmodules=only` settings that could report success without
publishing the release tag.
- ReleaseKit-owned Git inspection and preparation use original objects when
replacement refs exist. Committed module identity, release notes, validation
inputs, and build source eligibility use that consistent view. Ordinary dirty
builds remain supported, with their source eligibility reported separately.
- A verified local tag object remains available in `PublicationResult.TagObject`
when later inspection fails. Errors identify a possibly retained local ref
when its object ID could not be established. Failed verification stops before
a push.
- HTTP(S) userinfo is masked in owned Git diagnostics and CLI output, including
literal apostrophes in credentials and failed CI checkout preparation. Native
Git authentication, exact endpoint comparisons, and the raw captured
`PublicationResult.Endpoint` value retain their existing behavior.
- Child environment overlays preserve the working-directory-derived `PWD` on
POSIX systems. Native Git hooks now receive the expected directory environment
when ReleaseKit is invoked from another checkout or module subdirectory.
## Cancellation and diagnostic retention
- Buffered subprocess output has bounded I/O teardown after cancellation or
child exit, including when descendants retain inherited output descriptors.
Piped Git-reader cancellation closes owned pipes and joins child cleanup.
Cancellation remains recognizable through `errors.Is`; ordinary execution
failures preserve their underlying causes.
- A queued blob read rechecks cancellation after acquiring the reader mutex,
preserving a healthy batch session for later reads.
- Status-only Go commands and dependency preparation retain a 1 MiB diagnostic
tail. Failed commands identify omitted earlier output. Existing streaming
output continues to be forwarded in full, and commands requiring returned
output keep their complete capture.
## Builds and hosted delivery
- Completed build artifacts are reported only after hashing succeeds. A hashing
failure identifies the affected output and preserves earlier completed
artifacts and their digests.
- Temporary allocation and cleanup failures retain their paths and underlying
causes, including candidate builds, native version checks, delivery builds,
tag-message files, and build receipts.
- A managed-build cleanup failure after confirmed hosted delivery returns an
error alongside `DeliveryComplete` and the confirmed asset observations. The
CLI reports completed remote work and the local cleanup failure, returning
operational status 1.
- Gitea attachment downloads follow at most ten redirects, retaining cycle
detection and per-origin authorization handling. Limit exhaustion is
unverifiable content.
- Remote attachment comparison reads at most the locally verified expected size
plus one byte. Shorter or longer content conflicts; equal-length content still
requires the expected digest. Read, close, and cancellation errors remain
inspection failures, with existing attempted-write reconciliation preserved.
Shared Git observations, validation sequencing, artifact declaration matching,
and CLI workflows were consolidated internally. Consumer-facing types continue
to belong to the root `releasekit` and runtime `buildinfo` facades.
## Compatibility and upgrade guidance
The module identifier remains `go.maximumdirect.net/releasekit`, and the Go
consumer minimum remains 1.26.0. Existing v0.6.0 API calls, profile fields, and
build receipt formats remain supported. This minor release changes operational
behavior through the diagnostic and redirect budgets and cleanup-error reporting
described above.
When adopting v0.7.0:
1. Update library and CLI dependencies to v0.7.0 using the existing import paths
and profiles.
2. Handle a delivery error together with `DeliveryResult.State`. For
`DeliveryComplete`, address the reported local cleanup path; the confirmed
hosted delivery is already complete. Continue to resolve partial, conflicting,
and unknown outcomes through their existing recovery guidance.
3. Retain candidate validation's streamed `Output` when complete test diagnostics
are needed. Status-only failure text now contains the retained tail and an
omission notice when applicable.
4. When using Git replacement refs, expect release evidence to be evaluated
against original committed objects. A build of dirty or replacement-derived
working content can succeed while remaining ineligible for binary delivery.
5. Inspect the reported local tag ref after a tag-creation or verification
failure, including when `TagObject` is empty. Continue to treat the raw
`PublicationResult.Endpoint` as sensitive when handling it in application
output or logs.
See the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/publish.md),
[build guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/build.md),
[delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/consumers/delivery.md),
[CLI contract](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/cli.md),
and [Gitea integration guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/integrations/gitea.md)
for current behavior. Source publication and hosted delivery retain their
separate outcomes under the [maintainer procedure](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/release.md).
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.7.0/docs/oss/attribution.md)

54
docs/releases/v0.8.0.md Normal file
View File

@@ -0,0 +1,54 @@
# ReleaseKit v0.8.0
## Summary
ReleaseKit adds read-only recovery for source-publication attempts. It attempts
to retain evidence before a tag push, lets operators discover and explicitly
select a saved attempt, and observes the original destination without repeating
candidate validation or changing tags. Source publication and hosted delivery
continue to have separate outcomes.
## Publication recovery
- `Publish` returns reusable `PublicationEvidence` and attempts to save a
private record. The result reports the saved path or a recording error
separately from the publication outcome. Go callers can load or list records
and reconcile retained evidence through the root facade.
- The CLI adds `publication-attempts` for local discovery and `reconcile` for
an explicitly selected record. Both support human-readable and structured
output. `publish --record-dir` selects an alternate record directory, and
failed publication can print a recovery command for the saved attempt.
- Recovery uses the captured endpoint and full tag with current supported Git
transport settings. It reports publication, current absence, conflict, or an
unresolved observation. Current absence does not prove that a version was
never published; published versions and their contents remain immutable.
- Records preserve exact endpoint and path bytes. Ordinary UTF-8 evidence uses
record format 1; format 2 preserves other bytes. Recovery diagnostics redact
HTTP(S) URL userinfo, while private records and typed evidence can contain
sensitive endpoints. Operators control record retention and removal.
## Consumer tools and compatibility
The module path remains `go.maximumdirect.net/releasekit`, and the Go consumer
minimum remains 1.26.0. Existing publication calls and release profiles remain
supported. Publication now attempts to write a private record by default; a
storage failure is reported separately and does not change the publication
result. Applications handling results should inspect `RecordError` when a saved
recovery handoff matters.
Consumers with the CLI registered as a Go tool in their module can run it with
`go tool releasekit`.
The maintained multi-module launcher and Woodpecker examples use the selected
module's tool version. Register the CLI before generating a vendor tree when
using a vendored tool. Older recovery CLIs that only support record format 1
cannot load format 2 records; use a CLI that supports format 2.
See the [publication guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/consumers/publish.md),
[CLI reference](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/cli.md),
[publication record formats](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/integrations/publication-records.md),
and [consumer adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/consumers/adoption.md)
for usage and recovery details.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.8.0/docs/oss/attribution.md)

41
docs/releases/v0.9.0.md Normal file
View File

@@ -0,0 +1,41 @@
# ReleaseKit v0.9.0
ReleaseKit's maintained launchers and generated Go recovery commands now
prepare and run the release tool for the Go host when inherited `GOOS` and
`GOARCH` select another target. Release profiles still select the targets for
application builds.
## Launcher, delivery, and recovery fixes
- Local launchers and Woodpecker templates select the host before preparing
tool dependencies or compiling the CLI. Module-based launchers invoke
ReleaseKit by its full Go package path, so another registered tool named
`releasekit` does not make the invocation ambiguous.
- Generated Go recovery commands select the host when run in a POSIX shell
and find the Go executable through `PATH`. Recovery for API-only consumers
preserves both wildcard and version-specific module replacements when
relocating relative paths, fixing a panic after a failed publication.
- The manual hosted-page retry stops if fetching or checking out the tag fails,
or if local edits remain. It checks the tagged checkout before downloading
dependencies or building the CLI.
## Compatibility and upgrade
The module path remains `go.maximumdirect.net/releasekit` and the Go consumer
minimum remains 1.26.0. Public Go APIs, release profiles, and publication
record formats are unchanged.
Update copied launchers and CI templates to get the host and tool selection
fixes. Updating the module dependency alone does not update those files.
Configured product checks inherit the launcher's host target; if a check
needs an application target, set it explicitly in the check's `env` map
or command.
See the [adoption guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/consumers/adoption.md),
[delivery guide](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/consumers/delivery.md),
and [maintainer runbook](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/release.md)
for updated recipes.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/LICENSE) |
[ATTRIBUTION](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.9.0/docs/oss/attribution.md)

View File

@@ -0,0 +1,67 @@
# Deferred resource work
These two proposals remain deferred after the completed audit remediation for
v0.7.0. Their assessments are complete; production limits and exclusion indexing
await a future decision supported by consumer needs. The assessment evidence
was recorded in commit `9dc87ae`.
## Forge JSON response budgets
**Status:** Deferred; local sizing assessment complete.
Forge JSON decoding can consume memory proportional to response size. Release
notes and unpaginated attachment lists have no established supported maximum.
A future proposal should establish an appropriate response envelope before
selecting byte/time budgets or configuration. Any limit must retain context
cancellation, useful error classification, and uncertain-write reconciliation:
a rejected response does not establish that a create or upload failed remotely.
The [Gitea fixtures](../../internal/gitea/backend_test.go) construct repository,
release, tag, and attachment responses. Representative encoded fixtures measured
81 bytes for repository identity, 136 with permissions, 125 for a sparse release,
144 for a populated release, 73 for a one-item attachment list, and 62 for an
upload response, including the encoder's newline. Four literal release-ID
fixtures measured 21, 28, 29, and 29 bytes without a newline. Generated URLs,
notes, and lists vary with fixture inputs.
The checked-in v0.1.0–v0.6.0 release notes measured 1,235–7,899 bytes during the
assessment. These observations describe local examples and establish no
deployment or protocol maximum. Production response caps remain deferred.
## File-size exclusion indexing
**Status:** Deferred; benchmark assessment complete.
The current [exclusion scan](../../internal/validation/file_size.go) compares
each selected file with the normalized exclusions until a match is found.
The adoption decision weighs measured speedups against allocation and
path-walking costs for consumer workloads. Preserve literal component boundaries,
module-relative normalization, shared inputs, and the first oversized-file result.
The [benchmark-only prototype](../../internal/validation/file_size_benchmark_test.go)
compares the scan with a normalized set and ancestor lookups. It covers 1,000
and 10,000 paths, 1/10/100/1,000 exclusions, shallow/deep paths, early matches,
and nonmatches. Each measured operation includes normalization and one index
construction where applicable; fixture strings are prepared outside timing.
On Linux/amd64, Go 1.26.8, Intel Core i5-7260U, 64 combinations ran with three
samples each using:
```sh
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go test ./internal/validation \
-run '^$' -bench '^BenchmarkFileSizeExclusions$' -benchtime=100ms -count=3
```
Representative median times and allocations were:
| Paths / exclusions / case | Scan | Index |
| --- | --- | --- |
| 1,000 / 1 / shallow early match | 24.5 µs, 16 B, 1 allocation | 44.0 µs, 16 B, 1 allocation |
| 1,000 / 1 / deep nonmatch | 25.7 µs, 16 B, 1 allocation | 119.0 µs, 16 B, 1 allocation |
| 10,000 / 1,000 / shallow early match | 270 µs, 16,384 B, 1 allocation | 564 µs, 70,992 B, 6 allocations |
| 10,000 / 1,000 / shallow nonmatch | 227.0 ms, 16,384 B, 1 allocation | 521 µs, 70,992 B, 6 allocations |
| 10,000 / 1,000 / deep nonmatch | 233.4 ms, 16,384 B, 1 allocation | 1.36 ms, 70,992 B, 6 allocations |
The prototype was slower for small lists and early matches, and faster for
large nonmatching lists with higher allocation costs. Production matching
remains unchanged pending an adoption decision.

1
examples/multi-module/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.releasekit/

View File

@@ -0,0 +1 @@
v0.11.0

View File

@@ -1,7 +1,7 @@
# Multi-module release example # Multi-module release example
This example maps selectors and complete event tags to a physical Go module This example maps selectors and complete event tags to a physical Go module
directory and a repository-root profile. The library derives the release tag directory or installed tool and a repository-root profile. The library derives the release tag
from the selected module declaration and physical location; the table only from the selected module declaration and physical location; the table only
selects the corresponding profile and checkout directory. selects the corresponding profile and checkout directory.
@@ -9,19 +9,20 @@ Copy the contents of this directory into a consumer repository root, keeping
the listed module directories and profile paths at those locations, then run the listed module directories and profile paths at those locations, then run
the launcher from that checkout. the launcher from that checkout.
The sample modules declare Go 1.26.0, matching the current ReleaseKit consumer The sample modules declare Go 1.27.0, matching the current ReleaseKit consumer
minimum. minimum.
## Select the release tool ## Select the release tool
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
ReleaseKit version containing module-release support, then register that tool in ReleaseKit version that supports the selected source and rehearsal features,
each consumer module before running the launcher or workflow: then register that tool in each consumer module before running the launcher or
workflow. Version v0.11.0 supplies these interfaces:
```sh ```sh
: "${RELEASEKIT_TOOL_VERSION:?Select a ReleaseKit release with module-release support}" RELEASEKIT_TOOL_VERSION=v0.11.0
for module_dir in . integrations/ckconfig integrations/core/v2; do for module_dir in . integrations/ckconfig integrations/core/v2; do
go -C "$module_dir" get -tool "gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}" go -C "$module_dir" get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
go -C "$module_dir" mod tidy go -C "$module_dir" mod tidy
done done
``` ```
@@ -38,11 +39,12 @@ support and migration from earlier versions.
1. Local selector. 1. Local selector.
2. Shell pattern matched against a complete event tag. 2. Shell pattern matched against a complete event tag.
3. Repository-relative physical module directory (`.` means the root module). 3. Repository-relative tool module directory (`.` means the root module); `-` selects the installed tool from `.releasekit-version`.
4. Repository-relative profile path. 4. Repository-relative profile path.
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`, and The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`,
`integrations/core/v2.*`. The helper passes pattern text to the shell's `case` `integrations/core/v2.*`, and `configuration/20*`. Diagnostic tags select
the same row by their embedded selector. The helper passes pattern text to the shell's `case`
matcher without `eval`. A tag must match exactly one row; missing and ambiguous matcher without `eval`. A tag must match exactly one row; missing and ambiguous
matches are configuration errors. Module and profile paths may contain spaces. matches are configuration errors. Module and profile paths may contain spaces.
The `core-v2` row places the Go module physically under `integrations/core/v2` The `core-v2` row places the Go module physically under `integrations/core/v2`
@@ -68,15 +70,23 @@ Then select a module and semantic version with the shared launcher:
./release.sh root v1.2.3 ./release.sh root v1.2.3
./release.sh ckconfig v1.2.3 ./release.sh ckconfig v1.2.3
./release.sh core-v2 v2.1.0 ./release.sh core-v2 v2.1.0
./release.sh config 2026-12-05
``` ```
The launcher copies the selected module's `go.mod` and `go.sum` to temporary For a source-only row, the launcher installs the pinned tool with
`scripts/releasekit-tool` and passes the selected profile without interpreting
`-` as a source directory. The checked-in pin selects v0.11.0.
For Go rows, the launcher copies the selected module's `go.mod` and `go.sum` to temporary
alternate module files outside the checkout, resolves ReleaseKit from that alternate module files outside the checkout, resolves ReleaseKit from that
module's local dependency selection, and builds the tool there. It invokes module's local dependency selection, adds the CLI tool declaration to that
`publish` with the repository profile and `--expected-module` so the library temporary copy, and prepares its dependencies. It invokes the tool by its full
can verify that the profile agrees with the selected table row. The temporary package path with the alternate module file to run `publish` with the repository
files and tool are removed on exit. As with any `publish` invocation, commit the profile and `--expected-module` so the library can verify that the profile agrees with
selected module's release note and prepare its repository before publishing. the selected table row. Go builds and caches the executable and preserves its
exit status; the launcher removes the temporary metadata on exit. As with any
`publish` invocation, commit the selected module's release note and prepare its
repository before publishing.
If an integration depends on a sibling release, publish the dependency first, If an integration depends on a sibling release, publish the dependency first,
then publish the integration with the version that consumes it. For example, then publish the integration with the version that consumes it. For example,
@@ -86,11 +96,13 @@ This declaration does not infer dependency order or rerun the standard suite.
The maintained [Woodpecker example](woodpecker.yml) uses the same map and The maintained [Woodpecker example](woodpecker.yml) uses the same map and
selector for root, `ckconfig`, and major-version tags. It verifies and detaches selector for root, `ckconfig`, and major-version tags. It verifies and detaches
the literal event tag before selecting the module, copies that module's metadata the literal event tag before selecting the module, copies that module's metadata
outside the checkout, and builds the ReleaseKit version selected there. It then outside the checkout, and runs the selected ReleaseKit tool by its full package
uses `ci-deliver --prepared` with the mapped profile and expected physical module. path. It passes `ci-deliver --prepared`, the mapped profile, and the expected
physical module to the tool.
The `core-v2` profile demonstrates binary delivery; the other profiles are The `core-v2` profile demonstrates binary delivery; the other profiles are
page-only. Before enabling the workflow, configure each selected profile's page-only. Before enabling the workflow, replace the example forge and Woodpecker
`delivery` destination and add the Woodpecker repository secret destinations and repository ID in each profile. Configure separate local forge
and Woodpecker token files, then add the Woodpecker repository secret
`releasekit_gitea_token`; the workflow exposes it as `releasekit_gitea_token`; the workflow exposes it as
`RELEASEKIT_GITEA_TOKEN` only in the delivery step. `RELEASEKIT_GITEA_TOKEN` only in the delivery step.
@@ -108,9 +120,9 @@ modules:
: "${RELEASEKIT_SOURCE:?Set the absolute ReleaseKit checkout path}" : "${RELEASEKIT_SOURCE:?Set the absolute ReleaseKit checkout path}"
for module_dir in . integrations/ckconfig integrations/core/v2; do for module_dir in . integrations/ckconfig integrations/core/v2; do
go -C "$module_dir" mod edit \ go -C "$module_dir" mod edit \
-require=gitea.maximumdirect.net/eric/ReleaseKit@v0.0.0 \ -require=go.maximumdirect.net/releasekit@v0.0.0 \
-replace="gitea.maximumdirect.net/eric/ReleaseKit=$RELEASEKIT_SOURCE" \ -replace="go.maximumdirect.net/releasekit=$RELEASEKIT_SOURCE" \
-tool=gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit -tool=go.maximumdirect.net/releasekit/cmd/releasekit
GOTOOLCHAIN=local GOWORK=off go -C "$module_dir" mod tidy GOTOOLCHAIN=local GOWORK=off go -C "$module_dir" mod tidy
done done
``` ```
@@ -121,12 +133,40 @@ source and each selected product's module-local release note, then commit the
fixture and run the source-selected tool without publishing: fixture and run the source-selected tool without publishing:
```sh ```sh
go tool releasekit check --config releasekit-root.json v1.2.3 (
go -C integrations/ckconfig tool releasekit check --config releasekit-ckconfig.json v1.2.3 cd . || exit $?
go -C integrations/core/v2 tool releasekit check --config releasekit-core-v2.json v2.1.0 releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-root.json v1.2.3
)
(
cd ./integrations/ckconfig || exit $?
releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-ckconfig.json v1.2.3
)
(
cd ./integrations/core/v2 || exit $?
releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
go tool go.maximumdirect.net/releasekit/cmd/releasekit check --config releasekit-core-v2.json v2.1.0
)
``` ```
These commands use the repository-root profile paths even when invoked from a These commands use the repository-root profile paths even when invoked from a
child module. The core profile also verifies the native binary and injected child module. The core profile also verifies the native binary and injected
version. Prepared dependencies allow this verification with `GOPROXY=off` and version. Prepared dependencies allow this verification with `GOPROXY=off` and
`GOSUMDB=off`. `GOSUMDB=off`.
For an optional live rehearsal, select the corresponding tool and profile:
```sh
"$(./scripts/releasekit-tool)" test --config releasekit-config.json
go -C integrations/ckconfig tool go.maximumdirect.net/releasekit/cmd/releasekit test --config releasekit-ckconfig.json
```
A diagnostic ref contains the row selector and is verified against the
committed profile after bootstrap.

View File

@@ -0,0 +1,4 @@
{
"service": "example",
"enabled": true
}

View File

@@ -0,0 +1,3 @@
# Example Configuration 2026-12-05
Initial configuration release.

View File

@@ -1,3 +1,3 @@
module example.com/multi-module-consumer module example.com/multi-module-consumer
go 1.26.0 go 1.27.0

View File

@@ -1,3 +1,3 @@
module example.com/multi-module-consumer/integrations/ckconfig module example.com/multi-module-consumer/integrations/ckconfig
go 1.26.0 go 1.27.0

View File

@@ -1,3 +1,3 @@
module example.com/multi-module-consumer/integrations/core/v2 module example.com/multi-module-consumer/integrations/core/v2
go 1.26.0 go 1.27.0

View File

@@ -3,7 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {

View File

@@ -1,4 +1,5 @@
# selector<TAB>tag pattern<TAB>module directory<TAB>profile path # selector<TAB>tag pattern<TAB>tool module directory<TAB>profile path
root v[01].* . releasekit-root.json root v[01].* . releasekit-root.json
ckconfig integrations/ckconfig/v* integrations/ckconfig releasekit-ckconfig.json ckconfig integrations/ckconfig/v* integrations/ckconfig releasekit-ckconfig.json
core-v2 integrations/core/v2.* integrations/core/v2 releasekit-core-v2.json core-v2 integrations/core/v2.* integrations/core/v2 releasekit-core-v2.json
config configuration/20* - releasekit-config.json
1 # selector<TAB>tag pattern<TAB>module directory<TAB>profile path # selector<TAB>tag pattern<TAB>tool module directory<TAB>profile path
2 root root
3 ckconfig ckconfig
4 core-v2 core-v2
5 config

View File

@@ -19,6 +19,11 @@ trap 'rm -rf "$bootstrap_dir"' EXIT
tab=$(printf '\t') tab=$(printf '\t')
IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file" IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file"
if [ "$module_dir" = - ]; then
tool=$("$script_dir/scripts/releasekit-tool")
"$tool" publish --repo "$repository_dir" --config "$profile_path" "$version"
exit $?
fi
module_path=$repository_dir module_path=$repository_dir
if [ "$module_dir" != . ]; then if [ "$module_dir" != . ]; then
module_path=$repository_dir/$module_dir module_path=$repository_dir/$module_dir
@@ -31,18 +36,20 @@ else
: > "$bootstrap_dir/releasekit.sum" : > "$bootstrap_dir/releasekit.sum"
fi fi
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit releasekit_module=go.maximumdirect.net/releasekit
( (
cd "$module_path" cd "$module_path"
export GOWORK=off export GOWORK=off
export GOTOOLCHAIN=local export GOTOOLCHAIN=local
releasekit_host_os=$(go env GOHOSTOS) || exit $?
releasekit_host_arch=$(go env GOHOSTARCH) || exit $?
export GOOS="$releasekit_host_os" GOARCH="$releasekit_host_arch"
go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -m "$releasekit_module" go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -m "$releasekit_module"
go build -mod=mod -modfile="$bootstrap_dir/releasekit.mod" \ go mod edit -modfile="$bootstrap_dir/releasekit.mod" -tool="$releasekit_module/cmd/releasekit"
-o "$bootstrap_dir/releasekit" "$releasekit_module/cmd/releasekit" go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -deps "$releasekit_module/cmd/releasekit" > /dev/null
go tool -modfile="$bootstrap_dir/releasekit.mod" "$releasekit_module/cmd/releasekit" publish \
--repo "$repository_dir" \
--config "$profile_path" \
--expected-module "$module_dir" \
"$version"
) )
"$bootstrap_dir/releasekit" publish \
--repo "$repository_dir" \
--config "$profile_path" \
--expected-module "$module_dir" \
"$version"

View File

@@ -1,4 +1,28 @@
{ {
"product": "Example Consumer Integration", "product": "Example Consumer Integration",
"module_dir": "integrations/ckconfig" "module_dir": "integrations/ckconfig",
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "multi-product",
"credentials": {
"local": {
"token_file": ".releasekit/gitea-token"
},
"ci": {
"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"
}
}
},
"rehearsal": {
"selector": "ckconfig",
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
}
} }

View File

@@ -0,0 +1,25 @@
{
"product": "Example Configuration",
"source": {"dir": "configuration"},
"version": {"format": "date"},
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "multi-product",
"credentials": {
"local": {"token_file": ".releasekit/gitea-token"},
"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}
}
},
"rehearsal": {
"selector": "config",
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
}
}

View File

@@ -4,6 +4,32 @@
"build": { "build": {
"main_package": ".", "main_package": ".",
"binary_name": "core", "binary_name": "core",
"targets": ["linux/amd64"] "targets": [
"linux/amd64"
]
},
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "multi-product",
"credentials": {
"local": {
"token_file": ".releasekit/gitea-token"
},
"ci": {
"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"
}
}
},
"rehearsal": {
"selector": "core-v2",
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
} }
} }

View File

@@ -1,4 +1,28 @@
{ {
"product": "Example Consumer", "product": "Example Consumer",
"module_dir": "." "module_dir": ".",
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "multi-product",
"credentials": {
"local": {
"token_file": ".releasekit/gitea-token"
},
"ci": {
"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"
}
}
},
"rehearsal": {
"selector": "root",
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
}
} }

View File

@@ -0,0 +1,46 @@
#!/bin/sh
# Install the selected host tool once and print its durable absolute path.
set -eu
umask 077
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repository=$(git -C "$script_dir" rev-parse --show-toplevel)
pin=$repository/.releasekit-version
if [ ! -r "$pin" ]; then
printf 'ReleaseKit tool pin is unreadable: %s\n' "$pin" >&2
exit 2
fi
if version=$(LC_ALL=C awk '
{ gsub(/[[:space:]]+/, " "); for (i = 1; i <= NF; i++) { value = $i; count++ } }
END {
if (count != 1 || value !~ /^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/) exit 1
print value
}
' "$pin"); then :; else
printf 'ReleaseKit tool pin must contain one stable module version, such as v0.10.0: %s\n' "$pin" >&2
exit 2
fi
export GOWORK=off GOTOOLCHAIN=local
host_os=$(go env GOHOSTOS)
host_arch=$(go env GOHOSTARCH)
case $host_os in
windows) executable=releasekit.exe ;;
*) executable=releasekit ;;
esac
tool_dir=$repository/.releasekit/tools/$version/$host_os-$host_arch
tool=$tool_dir/$executable
if [ ! -x "$tool" ]; then
mkdir -p "$tool_dir"
temporary=$(mktemp -d "$tool_dir/.install.XXXXXX")
trap 'rm -rf "$temporary"' EXIT
trap 'exit 1' HUP INT TERM
if GOBIN=$temporary GOOS=$host_os GOARCH=$host_arch go install "go.maximumdirect.net/releasekit/cmd/releasekit@$version"; then :; else
status=$?
exit "$status"
fi
if [ ! -x "$temporary/$executable" ]; then
printf 'ReleaseKit installation produced no executable\n' >&2
exit 1
fi
mv "$temporary/$executable" "$tool"
fi
printf '%s\n' "$tool"

View File

@@ -14,6 +14,26 @@ case "$mode" in
*) usage ;; *) usage ;;
esac esac
# A diagnostic ref carries its dispatch selector before the tool is available.
if [ "$mode" = tag ]; then
case "$value" in
releasekit-test/*)
diagnostic=${value#releasekit-test/}
selector=${diagnostic%%/*}
attempt=${diagnostic#*/}
case "$attempt" in
*[!0-9a-f]*|'') ;;
*)
if [ "${#attempt}" -eq 32 ] && [ -n "$selector" ] && [ "$diagnostic" != "$attempt" ]; then
mode=selector
value=$selector
fi
;;
esac
;;
esac
fi
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd) script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
mapping=${RELEASEKIT_MODULE_MAP:-$script_dir/release-modules.tsv} mapping=${RELEASEKIT_MODULE_MAP:-$script_dir/release-modules.tsv}
[ -f "$mapping" ] || { echo "module map not found: $mapping" >&2; exit 2; } [ -f "$mapping" ] || { echo "module map not found: $mapping" >&2; exit 2; }

Some files were not shown because too many files have changed in this diff Show More