174 Commits

Author SHA1 Message Date
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
7d033c5ca1 Prepare v0.4.2 release notes and retire the completed bug report 2026-10-11 02:10:48 +00:00
f076da99b6 Resolve annotated tag events in Woodpecker delivery workflows 2026-10-11 02:07:54 +00:00
3f2a1a1052 Document Audita's annotated tag delivery failure 2026-10-11 01:54:26 +00:00
2d5a8110c6 Prepare v0.4.1 release notes 2026-10-11 00:57:29 +00:00
d42727b038 Map every concurrency audit finding to its roadmap correction 2026-10-11 00:17:06 +00:00
059a79525a Synchronize delivery test fixtures and record the concurrency audit 2026-10-11 00:07:25 +00:00
6176971307 Plan synchronization of delivery test fixtures 2026-10-10 23:56:12 +00:00
8f6e72b0b8 Report source delivery test fixture races 2026-10-10 23:52:34 +00:00
b96262eb0c Remove completed module release roadmaps and review notes 2026-10-10 15:44:03 +00:00
5a0bc6f78b Write release notes and migration guidance for v0.4.0 2026-10-10 15:39:47 +00:00
f27abcb53e Read blob sizes only for selected validation inputs 2026-10-10 15:29:29 +00:00
6c7b77970b Keep committed release note reads offline 2026-10-10 15:20:03 +00:00
80d88a0352 Reuse local asset verification during delivery uploads 2026-10-10 15:17:18 +00:00
c0a3f55f12 Resolve module paths consistently through symlinks 2026-10-10 15:13:00 +00:00
7216fb5f98 Record findings from the follow-up repository audit 2026-10-10 15:06:10 +00:00
6b0b8ce6de Align module release documentation with implemented behavior 2026-10-10 14:36:56 +00:00
8112a001d2 Select module files with ancestor boundary lookups 2026-10-10 14:29:27 +00:00
8552f92ddb Separate example setup from synthetic test releases 2026-10-10 14:27:47 +00:00
c09c7a2ac7 Preserve literal characters in shared file paths 2026-10-10 14:20:54 +00:00
54cc6baf95 Resolve committed module identity from Git objects 2026-10-10 14:20:09 +00:00
7eebbbbfc3 Accept valid local main module paths 2026-10-10 14:12:50 +00:00
c8eb64adec Rediscover Go settings only when Go work needs them 2026-10-10 14:11:48 +00:00
9333573cd8 Accept equivalent checkout paths in build receipts 2026-10-10 14:09:37 +00:00
d44ff1260d Resolve prebuilt assets from the selected module 2026-10-10 14:08:11 +00:00
f059fef320 Preserve build errors and available failure evidence 2026-10-10 14:05:39 +00:00
7555d3e6c9 Resolve source operations from the Git checkout root 2026-10-10 14:03:57 +00:00
750632f80e Record findings from the module release review 2026-10-10 13:53:04 +00:00
90559fe01b Complete module release documentation 2026-10-10 04:03:42 +00:00
b49c1f379e Add mapped multi-module delivery workflow 2026-10-10 03:55:05 +00:00
cd828dc06d Add multi-module release launcher example 2026-10-10 03:46:12 +00:00
c9879cffa2 Use prepared checkouts in root workflows 2026-10-10 03:41:36 +00:00
c0cc50b127 Support full-tag prepared CI delivery 2026-10-10 03:40:10 +00:00
f837871b77 Map CLI profiles to selected modules 2026-10-10 03:30:34 +00:00
d06b62efe2 Version and bind module build receipts 2026-10-10 03:16:40 +00:00
926b74bc0b Deliver module releases to full-tag pages 2026-10-10 03:10:43 +00:00
fdce017aff Build from the selected module 2026-10-10 02:53:38 +00:00
8350cbf9c9 Run validation in the selected module 2026-10-10 02:43:23 +00:00
02896b6e12 Apply module scope to file validation checks 2026-10-10 02:32:28 +00:00
3a99536f9c Select committed validation inputs by module 2026-10-10 02:25:12 +00:00
fa34cbaff3 Publish and reconcile complete module tags 2026-10-10 02:18:02 +00:00
3e516d0ac1 Carry module identity through candidate results 2026-10-10 02:15:13 +00:00
f99fb59cd4 Derive module release identity and accept full Git tags 2026-10-10 02:10:18 +00:00
dbfae9ea81 Plan implementation of individual module releases 2026-10-10 01:34:33 +00:00
f33023f8e0 Resolve standalone build identity from working-tree declarations 2026-10-10 01:21:19 +00:00
5847f40ab5 Record module release ownership rules and the open build decision 2026-10-10 01:19:27 +00:00
f656a2d2e9 Preserve simple consumers and resolve module identity once 2026-10-10 01:05:55 +00:00
578503c1ca Plan a clean module release API and receipt cutover 2026-10-10 01:02:17 +00:00
39dca97f9b Define shared file selection for module releases 2026-10-10 00:59:23 +00:00
283f62813f Plan complete module support across release operations 2026-10-10 00:49:13 +00:00
f89bdf7edf Plan module-scoped release support 2026-10-09 16:19:05 +00:00
86c1da2cf5 Accept ADR 0005 for module-scoped releases 2026-10-09 16:15:54 +00:00
e43df4416e Remove completed roadmaps and repair the benchmark link 2026-10-09 03:34:31 +00:00
9b51447acd Align COPYRIGHT with the upstream library template 2026-10-09 03:32:52 +00:00
80ec9e3fb4 Adopt release policy 1.6 and preserve local release conventions 2026-10-09 03:29:37 +00:00
86b73db71f Raise the Go minimum to 1.26.0 2026-10-09 03:20:21 +00:00
52e3a389bb Add release notes and upgrade guidance for v0.3.0 2026-10-09 03:17:16 +00:00
cf9e451ecd Reconcile completed performance and remediation roadmaps 2026-10-09 03:09:21 +00:00
6376ef23f1 Measure output capture allocations for chunked writes 2026-10-09 03:08:51 +00:00
7d92c477c2 Attribute reader shutdown failures to checks that read content 2026-10-09 03:07:13 +00:00
6eec022bb0 Preserve validation cancellation during reader shutdown 2026-10-09 03:06:06 +00:00
15dd58f5ac Record performance implementation review findings 2026-10-09 02:15:56 +00:00
df064bd1d3 Record final performance implementation results 2026-10-09 01:55:56 +00:00
42569b4af2 Cache runtime version metadata fallback 2026-10-09 01:46:07 +00:00
50d3573257 Transfer completed Go output without copies 2026-10-09 01:44:33 +00:00
39196a525c Use one delivery asset verification pass 2026-10-09 01:40:43 +00:00
cfd8ba7cb2 Reuse parsed validation content by blob 2026-10-09 01:37:33 +00:00
182da397e3 Release validation source bytes after checks 2026-10-09 01:33:21 +00:00
a3e993d95a Scope candidate blob readers to validation 2026-10-09 01:30:30 +00:00
33e10635b6 Add local batched Git blob reader 2026-10-09 01:23:00 +00:00
618a7c9dd3 Add piped child process support 2026-10-09 01:17:58 +00:00
41e58ef894 Measure delivery output and version costs 2026-10-09 01:11:07 +00:00
29e1bab228 Record validation performance baseline 2026-10-09 01:02:05 +00:00
ca571aca4f Plan the computational efficiency implementation 2026-10-09 00:42:08 +00:00
ff90510c38 Record the computational efficiency roadmap 2026-10-09 00:10:13 +00:00
db9e24f7dc Document versioned Go tool adoption for CLI consumers 2026-10-08 16:42:18 +00:00
4bb480f990 Separate the Go minimum from the release build toolchain 2026-10-08 16:29:48 +00:00
d51a0ada5e Record successful PromptKit cache recovery 2026-10-08 16:10:23 +00:00
f2124b3b7b Isolate synthetic module downloads in workflow tests 2026-10-08 14:30:08 +00:00
ae0e4a0263 Document checksum recovery and synthetic module cache isolation 2026-10-08 14:25:46 +00:00
c7942210d5 Record PromptKit checksum investigation findings 2026-10-08 14:23:24 +00:00
c339872bfe Report PromptKit's v0.2.0 checksum mismatch 2026-10-08 14:15:00 +00:00
174 changed files with 17465 additions and 3519 deletions

View File

@@ -18,8 +18,3 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details. GNU Lesser General Public License for more details.
Third-party code and assets are subject to their respective license terms. Third-party code and assets are subject to their respective license terms.
Policy documents adapted from Standard Repository Policies, the root AGENTS.md
orientation, and the Policy Reading Guide in docs/development.md remain licensed
under CC-BY-SA-4.0. See docs/oss/attribution.md for the affected material,
upstream credit, and license links.

View File

@@ -8,8 +8,22 @@ tagged-source delivery API, and the `version`, `check`, `publish`, `build`,
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.
See the [v0.1.0 release note](docs/releases/v0.1.0.md) for the initial baseline The Go module is `go.maximumdirect.net/releasekit`. The
and installation commands. [adoption guide](docs/consumers/adoption.md#migrating-from-the-original-module-path)
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 one Go module within a repository. The repository
root remains the default; a selected module's declared import path and physical
directory determine its complete Git tag and module-local release note. See the
[candidate check](docs/consumers/check.md),
[publication](docs/consumers/publish.md), and
[multi-module example](examples/multi-module/).
See the [consumer adoption guide](docs/consumers/adoption.md) to add ReleaseKit
as a versioned Go tool or package dependency, and the
[v0.1.0 release note](docs/releases/v0.1.0.md) for the initial baseline.
Run the offline Go test suite from the repository root with: Run the offline Go test suite from the repository root with:
@@ -42,6 +56,8 @@ failure recovery.
## Documentation ## Documentation
- [Consumer adoption](docs/consumers/adoption.md): versioned CLI tool and Go API
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): the `version`, `check`, `publish`, `build`,
@@ -65,6 +81,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,9 +2,14 @@ package releasekit
import ( import (
"context" "context"
"fmt"
"io" "io"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" "go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"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.
@@ -22,11 +27,14 @@ type BuildSpec struct {
// BuildRequest contains the source and output settings for Build. // BuildRequest contains the source and output settings for Build.
type BuildRequest struct { type BuildRequest struct {
RepositoryDir string // source repository whose current HEAD is recorded. RepositoryDir string // directory within the source Git checkout whose HEAD is recorded.
Version string // stable vMAJOR.MINOR.PATCH value injected at link time. // ModuleDir selects a repository-relative module directory; empty selects
Spec BuildSpec // application package, artifact name, and targets. // the repository root.
OutputDir string // output location; empty selects <repository>/dist. ModuleDir string
Output io.Writer // optional build progress destination. Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
Spec BuildSpec // application package, artifact name, and targets.
OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist.
Output io.Writer // optional build progress destination.
} }
// BuildArtifact identifies one generated binary and its SHA-256 digest. // BuildArtifact identifies one generated binary and its SHA-256 digest.
@@ -40,6 +48,9 @@ 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.
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. 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.
@@ -53,33 +64,60 @@ type BuildResult struct {
Compiler string // output of the selected local Go toolchain's version command. Compiler string // output of the selected local Go toolchain's version command.
} }
// Build compiles the selected targets with Version injected through buildinfo. // Build resolves the selected module's working-tree identity, then compiles the
// It uses the available compatible local Go toolchain, applies ReleaseKit's // selected targets with Version injected through buildinfo. It uses the
// readonly offline build settings, preserves effective cache and tool settings, // available compatible local Go toolchain, applies ReleaseKit's readonly
// and verifies the version command on the Go host before succeeding. An empty // offline build settings, preserves effective cache and tool settings, and
// target set records source identity without running the Go toolchain. Errors // verifies the version command on the Go host before succeeding. Relative
// return partial build facts in the result. // output paths use ModuleDir; an empty path selects its dist directory. An
// empty target set records source identity without running the Go toolchain.
// Errors return partial build facts in the result.
func Build(ctx context.Context, request BuildRequest) (BuildResult, error) { func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
result, err := internalbuild.Build(ctx, internalbuild.Request{ spec := *internalBuildSpec(&request.Spec)
RepositoryDir: request.RepositoryDir, result := internalbuild.Result{Version: request.Version}
Version: request.Version, failure := func(err error) (BuildResult, error) {
Spec: *internalBuildSpec(&request.Spec), result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
OutputDir: request.OutputDir, return publicBuildResult(result), err
Output: request.Output, }
if !versioncontract.ValidStableVersion(request.Version) {
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
}
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
if err != nil {
return failure(err)
}
result.RepositoryDir = repositoryDir
identity, err := releaseidentity.FromWorkingTree(ctx, repositoryDir, request.ModuleDir, request.Version)
result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag
if err != nil {
return failure(err)
}
result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{
Identity: identity,
Spec: spec,
OutputDir: request.OutputDir,
Output: request.Output,
}) })
return publicBuildResult(result), err
}
func publicBuildResult(result internalbuild.Result) BuildResult {
public := BuildResult{ public := BuildResult{
RepositoryDir: result.RepositoryDir, RepositoryDir: result.RepositoryDir,
ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath,
Tag: result.Tag,
CandidateCommit: result.CandidateCommit, CandidateCommit: result.CandidateCommit,
SourceVerified: result.SourceVerified, SourceVerified: result.SourceVerified,
Version: result.Version, Version: result.Version,
MainPackage: result.MainPackage, MainPackage: result.Settings.MainPackage,
BinaryName: result.BinaryName, BinaryName: result.Settings.BinaryName,
OutputDir: result.OutputDir, OutputDir: result.OutputDir,
Compiler: result.Compiler, Compiler: result.Compiler,
Targets: make([]Target, 0, len(result.Targets)), Targets: make([]Target, 0, len(result.Settings.Targets)),
Artifacts: make([]BuildArtifact, 0, len(result.Artifacts)), Artifacts: make([]BuildArtifact, 0, len(result.Artifacts)),
} }
for _, target := range result.Targets { for _, target := range result.Settings.Targets {
public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch}) public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch})
} }
for _, artifact := range result.Artifacts { for _, artifact := range result.Artifacts {
@@ -90,7 +128,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
SHA256: artifact.SHA256, SHA256: artifact.SHA256,
}) })
} }
return public, err return public
} }
func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec { func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
@@ -105,10 +143,9 @@ func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
} }
func internalBuildResult(result BuildResult) *internalbuild.Result { func internalBuildResult(result BuildResult) *internalbuild.Result {
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Version: result.Version, MainPackage: result.MainPackage, BinaryName: result.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler} input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
for _, target := range result.Targets { settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch}) 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 _, 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,67 @@ 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) {
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{
RepositoryDir: filepath.Join(t.TempDir(), "absent"), Version: "bad-version", Spec: spec,
})
if !errors.Is(err, releasekit.ErrInvalidVersion) || invalid.Version != "bad-version" || invalid.MainPackage != spec.MainPackage || invalid.BinaryName != spec.BinaryName || len(invalid.Targets) != 1 {
t.Fatalf("invalid version result = %#v, error = %v", invalid, err)
}
repo := newPublishFixture(t)
writeFile(t, repo.work, "nested/go.mod", "go 1.26.0\n")
failed, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repo.work, ModuleDir: "nested", Version: "v1.2.3", Spec: spec,
})
if err == nil || failed.RepositoryDir != repo.work || failed.ModuleDir != filepath.Join(repo.work, "nested") || failed.Version != "v1.2.3" || failed.MainPackage != spec.MainPackage || failed.BinaryName != spec.BinaryName || len(failed.Targets) != 1 || failed.SourceVerified {
t.Fatalf("declaration failure = %#v, error = %v", failed, err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := releasekit.Build(ctx, releasekit.BuildRequest{RepositoryDir: repo.work, Version: "v1.2.3", Spec: spec}); !errors.Is(err, context.Canceled) {
t.Fatalf("canceled build error = %v", err)
}
}
func TestBuildCreatesSelectedTargetsAndInjectsVersion(t *testing.T) { func TestBuildCreatesSelectedTargetsAndInjectsVersion(t *testing.T) {
repository := newBuildConsumer(t, `package main repository := newBuildConsumer(t, `package main
@@ -25,7 +83,7 @@ import (
"fmt" "fmt"
"os" "os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo" "go.maximumdirect.net/releasekit/buildinfo"
) )
func main() { func main() {
@@ -104,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() {
@@ -115,7 +173,7 @@ func main() {
t.Setenv("GOARCH", "arm64") t.Setenv("GOARCH", "arm64")
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{ result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, RepositoryDir: repository,
Version: "v2.3.4", Version: "v1.2.3",
Spec: releasekit.BuildSpec{ Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app", MainPackage: "./cmd/app",
BinaryName: "fixture", BinaryName: "fixture",
@@ -126,7 +184,7 @@ func main() {
if err != nil { if err != nil {
t.Fatalf("Build() error = %v; partial result = %#v", err, result) t.Fatalf("Build() error = %v; partial result = %#v", err, result)
} }
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v2.3.4-windows-arm64.exe" { if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v1.2.3-windows-arm64.exe" {
t.Fatalf("build artifacts = %#v", result.Artifacts) t.Fatalf("build artifacts = %#v", result.Artifacts)
} }
} }
@@ -136,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()) } }
`) `)
@@ -166,7 +224,7 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixt
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{ result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository, RepositoryDir: repository,
Version: "v2.3.4", Version: "v1.2.3",
Spec: releasekit.BuildSpec{ Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app", MainPackage: "./cmd/app",
BinaryName: "fixture", BinaryName: "fixture",
@@ -242,9 +300,148 @@ func main() {}
} }
} }
func TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput(t *testing.T) {
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
moduleDir := filepath.Join(repository, "integrations", "nested")
writeNestedBuildConsumer(t, repository, "integrations/nested", "example.com/nestedbuild", `package main
import (
"fmt"
"os"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() {
if len(os.Args) == 2 && os.Args[1] == "version" {
if logPath := os.Getenv("RELEASEKIT_SMOKE_LOG"); logPath != "" {
if executable, err := os.Executable(); err == nil {
_ = os.WriteFile(logPath, []byte(executable), 0o600)
}
}
fmt.Printf("nested-app %s\n", buildinfo.Version())
}
}
`)
outputDirectory := "artifacts"
crossTarget := releasekit.Target{OS: "darwin", Arch: "arm64"}
if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
crossTarget = releasekit.Target{OS: "linux", Arch: "amd64"}
}
nativeTarget := releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
ModuleDir: "integrations/nested",
Version: "v1.2.3",
Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app",
BinaryName: "nested-app",
Targets: []releasekit.Target{nativeTarget, crossTarget},
},
OutputDir: outputDirectory,
})
if err != nil {
t.Fatalf("Build() error = %v; result = %#v", err, result)
}
if result.ModuleDir != moduleDir || result.ModulePath != "example.com/nestedbuild" || result.Tag != "integrations/nested/v1.2.3" {
t.Fatalf("nested build identity = %#v", result)
}
wantOutput := filepath.Join(moduleDir, outputDirectory)
if result.OutputDir != wantOutput || len(result.Artifacts) != 2 {
t.Fatalf("nested build output = %#v, want directory %q and two artifacts", result, wantOutput)
}
var native string
for _, artifact := range result.Artifacts {
if filepath.Dir(artifact.Path) != wantOutput || !strings.Contains(artifact.Filename, "nested-app-v1.2.3-") {
t.Fatalf("nested artifact = %#v", artifact)
}
if artifact.Target == nativeTarget {
native = artifact.Path
}
}
if native == "" {
t.Fatalf("native artifact missing from %#v", result.Artifacts)
}
if output, err := exec.Command(native, "version").CombinedOutput(); err != nil || string(output) != "nested-app v1.2.3\n" {
t.Fatalf("nested native version = %q, error = %v", output, err)
}
localTemporary := filepath.Join(repository, "source-temporary")
if err := os.Mkdir(localTemporary, 0o700); err != nil {
t.Fatal(err)
}
crossOutput := filepath.Join(t.TempDir(), "cross-artifacts")
smokeLog := filepath.Join(t.TempDir(), "smoke-executable")
t.Setenv("RELEASEKIT_SMOKE_LOG", smokeLog)
t.Setenv("TMPDIR", localTemporary)
smokeResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
ModuleDir: "integrations/nested",
Version: "v1.2.3",
Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app",
BinaryName: "nested-app",
Targets: []releasekit.Target{crossTarget},
},
OutputDir: crossOutput,
})
if err != nil || len(smokeResult.Artifacts) != 1 {
t.Fatalf("nested cross build with source-local TMPDIR = %#v, %v", smokeResult, err)
}
smokePathBytes, err := os.ReadFile(smokeLog)
if err != nil {
t.Fatalf("read native smoke executable path: %v", err)
}
smokePath := string(smokePathBytes)
relativeSmokePath, err := filepath.Rel(repository, smokePath)
if err != nil || relativeSmokePath == "." || (!filepath.IsAbs(relativeSmokePath) && relativeSmokePath != ".." && !strings.HasPrefix(relativeSmokePath, ".."+string(filepath.Separator))) {
t.Fatalf("native smoke output path %q is inside repository %q (relative %q, error %v)", smokePath, repository, relativeSmokePath, err)
}
if _, err := os.Stat(smokePath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("native smoke output %q was not removed: %v", smokePath, err)
}
remaining, err := os.ReadDir(localTemporary)
if err != nil || len(remaining) != 0 {
t.Fatalf("native smoke output remained in source-local TMPDIR: %v %v", remaining, err)
}
emptyResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
ModuleDir: "integrations/nested",
Version: "v1.2.3",
})
if err != nil || emptyResult.Compiler != "" || emptyResult.OutputDir != filepath.Join(moduleDir, "dist") {
t.Fatalf("nested empty build = %#v, %v", emptyResult, err)
}
if _, err := os.Stat(emptyResult.OutputDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("empty nested build created dist: %v", err)
}
}
func TestBuildResolvesDirtyWorkingTreeDeclaration(t *testing.T) {
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
declarationPath := filepath.Join(repository, "go.mod")
contents, err := os.ReadFile(declarationPath)
if err != nil {
t.Fatal(err)
}
updated := strings.Replace(string(contents), "module example.com/buildfixture", "module example.com/changedbuild", 1)
if updated == string(contents) {
t.Fatal("fixture module declaration was not replaced")
}
writeBuildFixture(t, repository, "go.mod", updated)
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
Version: "v1.2.3",
})
if err != nil {
t.Fatal(err)
}
if result.ModulePath != "example.com/changedbuild" || result.Tag != "v1.2.3" {
t.Fatalf("dirty declaration identity = %#v", result)
}
}
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)
@@ -324,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 (
@@ -432,6 +684,21 @@ func TestBuildCancellationReturnsCompletedArtifacts(t *testing.T) {
func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) { func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
repository := newPublishFixture(t) repository := newPublishFixture(t)
realGo, err := exec.LookPath("go")
if err != nil {
t.Fatal(err)
}
goShimDir := t.TempDir()
goLog := filepath.Join(goShimDir, "go-commands")
goShim := filepath.Join(goShimDir, "go")
shimSource := "#!/bin/sh\nset -eu\nprintf '%s\\n' \"$*\" >> \"$RELEASEKIT_REAL_GO_LOG\"\nexec \"$RELEASEKIT_REAL_GO\" \"$@\"\n"
if err := os.WriteFile(goShim, []byte(shimSource), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_REAL_GO", realGo)
t.Setenv("RELEASEKIT_REAL_GO_LOG", goLog)
t.Setenv("GOENV", "off")
t.Setenv("PATH", goShimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
writeFile(t, repository.work, "guide.md", "# Guide\n[section](#guide)\n") writeFile(t, repository.work, "guide.md", "# Guide\n[section](#guide)\n")
gitRun(t, repository.work, "add", "guide.md") gitRun(t, repository.work, "add", "guide.md")
gitRun(t, repository.work, "commit", "-m", "add Markdown guide") gitRun(t, repository.work, "commit", "-m", "add Markdown guide")
@@ -439,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()) } }
`) `)
@@ -465,6 +732,26 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixt
if validations != 1 || candidate.Commit != gitText(t, repository.work, "rev-parse", "HEAD") { if validations != 1 || candidate.Commit != gitText(t, repository.work, "rev-parse", "HEAD") {
t.Fatalf("candidate = %#v, validation calls = %d", candidate, validations) t.Fatalf("candidate = %#v, validation calls = %d", candidate, validations)
} }
goCommands, err := os.ReadFile(goLog)
if err != nil {
t.Fatal(err)
}
var discoveries, suites, builds, versions int
for _, command := range strings.Split(strings.TrimSpace(string(goCommands)), "\n") {
switch {
case strings.HasPrefix(command, "env "):
discoveries++
case strings.HasPrefix(command, "test "):
suites++
case strings.HasPrefix(command, "build "):
builds++
case command == "version":
versions++
}
}
if discoveries != 2 || suites != 1 || builds != 1 || versions != 1 {
t.Fatalf("Go commands = %q; discovery=%d suite=%d build=%d version=%d, want 2, 1, 1, 1", goCommands, discoveries, suites, builds, versions)
}
if got := gitText(t, repository.work, "status", "--porcelain"); got != "" { if got := gitText(t, repository.work, "status", "--porcelain"); got != "" {
t.Fatalf("candidate build dirtied worktree: %s", got) t.Fatalf("candidate build dirtied worktree: %s", got)
} }
@@ -516,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.25.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.26.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")
@@ -528,13 +815,25 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
return repository return repository
} }
func writeNestedBuildConsumer(t *testing.T, repository, moduleDir, modulePath, mainSource string) string {
t.Helper()
root, err := filepath.Abs(".")
if err != nil {
t.Fatal(err)
}
module := fmt.Sprintf("module %s\n\ngo 1.26.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, "cmd/app/main.go")), mainSource)
return filepath.Join(repository, filepath.FromSlash(moduleDir))
}
func prepareCandidateBuild(t *testing.T, repository, mainSource string) { func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
t.Helper() t.Helper()
root, err := filepath.Abs(".") root, err := filepath.Abs(".")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.25.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.26.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)
@@ -568,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"} {
@@ -606,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)
} }
@@ -629,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.25.0 go 1.26.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()) }

View File

@@ -4,10 +4,10 @@ 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 a version that is not stable vMAJOR.MINOR.PATCH.
@@ -18,21 +18,30 @@ 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. // validation. ModuleDir is the absolute selected module directory, ModulePath
// is its declared Go import path, and Tag is the complete derived Git tag.
type Candidate struct { type Candidate struct {
RepositoryDir string RepositoryDir string
ModuleDir string
ModulePath string
Tag string
Commit string Commit string
Version string Version string // selected stable semantic version.
} }
// ReleaseRequest contains the inputs used to validate and optionally build one // ReleaseRequest contains the inputs used to validate and optionally build one
// local candidate. Remote is retained for publication operations; Check makes // local candidate. Remote is retained for publication operations; Check makes
// no remote availability claim. // no remote availability claim.
type ReleaseRequest struct { type ReleaseRequest struct {
// RepositoryDir names a directory within the source Git checkout. Operations
// resolve its root before applying repository-relative selections.
RepositoryDir string RepositoryDir string
Product string // ModuleDir selects a repository-relative module directory; empty selects
Version string // the repository root.
Remote string ModuleDir string
Product string
Version string // stable semantic version, 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.
@@ -46,9 +55,24 @@ type ReleaseRequest struct {
} }
// ValidationSpec selects optional shared validation checks. Its zero value // ValidationSpec selects optional shared validation checks. Its zero value
// preserves the current validation behavior. // preserves the current validation behavior. File checks inspect the selected
// module and shared-file inputs. Independent nested modules form automatic
// input boundaries; vendored files remain included. Referenced destinations
// 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 {
Go GoValidationSpec // SharedFiles adds repository-relative committed files to optional file
// checks. Nil selects the optional root COPYRIGHT, LICENSE, and
// docs/oss/attribution.md defaults; an empty non-nil slice selects none.
// Explicit files replace the defaults and must exist even when file checks
// are off.
SharedFiles []string
// 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
@@ -76,7 +100,7 @@ type FileSizeValidationSpec struct {
// LimitBytes is the maximum decimal byte count. Nil selects 1,000,000; // LimitBytes is the maximum decimal byte count. Nil selects 1,000,000;
// zero is a zero-byte limit, and negative values are invalid. // zero is a zero-byte limit, and negative values are invalid.
LimitBytes *int64 LimitBytes *int64
// Exclusions are literal repository-relative file or directory paths. // Exclusions are literal module-relative file or directory paths.
// A directory exclusion includes committed descendants. // A directory exclusion includes committed descendants.
Exclusions []string Exclusions []string
} }
@@ -88,7 +112,8 @@ type ModuleDistributionValidationSpec struct {
// nested paths and symlink entries. It does not select Go's test workspace. // nested paths and symlink entries. It does not select Go's test workspace.
WorkspaceFiles bool WorkspaceFiles bool
// LocalReplacements rejects filesystem replacements in committed go.mod // LocalReplacements rejects filesystem replacements in committed go.mod
// declarations, including nested modules. It does not select Go's workspace. // declarations in the selected inputs, including vendor and explicit shared
// files. It does not select Go's workspace.
LocalReplacements bool LocalReplacements bool
} }
@@ -107,21 +132,26 @@ 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 committed note matching Product and Version, // worktree and index on main, a selected module declaration and module-local
// and an unused local tag. It always runs the offline Go test suite with the // committed note matching Product and Version, and an unused local tag. An
// available compatible local Go toolchain and Go host target, then calls // empty ModuleDir selects the repository root. The module declaration
// determines the full Git tag for the semantic Version. It always runs the
// 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
// files after formatting. Its zero value disables that distribution check and // files after formatting. Its zero value disables that distribution check and
// does not change Go's workspace environment. // does not change Go's workspace environment.
// Validation.ModuleDistribution.LocalReplacements parses committed go.mod // Validation.ModuleDistribution.LocalReplacements parses committed go.mod
// declarations, including nested modules, and rejects filesystem replacements // declarations in the selected inputs and rejects filesystem replacements
// after workspace-file inspection. Its zero value disables that check. // after workspace-file inspection. Its zero value disables that check.
// Validation.FileSize checks each selected committed blob after module // Validation.FileSize checks each selected committed blob after module
// distribution checks. Its nil value disables size checks; an empty object // distribution checks. Its nil value disables size checks; an empty object
@@ -139,25 +169,35 @@ type GoValidationSpec struct {
func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) { func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
checked, err := candidate.Check(ctx, candidateRequest(request)) checked, err := candidate.Check(ctx, candidateRequest(request))
if err != nil { if err != nil {
return Candidate{}, convertValidationError(err) return publicCandidate(checked), convertValidationError(err)
} }
return publicCandidate(checked), nil
}
func publicCandidate(checked candidate.Candidate) Candidate {
return Candidate{ return Candidate{
RepositoryDir: checked.RepositoryDir, RepositoryDir: checked.RepositoryDir,
ModuleDir: checked.ModuleDir,
ModulePath: checked.ModulePath,
Tag: checked.Tag,
Commit: checked.Commit, Commit: checked.Commit,
Version: checked.Version, Version: checked.Version,
}, nil }
} }
func candidateRequest(request ReleaseRequest) candidate.Request { func candidateRequest(request ReleaseRequest) candidate.Request {
fileSize := internalFileSizeSettings(request.Validation.FileSize) fileSize := internalFileSizeSettings(request.Validation.FileSize)
result := candidate.Request{ result := candidate.Request{
RepositoryDir: request.RepositoryDir, RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir,
Product: request.Product, Product: request.Product,
Version: request.Version, Version: request.Version,
Validation: validation.Settings{ Validation: validation.Settings{
Race: request.Validation.Go.Race, Race: request.Validation.Go.Race,
FullVet: request.Validation.Go.FullVet, FullVet: request.Validation.Go.FullVet,
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)), CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
ForbiddenFiles: copyStringSlice(request.Validation.ForbiddenFiles),
GoFormat: request.Validation.GoFormat, GoFormat: request.Validation.GoFormat,
Markdown: internalMarkdownSettings(request.Validation.Markdown), Markdown: internalMarkdownSettings(request.Validation.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{ ModuleDistribution: validation.ModuleDistributionSettings{
@@ -176,6 +216,13 @@ func candidateRequest(request ReleaseRequest) candidate.Request {
return result return result
} }
func copyStringSlice(values []string) []string {
if values == nil {
return nil
}
return append(make([]string, 0, len(values)), values...)
}
func internalMarkdownSettings(spec *MarkdownValidationSpec) *validation.MarkdownSettings { func internalMarkdownSettings(spec *MarkdownValidationSpec) *validation.MarkdownSettings {
if spec == nil { if spec == nil {
return nil return nil
@@ -203,10 +250,6 @@ func candidateChecks(checks func(context.Context, Candidate) error) func(context
return nil return nil
} }
return func(ctx context.Context, captured candidate.Candidate) error { return func(ctx context.Context, captured candidate.Candidate) error {
return checks(ctx, Candidate{ return checks(ctx, publicCandidate(captured))
RepositoryDir: captured.RepositoryDir,
Commit: captured.Commit,
Version: captured.Version,
})
} }
} }

38
check_request_test.go Normal file
View File

@@ -0,0 +1,38 @@
package releasekit
import "testing"
func TestCandidateRequestPreservesSharedFileSelection(t *testing.T) {
for _, tt := range []struct {
name string
input []string
wantNil bool
wantValues []string
}{
{name: "omitted defaults", input: nil, wantNil: true},
{name: "explicit empty", input: []string{}, wantValues: []string{}},
{name: "explicit paths", input: []string{"LICENSE", "docs/shared.md"}, wantValues: []string{"LICENSE", "docs/shared.md"}},
} {
t.Run(tt.name, func(t *testing.T) {
request := ReleaseRequest{Validation: ValidationSpec{SharedFiles: tt.input}}
mapped := candidateRequest(request).Validation.SharedFiles
if (mapped == nil) != tt.wantNil {
t.Fatalf("mapped shared files nil=%t, want %t", mapped == nil, tt.wantNil)
}
if len(mapped) != len(tt.wantValues) {
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
}
for index, value := range tt.wantValues {
if mapped[index] != value {
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
}
}
if len(tt.input) != 0 {
request.Validation.SharedFiles[0] = "changed"
if mapped[0] != tt.wantValues[0] {
t.Fatal("mapped shared-file selection aliases the caller's slice")
}
}
})
}
}

View File

@@ -0,0 +1,103 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
for _, tt := range []struct {
name, module string
absolute bool
alias bool
}{
{name: "root relative"},
{name: "nested relative", module: "apps/widget"},
{name: "nested absolute", module: "apps/widget", absolute: true},
{name: "nested checkout alias", module: "apps/widget", absolute: true, alias: true},
} {
t.Run(tt.name, func(t *testing.T) {
repository := newDeliveryBuildRepository(t)
moduleDirectory := repository
tag := "v1.2.3"
if tt.module != "" {
moduleDirectory = filepath.Join(repository, filepath.FromSlash(tt.module))
tag = tt.module + "/v1.2.3"
for _, name := range []string{"go.mod", "main.go", "docs/releases/v1.2.3.md"} {
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, tt.module+"/"+name, string(contents))
}
}
writeRepositoryFile(t, repository, ".gitignore", "dist/\n")
state := &deliveryServerState{data: deliveryServerData{tag: tag}}
server := newDeliveryServer(t, state)
defer server.Close()
settings := cli.Settings{Product: "Example Product", ModuleDir: tt.module,
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)
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Prepare module source and output exclusion")
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", tag)
output, resolved := "dist", filepath.Join(moduleDirectory, "dist")
if tt.absolute {
output = filepath.Join(t.TempDir(), "assets")
resolved = output
}
var stdout, stderr bytes.Buffer
invocationRepository := repository
if tt.alias {
invocationRepository = filepath.Join(t.TempDir(), "checkout-alias")
if err := os.Symlink(repository, invocationRepository); err != nil {
t.Fatal(err)
}
}
if status := run(context.Background(), []string{"build", "--repo", invocationRepository, "--output", output, "v1.2.3"}, &stdout, &stderr); status != 0 {
t.Fatalf("build status=%d, stderr=%s", status, stderr.String())
}
receipt, err := cli.LoadBuildReceipt(filepath.Join(resolved, cli.BuildReceiptName))
if err != nil || receipt.ModuleDir != moduleDirectory || receipt.Tag != tag {
t.Fatalf("build receipt=%#v, error=%v", receipt, err)
}
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
args := []string{"deliver", "--repo", invocationRepository, "--assets", output, "v1.2.3"}
stdout.Reset()
stderr.Reset()
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 2 {
t.Fatalf("delivery status=%d, creates=%d, uploads=%d, stderr=%s", status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
}
if tt.alias {
if status := run(context.Background(), []string{"deliver", "--repo", repository, "--assets", output, "v1.2.3"}, &stdout, &stderr); status != 0 || state.snapshot().assetUploads != 2 {
t.Fatalf("physical-path retry status=%d, uploads=%d, stderr=%s", status, state.snapshot().assetUploads, stderr.String())
}
}
if tt.module != "" {
cliGitRun(t, repository, "tag", "v1.2.3")
wrongModule := settings
wrongModule.ModuleDir = ""
invocation := cli.Invocation{Repository: repository, AssetsDir: resolved, Version: "v1.2.3"}
requestsBefore := state.snapshot().apiRequests
if status := deliverWithSettings(context.Background(), invocation, wrongModule, &stdout, &stderr); status != 1 || state.snapshot().apiRequests != requestsBefore {
t.Fatalf("wrong module status=%d, requests=%d->%d, stderr=%s", status, requestsBefore, state.snapshot().apiRequests, stderr.String())
}
}
if err := os.WriteFile(receipt.Artifacts[0].Path, []byte("changed"), 0o600); err != nil {
t.Fatal(err)
}
writesBefore := state.snapshot().writes
if status := run(context.Background(), args, &stdout, &stderr); status != 1 || state.snapshot().writes != writesBefore {
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 module 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

@@ -0,0 +1,71 @@
package main
import (
"bytes"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestCandidateCheckUsesCommittedDeclarationSymlink(t *testing.T) {
repository := newCLIRepository(t)
if err := os.Rename(filepath.Join(repository, "go.mod"), filepath.Join(repository, "module.txt")); err != nil {
t.Fatal(err)
}
if err := os.Symlink("module.txt", filepath.Join(repository, "go.mod")); err != nil {
t.Fatal(err)
}
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product"})
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Use committed declaration symlink")
var stdout, stderr bytes.Buffer
if status := run(context.Background(), []string{"check", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 {
t.Fatalf("linked declaration check status=%d stderr=%s", status, stderr.String())
}
}
func TestPageOnlyDeliveryUsesCommittedModuleInSparseCheckout(t *testing.T) {
repository := newCLIRepository(t)
const module = "apps/widget"
writeRepositoryFile(t, repository, module+"/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
writeRepositoryFile(t, repository, module+"/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nNested release note.\n")
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Add sparse release module")
state := &deliveryServerState{data: deliveryServerData{tag: module + "/v1.2.3"}}
server := newDeliveryServer(t, state)
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", ModuleDir: module,
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") })
cliGitRun(t, repository, "tag", state.snapshot().tag)
cliGitRun(t, repository, "checkout", "--detach", state.snapshot().tag)
cliGitRun(t, repository, "sparse-checkout", "set", "--cone", "docs")
if _, err := os.Stat(filepath.Join(repository, filepath.FromSlash(module))); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("module fixture is materialized: %v", err)
}
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
gitOnly := t.TempDir()
gitPath, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
if err := os.Symlink(gitPath, filepath.Join(gitOnly, "git")); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", gitOnly)
for _, args := range [][]string{
{"deliver", "--repo", repository, "v1.2.3"},
{"ci-deliver", "--repo", repository, "--prepared", "--expected-module", module, "--commit", state.snapshot().commit, state.snapshot().tag},
} {
var stdout, stderr bytes.Buffer
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("%s sparse delivery status=%d creates=%d uploads=%d stderr=%s", args[0], status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
}
}
}

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", TokenEnv: "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,54 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestMultiModuleExampleSetupUsesCurrentSourceTool(t *testing.T) {
root := cliRepositoryRoot(t)
repository := newCLIRepository(t)
copyExampleTree(t, filepath.Join(root, "examples", "multi-module"), repository)
const module = "go.maximumdirect.net/releasekit"
environment := append(os.Environ(), "GOTOOLCHAIN=local", "GOWORK=off", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=")
goCommand := func(directory string, args ...string) string {
t.Helper()
command := exec.Command("go", args...)
command.Dir, command.Env = directory, environment
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("go %q: %v\n%s", args, err, output)
}
return string(output)
}
selections := []struct {
directory, profile, product, version string
}{
{".", "releasekit-root.json", "Example Consumer", "v1.2.3"},
{"integrations/ckconfig", "releasekit-ckconfig.json", "Example Consumer Integration", "v1.2.3"},
{"integrations/core/v2", "releasekit-core-v2.json", "Example Consumer Core v2", "v2.1.0"},
}
for _, selected := range selections {
directory := filepath.Join(repository, filepath.FromSlash(selected.directory))
if selected.directory != "integrations/core/v2" {
writeRepositoryFile(t, repository, selected.directory+"/source.go", "package candidate\n")
}
goCommand(directory, "mod", "edit", "-require="+module+"@v0.0.0", "-replace="+module+"="+root, "-tool="+module+"/cmd/releasekit")
goCommand(directory, "mod", "tidy")
writeRepositoryFile(t, repository, selected.directory+"/docs/releases/"+selected.version+".md", "# "+selected.product+" "+selected.version+"\n\nSource verification fixture.\n")
}
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Select current source in disposable example")
for _, selected := range selections {
output := goCommand(filepath.Join(repository, filepath.FromSlash(selected.directory)), "tool", "releasekit", "check", "--config", selected.profile, selected.version)
if !strings.Contains(output, "is valid") {
t.Fatalf("source-selected check output=%s", output)
}
}
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
t.Fatalf("source verification changed committed fixture: %s", status)
}
}

View File

@@ -13,10 +13,11 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process" "go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] 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] --commit OID VERSION" 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"
type Command string type Command string
@@ -31,14 +32,17 @@ const (
// 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
ExpectedTag string
Prepared bool
} }
// Parse accepts only commands that have been implemented by the executable. // Parse accepts only commands that have been implemented by the executable.
@@ -67,10 +71,16 @@ func Parse(args []string) (Invocation, error) {
flags.StringVar(&assetsDir, "assets", "", "verified build assets directory") flags.StringVar(&assetsDir, "assets", "", "verified build assets directory")
} }
var remote *string var remote *string
expectedModule := ""
if action == PublishAction || action == CIDeliveryAction {
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
}
expectedCommit := "" expectedCommit := ""
prepared := false
if action == CIDeliveryAction { if action == CIDeliveryAction {
remote = flags.String("remote", "origin", "Git remote") remote = flags.String("remote", "origin", "Git remote")
flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit") flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit")
flags.BoolVar(&prepared, "prepared", false, "verify an already prepared tagged checkout without fetching or checkout")
} }
if err := flags.Parse(args[1:]); err != nil { if err := flags.Parse(args[1:]); err != nil {
return Invocation{}, err return Invocation{}, err
@@ -84,11 +94,25 @@ func Parse(args []string) (Invocation, error) {
if action == CIDeliveryAction && !validGitObjectID(expectedCommit) { if action == CIDeliveryAction && !validGitObjectID(expectedCommit) {
return Invocation{}, errors.New("ci-deliver --commit must be a full Git object ID") return Invocation{}, errors.New("ci-deliver --commit must be a full Git object ID")
} }
version := flags.Arg(0)
expectedTag := ""
if action == CIDeliveryAction {
expectedTag = version
if slash := strings.LastIndex(version, "/"); slash >= 0 {
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: flags.Arg(0)}, nil 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
default: default:
return Invocation{}, fmt.Errorf("unknown command %q", args[0]) return Invocation{}, fmt.Errorf("unknown command %q", args[0])
} }
@@ -116,6 +140,7 @@ type CheckCommand struct {
// 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"`
Remote string `json:"remote,omitempty"` Remote string `json:"remote,omitempty"`
ExpectedPushURL string `json:"expected_push_url,omitempty"` ExpectedPushURL string `json:"expected_push_url,omitempty"`
Checks []CheckCommand `json:"checks,omitempty"` Checks []CheckCommand `json:"checks,omitempty"`
@@ -126,7 +151,11 @@ type Settings struct {
// ValidationSettings selects shared candidate checks in a release profile. // ValidationSettings selects shared candidate checks in a release profile.
type ValidationSettings struct { type ValidationSettings struct {
Go GoValidationSettings `json:"go,omitempty"` // SharedFiles selects committed files relative to the repository root.
// Nil uses optional defaults; a non-nil empty slice selects no shared files.
SharedFiles []string `json:"shared_files"`
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"`
@@ -167,12 +196,14 @@ 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 {
Forge string `json:"forge,omitempty"`
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
Owner string `json:"owner"` Owner string `json:"owner"`
Repository string `json:"repository"` Repository string `json:"repository"`
TokenEnv string `json:"token_env,omitempty"` TokenEnv string `json:"token_env,omitempty"`
TokenFile string `json:"token_file,omitempty"`
} }
// BuildSettings selects the Go application package, artifact name, and targets. // BuildSettings selects the Go application package, artifact name, and targets.
@@ -269,9 +300,9 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
return settings, nil return settings, nil
} }
// RunChecks runs configured argument vectors in repoDir. Each command receives // RunChecks runs configured argument vectors in dir. Each command receives
// its own environment overlay and inherits the remaining process environment. // its own environment overlay and inherits the remaining process environment.
func RunChecks(ctx context.Context, repoDir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error { func RunChecks(ctx context.Context, dir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error {
for i, check := range checks { for i, check := range checks {
environment := make(map[string]string, len(check.Env)+len(ownedEnv)) environment := make(map[string]string, len(check.Env)+len(ownedEnv))
for key, value := range check.Env { for key, value := range check.Env {
@@ -282,7 +313,7 @@ func RunChecks(ctx context.Context, repoDir string, checks []CheckCommand, owned
} }
if err := process.Run(ctx, process.Invocation{ if err := process.Run(ctx, process.Invocation{
Args: check.Args, Args: check.Args,
Dir: repoDir, Dir: dir,
Env: environment, Env: environment,
Stdout: stdout, Stdout: stdout,
Stderr: stderr, Stderr: stderr,

View File

@@ -33,6 +33,10 @@ func TestParse(t *testing.T) {
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.Version != "v1.2.4" {
t.Fatalf("Parse(publish) = %#v", publish) t.Fatalf("Parse(publish) = %#v", publish)
} }
publishMapped, err := Parse([]string{"publish", "--repo", "candidate", "--expected-module", "integrations/ckconfig", "v1.2.4"})
if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" {
t.Fatalf("Parse(publish --expected-module) = %#v, error = %v", publishMapped, 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)
@@ -47,11 +51,11 @@ func TestParse(t *testing.T) {
if deliver.Command != DeliveryAction || deliver.Repository != "candidate" || deliver.ConfigPath != "releasekit.json" || deliver.AssetsDir != "assets with spaces" || deliver.Version != "v1.2.6" { if deliver.Command != DeliveryAction || deliver.Repository != "candidate" || deliver.ConfigPath != "releasekit.json" || deliver.AssetsDir != "assets with spaces" || deliver.Version != "v1.2.6" {
t.Fatalf("Parse(deliver) = %#v", deliver) t.Fatalf("Parse(deliver) = %#v", deliver)
} }
ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.7"}) ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--prepared", "--expected-module", "integrations/ckconfig", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/v1.2.7"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" { if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" || ciDelivery.ExpectedTag != "integrations/ckconfig/v1.2.7" || ciDelivery.ExpectedModule != "integrations/ckconfig" || !ciDelivery.Prepared {
t.Fatalf("Parse(ci-deliver) = %#v", ciDelivery) t.Fatalf("Parse(ci-deliver) = %#v", ciDelivery)
} }
ciDefault, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.8"}) ciDefault, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.8"})
@@ -64,6 +68,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") {
t.Fatalf("Parse(ci-deliver unstable terminal tag) error = %v", 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")
} }
@@ -166,6 +173,56 @@ func TestLoadSettingsReadsGoValidation(t *testing.T) {
} }
} }
func TestLoadSettingsPreservesSharedFilesSelection(t *testing.T) {
repoDir := t.TempDir()
profileDir := filepath.Join(repoDir, "profiles")
if err := os.MkdirAll(profileDir, 0o700); err != nil {
t.Fatal(err)
}
for _, test := range []struct {
name string
profile string
wantNil bool
wantFile string
}{
{name: "omitted", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{}}`, wantNil: true},
{name: "null", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":null}}`, wantNil: true},
{name: "empty", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":[]}}`},
{name: "selected", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":["../README.md"]}}`, wantFile: "../README.md"},
} {
t.Run(test.name, func(t *testing.T) {
path := filepath.Join(profileDir, "release.json")
if err := os.WriteFile(path, []byte(test.profile), 0o600); err != nil {
t.Fatal(err)
}
settings, err := LoadSettings(repoDir, filepath.Join("profiles", "release.json"))
if err != nil {
t.Fatal(err)
}
if settings.ModuleDir != "integrations/ckconfig" {
t.Fatalf("module_dir = %q", settings.ModuleDir)
}
if settings.Validation == nil || (settings.Validation.SharedFiles == nil) != test.wantNil {
t.Fatalf("shared_files = %#v, want nil=%t", settings.Validation, test.wantNil)
}
if test.wantFile != "" && (len(settings.Validation.SharedFiles) != 1 || settings.Validation.SharedFiles[0] != test.wantFile) {
t.Fatalf("shared_files = %#v, want %q", settings.Validation.SharedFiles, test.wantFile)
}
encoded, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
var roundTrip Settings
if err := json.Unmarshal(encoded, &roundTrip); err != nil {
t.Fatal(err)
}
if (roundTrip.Validation.SharedFiles == nil) != test.wantNil {
t.Fatalf("serialized shared_files = %#v, want nil=%t; JSON=%s", roundTrip.Validation.SharedFiles, test.wantNil, encoded)
}
})
}
}
func TestLoadSettingsPreservesMarkdownObjectSelection(t *testing.T) { func TestLoadSettingsPreservesMarkdownObjectSelection(t *testing.T) {
repoDir := t.TempDir() repoDir := t.TempDir()
profilePath := filepath.Join(repoDir, "releasekit.json") profilePath := filepath.Join(repoDir, "releasekit.json")

View File

@@ -2,7 +2,6 @@ package cli
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@@ -11,11 +10,13 @@ import (
"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/versioncontract" "go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
const BuildReceiptName = ".releasekit-build.json" const BuildReceiptName = ".releasekit-build.json"
const BuildReceiptSchemaVersion = 1
type ReceiptTarget struct { type ReceiptTarget struct {
OS string `json:"os"` OS string `json:"os"`
@@ -31,7 +32,11 @@ type ReceiptArtifact struct {
// BuildReceipt is private local coordination data for generated binaries. // BuildReceipt is private local coordination data for generated binaries.
type BuildReceipt struct { type BuildReceipt struct {
SchemaVersion int `json:"schema_version"`
RepositoryDir string `json:"repository_dir"` RepositoryDir string `json:"repository_dir"`
ModuleDir string `json:"module_dir"`
ModulePath string `json:"module_path"`
Tag string `json:"tag"`
CandidateCommit string `json:"candidate_commit"` CandidateCommit string `json:"candidate_commit"`
SourceVerified bool `json:"source_verified"` SourceVerified bool `json:"source_verified"`
Version string `json:"version"` Version string `json:"version"`
@@ -44,12 +49,16 @@ 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)
} }
receipt.OutputDir = resolvedDir receipt.OutputDir = resolvedDir
if err := validateBuildReceipt(receipt, true); err != nil { if err := validateBuildReceipt(receipt); err != nil {
return "", err return "", err
} }
contents, err := json.MarshalIndent(receipt, "", " ") contents, err := json.MarshalIndent(receipt, "", " ")
@@ -62,7 +71,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)
@@ -111,41 +124,62 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
} }
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err) return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
} }
if err := validateBuildReceipt(receipt, true); err != nil { if err := validateBuildReceipt(receipt); err != nil {
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
return BuildReceipt{}, fmt.Errorf("%w; regenerate it with the updated build command", err)
}
return BuildReceipt{}, err return BuildReceipt{}, err
} }
if filepath.Clean(receipt.OutputDir) != filepath.Dir(resolvedPath) { if !sameDirectory(receipt.OutputDir, filepath.Dir(resolvedPath)) {
return BuildReceipt{}, errors.New("build receipt output directory does not match its location") return BuildReceipt{}, errors.New("build receipt output directory does not match its location")
} }
return receipt, nil return receipt, nil
} }
func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool { func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool {
resolvedRepo, err := filepath.Abs(repositoryDir) if !sameDirectory(receipt.RepositoryDir, repositoryDir) {
if err != nil || filepath.Clean(receipt.RepositoryDir) != filepath.Clean(resolvedRepo) {
return false return false
} }
if receipt.CandidateCommit != commit || receipt.Version != version || receipt.MainPackage != settings.MainPackage || receipt.BinaryName != settings.BinaryName { if receipt.CandidateCommit != commit || receipt.Version != version {
return false return false
} }
want := normalizeReceiptTargets(settings.Targets) want := artifact.NormalizeSettings(settings.MainPackage, settings.BinaryName, parseReceiptTargets(settings.Targets))
if len(want) != len(receipt.Targets) { got := artifact.NormalizeSettings(receipt.MainPackage, receipt.BinaryName, parseStoredTargets(receipt.Targets))
if want.MainPackage != got.MainPackage || want.BinaryName != got.BinaryName || len(want.Targets) != len(got.Targets) {
return false return false
} }
for i, target := range want { for i, target := range want.Targets {
if target != receipt.Targets[i] { if target != got.Targets[i] {
return false return false
} }
} }
return true return true
} }
func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error { func sameDirectory(first, second string) bool {
firstInfo, err := os.Stat(first)
if err != nil {
return false
}
secondInfo, err := os.Stat(second)
return err == nil && os.SameFile(firstInfo, secondInfo)
}
func validateBuildReceipt(receipt BuildReceipt) error {
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
}
if !versioncontract.ValidStableVersion(receipt.Version) { if !versioncontract.ValidStableVersion(receipt.Version) {
return fmt.Errorf("build receipt has invalid version %q", receipt.Version) return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
} }
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.OutputDir) { if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository and output directories must be absolute") return errors.New("build receipt repository, module, and output directories must be absolute")
}
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
return errors.New("build receipt is missing module path or full tag")
}
if err := validateRecordedIdentity(receipt); err != nil {
return fmt.Errorf("build receipt has inconsistent module identity: %w", err)
} }
if !validCommitID(receipt.CandidateCommit) { if !validCommitID(receipt.CandidateCommit) {
return errors.New("build receipt has invalid candidate commit") return errors.New("build receipt has invalid candidate commit")
@@ -156,32 +190,15 @@ func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) 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)
@@ -191,39 +208,38 @@ func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
if !validSHA256(artifact.SHA256) { if !validSHA256(artifact.SHA256) {
return fmt.Errorf("build receipt has invalid SHA-256 for %q", artifact.Filename) return fmt.Errorf("build receipt has invalid SHA-256 for %q", artifact.Filename)
} }
if verifyFiles {
if err := verifyReceiptArtifact(artifact); err != nil {
return err
}
}
} }
return nil return nil
} }
func verifyReceiptArtifact(artifact ReceiptArtifact) error { func validateRecordedIdentity(receipt BuildReceipt) error {
info, err := os.Lstat(artifact.Path) repositoryDir := filepath.Clean(receipt.RepositoryDir)
moduleDir := filepath.Clean(receipt.ModuleDir)
relative, err := filepath.Rel(repositoryDir, moduleDir)
if err != nil { if err != nil {
return fmt.Errorf("inspect build artifact %q: %w", artifact.Path, err) return fmt.Errorf("relate module directory to repository: %w", err)
} }
if !info.Mode().IsRegular() { if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
return fmt.Errorf("build artifact %q is not a regular file", artifact.Path) return errors.New("module directory is outside repository")
} }
file, err := os.Open(artifact.Path) if relative == "" {
relative = "."
}
identity, err := releaseidentity.Derive(releaseidentity.Selection{
RepositoryDir: repositoryDir,
ModuleDir: moduleDir,
ModuleSubdir: filepath.ToSlash(relative),
}, []byte("module "+receipt.ModulePath+"\n"), receipt.Version)
if err != nil { if err != nil {
return fmt.Errorf("open build artifact %q: %w", artifact.Path, err) return err
} }
defer file.Close() if identity.Tag != receipt.Tag {
hash := sha256.New() return fmt.Errorf("full tag %q does not match module selection and version; want %q", receipt.Tag, identity.Tag)
if _, err := io.Copy(hash, file); err != nil {
return fmt.Errorf("hash build artifact %q: %w", artifact.Path, err)
}
if actual := hex.EncodeToString(hash.Sum(nil)); actual != artifact.SHA256 {
return fmt.Errorf("build artifact %q hash changed: got %s, expected %s", artifact.Path, actual, artifact.SHA256)
} }
return nil return nil
} }
func normalizeReceiptTargets(targets []string) []ReceiptTarget { func parseReceiptTargets(targets []string) []artifact.Target {
parsed := make([]artifact.Target, 0, len(targets)) parsed := make([]artifact.Target, 0, len(targets))
for _, value := range targets { for _, value := range targets {
goos, goarch, ok := strings.Cut(value, "/") goos, goarch, ok := strings.Cut(value, "/")
@@ -232,12 +248,15 @@ func normalizeReceiptTargets(targets []string) []ReceiptTarget {
} }
parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch}) parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch})
} }
normalized := artifact.NormalizeTargets(parsed) return parsed
result := make([]ReceiptTarget, 0, len(normalized)) }
for _, target := range normalized {
result = append(result, ReceiptTarget{OS: target.OS, Arch: target.Arch}) func parseStoredTargets(targets []ReceiptTarget) []artifact.Target {
parsed := make([]artifact.Target, 0, len(targets))
for _, target := range targets {
parsed = append(parsed, artifact.Target{OS: target.OS, Arch: target.Arch})
} }
return result return parsed
} }
func validCommitID(value string) bool { func validCommitID(value string) bool {

View File

@@ -3,62 +3,159 @@ package cli
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json"
"errors"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
) )
func TestBuildReceiptRoundTripBindsFilesAndBuildInputs(t *testing.T) { func TestWriteBuildReceiptReportsTemporaryCleanup(t *testing.T) {
outputDir := t.TempDir() for _, mode := range []string{"renamed", "cleanup failure", "install and cleanup failure"} {
repositoryDir := t.TempDir() t.Run(mode, func(t *testing.T) {
filename := "example-v1.2.3-linux-amd64" repository := t.TempDir()
artifactPath := filepath.Join(outputDir, filename) output := t.TempDir()
contents := []byte("built application") name := "app-v1.2.3-linux-amd64"
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil { receipt := BuildReceipt{
t.Fatal(err) SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repository, ModuleDir: repository,
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)
}
}
})
} }
digest := sha256.Sum256(contents) }
receipt := BuildReceipt{
RepositoryDir: repositoryDir, func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
CandidateCommit: strings.Repeat("a", 40), for _, test := range []struct {
Version: "v1.2.3", name string
MainPackage: "./cmd/example", moduleDir string
BinaryName: "example", modulePath string
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, tag string
Compiler: "go version go1.25.0 linux/amd64", }{
Artifacts: []ReceiptArtifact{{ {name: "root", moduleDir: ".", modulePath: "example.com/receipt", tag: "v1.2.3"},
Path: artifactPath, {name: "nested", moduleDir: "integrations/ckconfig", modulePath: "example.com/ckconfig", tag: "integrations/ckconfig/v1.2.3"},
Filename: filename, } {
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, t.Run(test.name, func(t *testing.T) {
SHA256: hex.EncodeToString(digest[:]), outputDir := t.TempDir()
}}, repositoryDir := t.TempDir()
} moduleDir := repositoryDir
path, err := WriteBuildReceipt(outputDir, receipt) if test.moduleDir != "." {
if err != nil { moduleDir = filepath.Join(repositoryDir, filepath.FromSlash(test.moduleDir))
t.Fatal(err) if err := os.MkdirAll(moduleDir, 0o755); err != nil {
} t.Fatal(err)
loaded, err := LoadBuildReceipt(path) }
if err != nil { }
t.Fatal(err) filename := "example-v1.2.3-linux-amd64"
} artifactPath := filepath.Join(outputDir, filename)
settings := BuildSettings{ contents := []byte("built application")
MainPackage: "./cmd/example", if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
BinaryName: "example", t.Fatal(err)
Targets: []string{"linux/amd64", "linux/amd64"}, }
} digest := sha256.Sum256(contents)
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) { receipt := BuildReceipt{
t.Fatalf("receipt does not match normalized build settings: %#v", loaded) SchemaVersion: BuildReceiptSchemaVersion,
} RepositoryDir: repositoryDir,
settings.BinaryName = "other" ModuleDir: moduleDir,
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) { ModulePath: test.modulePath,
t.Fatal("receipt matched changed build settings") Tag: test.tag,
} CandidateCommit: strings.Repeat("a", 40),
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil { Version: "v1.2.3",
t.Fatal(err) MainPackage: "./cmd/example",
} BinaryName: "example",
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "hash changed") { Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
t.Fatalf("LoadBuildReceipt() error = %v, want changed-file hash error", err) Compiler: "go version go1.25.0 linux/amd64",
Artifacts: []ReceiptArtifact{{
Path: artifactPath, Filename: filename,
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
}},
}
path, err := WriteBuildReceipt(outputDir, receipt)
if err != nil {
t.Fatal(err)
}
loaded, err := LoadBuildReceipt(path)
if err != nil {
t.Fatal(err)
}
settings := BuildSettings{MainPackage: "./cmd/example", BinaryName: "example", Targets: []string{"linux/amd64", "linux/amd64"}}
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
t.Fatalf("receipt does not match normalized build settings: %#v", loaded)
}
aliases := t.TempDir()
repositoryAlias, outputAlias := filepath.Join(aliases, "repository"), filepath.Join(aliases, "output")
if err := os.Symlink(repositoryDir, repositoryAlias); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outputDir, outputAlias); err != nil {
t.Fatal(err)
}
if !loaded.MatchesBuild(repositoryAlias, receipt.CandidateCommit, receipt.Version, settings) {
t.Fatal("receipt rejected an alias of its source repository")
}
if _, err := LoadBuildReceipt(filepath.Join(outputAlias, BuildReceiptName)); err != nil {
t.Fatalf("load receipt through output alias: %v", err)
}
if loaded.MatchesBuild(t.TempDir(), receipt.CandidateCommit, receipt.Version, settings) {
t.Fatal("receipt matched a different repository")
}
settings.BinaryName = "other"
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
t.Fatal("receipt matched changed build settings")
}
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil {
t.Fatal(err)
}
if _, err := LoadBuildReceipt(path); err != nil {
t.Fatalf("receipt loading verified changed artifact bytes: %v", err)
}
if err := os.Remove(artifactPath); err != nil {
t.Fatal(err)
}
if _, err := LoadBuildReceipt(path); err != nil {
t.Fatalf("receipt loading required artifact bytes: %v", err)
}
})
} }
} }
@@ -68,7 +165,9 @@ func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
body string body string
want string want string
}{ }{
{name: "unknown field", body: `{"unexpected":true}`, want: "unknown field"}, {name: "unknown field", body: `{"schema_version":1,"unexpected":true}`, want: "unknown field"},
{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: "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) {
@@ -82,3 +181,66 @@ func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
}) })
} }
} }
func TestWriteBuildReceiptRejectsInconsistentRecordedIdentity(t *testing.T) {
repositoryDir := t.TempDir()
moduleDir := filepath.Join(repositoryDir, "integrations", "ckconfig")
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
t.Fatal(err)
}
outputDir := t.TempDir()
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion,
RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
Artifacts: []ReceiptArtifact{{
Path: filepath.Join(outputDir, "helper-v1.2.3-linux-amd64"), Filename: "helper-v1.2.3-linux-amd64",
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64),
}},
}
if _, err := WriteBuildReceipt(outputDir, receipt); err == nil || !strings.Contains(err.Error(), "full tag") {
t.Fatalf("WriteBuildReceipt() error = %v, want inconsistent full tag", err)
}
}
func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
repositoryDir := t.TempDir()
outputDir := t.TempDir()
artifactPath := filepath.Join(outputDir, "helper-v1.2.3-linux-amd64")
contents := []byte("fixture")
if err := os.WriteFile(artifactPath, contents, 0o600); err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(contents)
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion,
RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
Artifacts: []ReceiptArtifact{{
Path: artifactPath, Filename: filepath.Base(artifactPath),
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
}},
}
contents, err := json.Marshal(receipt)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(contents, &fields); err != nil {
t.Fatal(err)
}
fields["module_dir"] = filepath.Join(repositoryDir, "integrations", "ckconfig")
contents, err = json.Marshal(fields)
if err != nil {
t.Fatal(err)
}
path := filepath.Join(outputDir, BuildReceiptName)
if err := os.WriteFile(path, contents, 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "inconsistent module identity") {
t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err)
}
}

View File

@@ -0,0 +1,44 @@
package main
import (
"bytes"
"context"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T) {
repository := newDeliveryBuildRepository(t)
writeRepositoryFile(t, repository, "go.mod", "module example\n\ngo 1.26.0\n")
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Use local main module path")
state := &deliveryServerState{}
server := newDeliveryServer(t, state)
defer server.Close()
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)
for _, args := range [][]string{
{"check", "--repo", repository, "v1.2.3"},
{"build", "--repo", repository, "--output", filepath.Join(t.TempDir(), "assets"), "v1.2.3"},
} {
var stdout, stderr bytes.Buffer
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || !strings.Contains(stdout.String(), "module example version v1.2.3 tag v1.2.3") {
t.Fatalf("%s status=%d stdout=%s stderr=%s", args[0], status, stdout.String(), stderr.String())
}
}
settings.Build = nil
writeDeliveryProfile(t, repository, settings)
state.update(func(state *deliveryServerData) { state.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
if status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("page delivery status=%d creates=%d uploads=%d stderr=%s", status, state.snapshot().releaseCreates, state.snapshot().assetUploads, stderr.String())
}
}

View File

@@ -11,9 +11,12 @@ import (
"strings" "strings"
"syscall" "syscall"
"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"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
) )
func main() { func main() {
@@ -29,103 +32,22 @@ 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.VersionCommand {
invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository)
if err != nil {
fmt.Fprintf(stderr, "%v\n", err)
return 1
}
}
switch invocation.Command { switch invocation.Command {
case cli.VersionCommand: case cli.VersionCommand:
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 {
request.ExpectedPushURL = settings.ExpectedPushURL
fmt.Fprintf(stderr, "validating and publishing %s\n", invocation.Version)
result, err := releasekit.Publish(ctx, request)
if err != nil {
fmt.Fprintf(stderr, "publication state=%s phase=%s version=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.Version, 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 at %s (tag object %s)\n", result.Version, result.CandidateCommit, result.TagObject)
return 0
}
candidate, err := releasekit.Check(ctx, request)
if err != nil {
fmt.Fprintf(stderr, "check failed: %s\n", candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
return 1
}
fmt.Fprintf(stdout, "local candidate %s at %s is valid\n", candidate.Version, 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,
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 at %s: %v\n", 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 %s at %s\n", result.Version, 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 %s at %s with %s\n", len(result.Artifacts), result.Version, 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:
@@ -134,9 +56,111 @@ 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 := 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, 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 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,
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 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,
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
Remote: settings.Remote, Remote: settings.Remote,
@@ -147,9 +171,13 @@ 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.RepositoryDir, checks, map[string]string{ return cli.RunChecks(ctx, candidate.ModuleDir, 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_MODULE_DIR": candidate.ModuleDir,
"RELEASEKIT_MODULE_PATH": candidate.ModulePath,
"RELEASEKIT_TAG": candidate.Tag,
}, output, output) }, output, output)
} }
} }
@@ -161,7 +189,9 @@ func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec
return releasekit.ValidationSpec{} return releasekit.ValidationSpec{}
} }
result := releasekit.ValidationSpec{ result := releasekit.ValidationSpec{
GoFormat: settings.GoFormat, SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles),
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,
@@ -199,6 +229,42 @@ func candidateFailureText(err error) string {
return err.Error() return err.Error()
} }
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error {
if expectedModule == "" {
return nil
}
commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil {
return err
}
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit)
if err != nil {
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err)
}
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit)
if err != nil {
return fmt.Errorf("normalize profile module %q: %w", profileModule, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir)
}
return nil
}
func selectedModuleLabel(moduleDir string) string {
if moduleDir == "" {
return "."
}
return moduleDir
}
func copyStringsPreservingEmpty(values []string) []string {
if values == nil {
return nil
}
return append([]string{}, values...)
}
func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int { func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath) settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil { if err != nil {
@@ -211,9 +277,10 @@ func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr
func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int { func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{ err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
Version: invocation.Version, Tag: invocation.ExpectedTag,
Remote: invocation.Remote, Remote: invocation.Remote,
ExpectedCommit: invocation.Commit, ExpectedCommit: invocation.Commit,
VerifyOnly: invocation.Prepared,
}) })
if err != nil { if err != nil {
fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err) fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err)
@@ -228,12 +295,32 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
fmt.Fprintf(stderr, "load profile: %v\n", err) fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2 return 2
} }
destination, status := deliveryDestination(settings, stderr) if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
return 2
}
identity, err := releaseidentity.FromCommitted(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit)
if err != nil {
fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err)
return 1
}
if invocation.ExpectedTag != identity.Tag {
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected module tag %q\n", invocation.ExpectedTag, identity.Tag)
return 1
}
destination, status := deliveryDestination(invocation.Repository, settings, 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.PrepareBuildDependencies(ctx, invocation.Repository); err != nil { 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{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
}); err != nil {
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err) fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
return 1 return 1
} }
@@ -244,32 +331,61 @@ 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, 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, 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 tokenEnv := delivery.TokenEnv
if strings.TrimSpace(tokenEnv) == "" { if strings.TrimSpace(tokenEnv) == "" {
tokenEnv = "RELEASEKIT_GITEA_TOKEN" tokenEnv = "RELEASEKIT_GITEA_TOKEN"
} }
token, ok := os.LookupEnv(tokenEnv) token, ok := os.LookupEnv(tokenEnv)
if !ok || strings.TrimSpace(token) == "" { if (!ok || strings.TrimSpace(token) == "") && delivery.TokenFile != "" {
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv) name := delivery.TokenFile
return releasekit.GiteaDestination{}, 2 if !filepath.IsAbs(name) {
name = filepath.Join(repositoryDir, name)
}
contents, err := os.ReadFile(name)
if err != nil {
fmt.Fprintf(stderr, "read delivery token file: %v\n", err)
return releasekit.DeliveryDestination{}, 2
}
token = strings.TrimSpace(string(contents))
if token == "" {
fmt.Fprintln(stderr, "delivery token file is empty or blank")
return releasekit.DeliveryDestination{}, 2
}
} }
return releasekit.GiteaDestination{BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0 if strings.TrimSpace(token) == "" {
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
return releasekit.DeliveryDestination{}, 2
}
return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, 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")
@@ -282,10 +398,17 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
} }
if hasTargets { if hasTargets {
if invocation.AssetsDir != "" { if invocation.AssetsDir != "" {
assetsDir := invocation.AssetsDir commit, err := git.CaptureHead(ctx, invocation.Repository)
if !filepath.IsAbs(assetsDir) { if err != nil {
assetsDir = filepath.Join(invocation.Repository, assetsDir) fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
return 1
} }
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit)
if err != nil {
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
return 1
}
assetsDir := artifact.OutputDirectory(selection.ModuleDir, invocation.AssetsDir)
receipt, err := cli.LoadBuildReceipt(filepath.Join(assetsDir, cli.BuildReceiptName)) receipt, err := cli.LoadBuildReceipt(filepath.Join(assetsDir, cli.BuildReceiptName))
if err != nil { if err != nil {
fmt.Fprintf(stderr, "load verified build receipt: %v\n", err) fmt.Fprintf(stderr, "load verified build receipt: %v\n", err)
@@ -301,26 +424,19 @@ 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,
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
ExpectedTag: invocation.ExpectedTag,
Destination: destination, Destination: destination,
Build: buildSpec, Build: buildSpec,
Prebuilt: prebuilt, Prebuilt: prebuilt,
Output: stderr, Output: stderr,
}) })
if err != nil { if err != nil {
fmt.Fprintf(stderr, "delivery state=%s version=%s commit=%s url=%s: %v\n", result.State, result.Version, 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 %s at %s (state %s)\n", result.Version, 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 != "" {
fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL) fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL)
} }
@@ -328,6 +444,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
@@ -342,13 +498,13 @@ func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) { func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
switch result.State { switch result.State {
case releasekit.DeliveryNotAttempted: case releasekit.DeliveryNotAttempted:
fmt.Fprintln(output, "recovery: fix the local or preflight failure before retrying; no remote write was attempted") fmt.Fprintf(output, "recovery: fix the local or preflight failure for module %s version %s tag %s before retrying; no remote write was attempted\n", result.ModulePath, result.Version, result.Tag)
case releasekit.DeliveryPartial: case releasekit.DeliveryPartial:
fmt.Fprintln(output, "recovery: fix the reported cause, then retry this version") fmt.Fprintf(output, "recovery: fix the reported cause, then retry module %s version %s tag %s\n", result.ModulePath, result.Version, result.Tag)
case releasekit.DeliveryConflict: case releasekit.DeliveryConflict:
fmt.Fprintln(output, "recovery: investigate conflicting hosted content; use a new version if the source or published contents need correction") fmt.Fprintf(output, "recovery: investigate conflicting hosted content for module %s version %s tag %s; use a new version if the source or published contents need correction\n", result.ModulePath, result.Version, result.Tag)
case releasekit.DeliveryUnknown: case releasekit.DeliveryUnknown:
fmt.Fprintln(output, "recovery: resolve the remote state before retrying") fmt.Fprintf(output, "recovery: resolve the remote state for module %s version %s tag %s before retrying\n", result.ModulePath, result.Version, result.Tag)
default: default:
return return
} }
@@ -359,7 +515,8 @@ 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, CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified, RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag,
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,
} }
@@ -393,7 +550,11 @@ func configuredBuildSpec(settings *cli.BuildSettings) *releasekit.BuildSpec {
func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt { func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
receipt := cli.BuildReceipt{ receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: result.RepositoryDir, RepositoryDir: result.RepositoryDir,
ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath,
Tag: result.Tag,
CandidateCommit: result.CandidateCommit, CandidateCommit: result.CandidateCommit,
SourceVerified: result.SourceVerified, SourceVerified: result.SourceVerified,
Version: result.Version, Version: result.Version,

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,247 @@
package main
import (
"bytes"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
helper := filepath.Join(example, "select-module.sh")
for _, test := range []struct {
mode string
value string
want string
}{
{mode: "selector", value: "root", want: "root\tv[01].*\t.\treleasekit-root.json"},
{mode: "selector", value: "ckconfig", 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: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
} {
t.Run(test.mode+" "+test.value, func(t *testing.T) {
got := runModuleSelector(t, helper, test.mode, test.value, "")
if strings.TrimSpace(got) != test.want {
t.Fatalf("selector output = %q, want %q", got, test.want)
}
})
}
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
if err := os.WriteFile(mapPath, []byte("one\tfeature/*\tmodules/one\tprofiles/one.json\ntwo\tfeature/v1.*\tmodules/two\tprofiles/two.json\n"), 0o600); err != nil {
t.Fatal(err)
}
if output := runModuleSelectorError(t, helper, "selector", "absent", mapPath); !strings.Contains(output, "no module map row") {
t.Fatalf("unknown selector error = %q", output)
}
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
t.Fatalf("ambiguous event error = %q", output)
}
if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
t.Fatal(err)
}
got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath)
want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json"
if strings.TrimSpace(got) != want {
t.Fatalf("paths with spaces = %q, want %q", got, want)
}
}
func TestMultiModuleLauncherUsesSelectedModuleAndProfile(t *testing.T) {
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
repository := newCLIRepository(t)
copyExampleTree(t, example, repository)
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 go.maximumdirect.net/releasekit v0.2.198\n"
writeRepositoryFile(t, repository, "go.mod", rootModule)
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", selectedModule)
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, "profiles/core release.json", `{"product":"Example Consumer Integration","module_dir":"integrations/ck config"}`)
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "prepare multi-module launcher fixture")
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
if err := os.WriteFile(mapPath, []byte("with space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
t.Fatal(err)
}
shimDir := t.TempDir()
goLog := filepath.Join(t.TempDir(), "go commands")
argsLog := filepath.Join(t.TempDir(), "tool arguments")
shim := `#!/bin/sh
set -eu
printf 'cwd=%s args=%s\n' "$PWD" "$*" >> "$RELEASEKIT_TEST_GO_LOG"
modfile=
output=
previous=
for argument in "$@"; do
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
if [ "$previous" = -o ]; then output=$argument; fi
previous=$argument
done
if [ -n "$modfile" ]; then cat "$modfile" >> "$RELEASEKIT_TEST_GO_LOG"; fi
if [ "$1" = build ]; then
cat > "$output" <<'TOOL'
#!/bin/sh
printf '<%s>\n' "$@" > "$RELEASEKIT_TEST_TOOL_ARGS"
TOOL
chmod +x "$output"
fi
`
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("RELEASEKIT_MODULE_MAP", mapPath)
t.Setenv("RELEASEKIT_TEST_GO_LOG", goLog)
t.Setenv("RELEASEKIT_TEST_TOOL_ARGS", argsLog)
launcher := filepath.Join(repository, "release.sh")
command := exec.Command(launcher, "with space", "v1.2.4")
var stdout, stderr bytes.Buffer
command.Stdout = &stdout
command.Stderr = &stderr
if err := command.Run(); err != nil {
t.Fatalf("launcher error: %v stdout=%q stderr=%q", err, stdout.String(), stderr.String())
}
goCommands, err := os.ReadFile(goLog)
if err != nil {
t.Fatal(err)
}
wantModule := filepath.Join(repository, "integrations", "ck config")
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)
}
toolArgs, err := os.ReadFile(argsLog)
if err != nil {
t.Fatal(err)
}
for _, expected := range []string{"<publish>", "<--repo>", "<" + repository + ">", "<--config>", "<profiles/core release.json>", "<--expected-module>", "<integrations/ck config>", "<v1.2.4>"} {
if !strings.Contains(string(toolArgs), expected) {
t.Errorf("publication arguments %q omit %q", toolArgs, expected)
}
}
if strings.Contains(string(goCommands), repository+"/.releasekit-bootstrap.") {
t.Fatalf("temporary tool metadata was placed inside the repository: %s", goCommands)
}
}
func TestMultiModuleLauncherBuildsToolFromSelectedDependency(t *testing.T) {
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
repository := newCLIRepository(t)
copyExampleTree(t, example, repository)
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 go.maximumdirect.net/releasekit v0.2.198\n")
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "prepare selected tool module")
proxy := writeReleaseKitModuleProxy(t)
moduleCache := t.TempDir()
t.Setenv("GOMODCACHE", moduleCache)
t.Cleanup(func() {
_ = filepath.WalkDir(moduleCache, func(path string, entry fs.DirEntry, err error) error {
if err == nil && entry.IsDir() {
_ = os.Chmod(path, 0o700)
}
return nil
})
})
t.Setenv("GOPROXY", "file://"+filepath.ToSlash(proxy))
t.Setenv("GOSUMDB", "off")
t.Setenv("GOTOOLCHAIN", "local")
moduleBefore, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
if err != nil {
t.Fatal(err)
}
command := exec.Command(filepath.Join(repository, "release.sh"), "ckconfig", "v1.2.3")
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("launcher error: %v output=%q", err, 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 built the root-selected ReleaseKit version: %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)
}
}
func runModuleSelector(t *testing.T, helper, mode, value, mapPath string) string {
t.Helper()
command := exec.Command("sh", helper, mode, value)
command.Env = os.Environ()
if mapPath != "" {
command.Env = append(command.Env, "RELEASEKIT_MODULE_MAP="+mapPath)
}
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("selector %s %q: %v: %s", mode, value, err, output)
}
return string(output)
}
func runModuleSelectorError(t *testing.T, helper, mode, value, mapPath string) string {
t.Helper()
command := exec.Command("sh", helper, mode, value)
command.Env = append(os.Environ(), "RELEASEKIT_MODULE_MAP="+mapPath)
output, err := command.CombinedOutput()
if err == nil {
t.Fatalf("selector %s %q unexpectedly succeeded: %s", mode, value, output)
}
return string(output)
}
func copyExampleTree(t *testing.T, source, destination string) {
t.Helper()
err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
relative, err := filepath.Rel(source, path)
if err != nil {
return err
}
if relative == "." {
return nil
}
target := filepath.Join(destination, relative)
if entry.IsDir() {
return os.MkdirAll(target, 0o700)
}
contents, err := os.ReadFile(path)
if err != nil {
return err
}
info, err := entry.Info()
if err != nil {
return err
}
mode := info.Mode().Perm()
if err := os.WriteFile(target, contents, mode); err != nil {
return err
}
return os.Chmod(target, mode)
})
if err != nil {
t.Fatal(fmt.Errorf("copy multi-module example: %w", err))
}
}

View File

@@ -0,0 +1,444 @@
package main
import (
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
root := cliRepositoryRoot(t)
example := filepath.Join(root, "examples", "multi-module")
contents, err := os.ReadFile(filepath.Join(example, "woodpecker.yml"))
if err != nil {
t.Fatal(err)
}
block, err := extractWoodpeckerCommand(string(contents), "deliver")
if err != nil {
t.Fatal(err)
}
command := strings.ReplaceAll(block, "$${", "${")
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*"} {
if !strings.Contains(string(contents), eventTag) {
t.Errorf("workflow tag filters omit %q", eventTag)
}
}
toolBinary := buildWorkflowCLI(t, root)
proxy := writeWorkflowToolProxy(t)
t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) {
const tag = "integrations/ckconfig/v1.2.3"
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),
})
writeRepositoryFile(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Example Consumer Integration v1.2.3\n\nTagged integration note.\n")
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.197"))
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
env["CI_COMMIT_SHA"] = cliGitOutput(t, repository, "rev-parse", "refs/tags/"+tag)
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)
}
if delivery.snapshot().creates != 1 || delivery.snapshot().requests == 0 || delivery.snapshot().tag != tag {
t.Fatalf("page delivery fixture = %#v", delivery.snapshot())
}
cliGitRun(t, repository, "checkout", "main")
writeRepositoryFile(t, repository, "release-modules.tsv", "# changed after release\nroot\tv[01].*\t.\treleasekit-root.json\n")
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.198"))
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "change default branch release selection")
cliGitRun(t, repository, "push", "origin", "main")
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "tool-version=v0.2.197") || strings.Contains(output, "tool-version=v0.2.198") {
t.Fatalf("tag retry did not use its committed tool version: %q", output)
}
if delivery.snapshot().creates != 1 || delivery.snapshot().tag != tag {
t.Fatalf("tag retry did not reuse the tagged mapping: %#v", delivery.snapshot())
}
})
t.Run("binary delivery from physical major module", func(t *testing.T) {
const tag = "integrations/core/v2.1.0"
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "core", Targets: []string{"linux/amd64"}},
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")
prepareWorkflowModuleSum(t, repository, "integrations/core/v2", proxy)
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
t.Fatalf("binary delivery output = %q", output)
}
observed := delivery.snapshot()
if observed.creates != 1 || observed.uploads != 2 || observed.tag != tag {
t.Fatalf("binary delivery fixture = %#v", observed)
}
if _, ok := observed.assets["core-v2.1.0-linux-amd64"]; !ok {
t.Fatalf("binary asset missing: %#v", observed.assets)
}
if _, ok := observed.assets["SHA256SUMS"]; !ok {
t.Fatalf("checksum asset missing: %#v", observed.assets)
}
})
t.Run("binary delivery from virtual major module", func(t *testing.T) {
const tag = "integrations/core/v2.1.0"
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeRepositoryFile(t, repository, "release-modules.tsv", strings.ReplaceAll(readWorkflowFile(t, repository, "release-modules.tsv"), "integrations/core/v2\treleasekit-core-v2.json", "integrations/core\treleasekit-core-v2.json"))
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
Product: "Example Consumer Core v2", ModuleDir: "integrations/core",
Delivery: workflowDeliverySettings(delivery.snapshot().URL),
})
writeRepositoryFile(t, repository, "integrations/core/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/core/v2", "v0.2.197"))
writeRepositoryFile(t, repository, "integrations/core/main.go", readWorkflowFile(t, example, "integrations/core/v2/main.go"))
writeRepositoryFile(t, repository, "integrations/core/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
prepareWorkflowModuleSum(t, repository, "integrations/core", proxy)
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
t.Fatalf("virtual-major delivery output = %q", output)
}
if delivery.snapshot().creates != 1 || delivery.snapshot().tag != tag {
t.Fatalf("virtual-major delivery fixture = %#v", delivery.snapshot())
}
})
t.Run("inconsistent mapping fails exact event tag check", func(t *testing.T) {
const tag = "integrations/ckconfig/v2.1.0"
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
mapping := readWorkflowFile(t, repository, "release-modules.tsv")
mapping = strings.Replace(mapping,
"ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json",
"ckconfig\tintegrations/ckconfig/v*\tintegrations/core/v2\treleasekit-core-v2.json", 1)
writeRepositoryFile(t, repository, "release-modules.tsv", mapping)
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
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\nMismatched mapped note.\n")
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(delivery *mappedDeliveryData) { delivery.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
t.Fatalf("inconsistent mapping succeeded: %s", output)
} else if !strings.Contains(output, tag) || !strings.Contains(output, "integrations/core/v2.1.0") {
t.Fatalf("inconsistent mapping did not fail the exact tag comparison: %s", output)
}
if delivery.snapshot().requests != 0 {
t.Fatalf("exact event tag mismatch reached hosted delivery: %#v", delivery.snapshot())
}
})
}
type mappedDeliveryFixture struct {
mu sync.Mutex
data mappedDeliveryData
}
func (state *mappedDeliveryFixture) update(change func(*mappedDeliveryData)) {
state.mu.Lock()
defer state.mu.Unlock()
change(&state.data)
}
func (state *mappedDeliveryFixture) snapshot() mappedDeliveryData {
state.mu.Lock()
defer state.mu.Unlock()
result := state.data
result.assets = make(map[string][]byte, len(state.data.assets))
for key, value := range state.data.assets {
result.assets[key] = append([]byte(nil), value...)
}
return result
}
type mappedDeliveryData struct {
URL string
tag string
commit string
page bool
name string
body string
creates int
uploads int
requests int
assets map[string][]byte
}
func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
t.Helper()
state := &mappedDeliveryFixture{data: mappedDeliveryData{tag: tag, assets: make(map[string][]byte)}}
data := &state.data
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
defer state.mu.Unlock()
data.requests++
if r.Header.Get("Authorization") != "token fixture-token" {
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
}
apiRoot := "/api/v1/repos/owner/example/"
escapedTag := url.PathEscape(tag)
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:
_ = json.NewEncoder(w).Encode(map[string]any{"name": tag, "commit": map[string]string{"sha": data.commit}})
case apiRoot + "releases/tags/" + escapedTag:
if !data.page {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": data.commit, "name": data.name, "body": data.body, "draft": false, "prerelease": false})
case apiRoot + "releases":
var payload struct {
Tag string `json:"tag_name"`
Commit string `json:"target_commitish"`
Name string `json:"name"`
Body string `json:"body"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Errorf("decode release create: %v", err)
}
if payload.Tag != tag || payload.Commit != data.commit {
t.Errorf("release payload = %#v", payload)
}
data.page = true
data.name = payload.Name
data.body = payload.Body
data.creates++
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": data.commit, "name": payload.Name, "body": payload.Body, "draft": false, "prerelease": false})
case apiRoot + "releases/10/assets":
if r.Method == http.MethodGet {
listing := make([]map[string]any, 0, len(data.assets))
for name, content := range data.assets {
listing = append(listing, map[string]any{"id": len(listing) + 1, "name": name, "size": len(content), "browser_download_url": serverURL(r) + "/files/" + name})
}
_ = json.NewEncoder(w).Encode(listing)
return
}
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Errorf("parse asset upload: %v", err)
http.Error(w, "multipart", http.StatusBadRequest)
return
}
name := r.URL.Query().Get("name")
file, _, err := r.FormFile("attachment")
if err != nil {
t.Errorf("read asset %q: %v", name, err)
http.Error(w, "attachment", http.StatusBadRequest)
return
}
content, err := io.ReadAll(file)
_ = file.Close()
if err != nil {
t.Errorf("read asset bytes: %v", err)
}
data.assets[name] = content
data.uploads++
_ = json.NewEncoder(w).Encode(map[string]any{"id": data.uploads, "name": name, "size": len(content)})
default:
if strings.HasPrefix(r.URL.Path, "/files/") {
name := strings.TrimPrefix(r.URL.Path, "/files/")
if content, ok := data.assets[name]; ok {
_, _ = w.Write(content)
return
}
http.NotFound(w, r)
return
}
t.Errorf("unexpected delivery request %s %s", r.Method, r.URL.EscapedPath())
http.NotFound(w, r)
}
}))
data.URL = "http://" + server.Listener.Addr().String()
server.Start()
t.Cleanup(server.Close)
return state
}
func serverURL(r *http.Request) string {
return "http://" + r.Host
}
func buildWorkflowCLI(t *testing.T, root string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "releasekit")
command := exec.Command("go", "build", "-o", path, "./cmd/releasekit")
command.Dir = root
command.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
if output, err := command.CombinedOutput(); err != nil {
t.Fatalf("build workflow CLI: %v\n%s", err, output)
}
return path
}
func writeWorkflowToolProxy(t *testing.T) string {
t.Helper()
const module = "go.maximumdirect.net/releasekit"
const helper = "example.com/releasekit-helper"
proxyDir := t.TempDir()
moduleFile := "module " + module + "\n\ngo 1.25.0\n\nrequire " + helper + " v1.0.0\n"
for _, version := range []string{"v0.2.197", "v0.2.198"} {
main := fmt.Sprintf(`package main
import (
"fmt"
"os"
"os/exec"
helper "%s"
)
func main() {
fmt.Println("tool-version=%s helper=" + helper.Version)
command := exec.Command(os.Getenv("RELEASEKIT_TEST_BINARY"), os.Args[1:]...)
command.Env = os.Environ()
command.Stdout = os.Stdout
command.Stderr = os.Stderr
if err := command.Run(); err != nil {
if exit, ok := err.(*exec.ExitError); ok { os.Exit(exit.ExitCode()) }
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
`, helper, version)
files := map[string]string{
"cmd/releasekit/main.go": main,
"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",
}
writeModuleProxyVersion(t, proxyDir, module, version, moduleFile, files)
}
writeModuleProxyVersion(t, proxyDir, helper, "v1.0.0", "module "+helper+"\n\ngo 1.25.0\n", map[string]string{"helper.go": "package helper\nconst Version = \"tagged dependency\"\n"})
return proxyDir
}
func newWorkflowRepository(t *testing.T, example string) string {
t.Helper()
repository := filepath.Join(t.TempDir(), "multi module checkout")
if err := os.Mkdir(repository, 0o700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, example, repository)
for _, selection := range []struct{ directory, module string }{
{".", "example.com/multi-module-consumer"},
{"integrations/ckconfig", "example.com/multi-module-consumer/integrations/ckconfig"},
{"integrations/core/v2", "example.com/multi-module-consumer/integrations/core/v2"},
} {
writeRepositoryFile(t, repository, selection.directory+"/go.mod", workflowModuleFile(selection.module, "v0.2.197"))
}
cliGitRun(t, repository, "init", "--initial-branch=main")
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
cliGitRun(t, repository, "config", "commit.gpgsign", "false")
return repository
}
func workflowModuleFile(module, version string) string {
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 {
return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"}
}
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {
t.Helper()
contents, err := json.MarshalIndent(settings, "", " ")
if err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repository, name, string(contents)+"\n")
}
func tagAndPushWorkflowRepository(t *testing.T, repository, tag string) string {
t.Helper()
cliGitRun(t, repository, "add", "--all")
cliGitRun(t, repository, "commit", "-m", "prepare mapped delivery")
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
cliGitRun(t, repository, "tag", "-a", tag, "-m", "mapped release")
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)
return commit
}
func multiModuleWorkflowEnvironment(t *testing.T, repository, commit, tag, binary, proxy string) map[string]string {
t.Helper()
goDir, goLog := installGoBootstrapShim(t)
environment := templateEnvironment(repository, commit, goDir, goLog)
environment["CI_COMMIT_TAG"] = tag
environment["RELEASEKIT_TEST_BINARY"] = binary
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
cache := environment["GOMODCACHE"]
t.Cleanup(func() {
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
if err == nil && entry.IsDir() {
_ = os.Chmod(path, 0o700)
}
return nil
})
})
return environment
}
func prepareWorkflowModuleSum(t *testing.T, repository, moduleDir, proxy string) {
t.Helper()
cache := t.TempDir()
t.Cleanup(func() {
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
if err == nil && entry.IsDir() {
_ = os.Chmod(path, 0o700)
}
return nil
})
})
command := exec.Command("go", "mod", "download", "go.maximumdirect.net/releasekit@v0.2.197")
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")
if output, err := command.CombinedOutput(); err != nil {
t.Fatalf("prepare tagged module sums: %v\n%s", err, output)
}
}
func readWorkflowFile(t *testing.T, repository, name string) string {
t.Helper()
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
if err != nil {
t.Fatal(err)
}
return string(contents)
}

View File

@@ -79,9 +79,10 @@ 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",
"repository": "releasekit",
"token_env": "RELEASEKIT_GITEA_TOKEN", "token_env": "RELEASEKIT_GITEA_TOKEN",
}, },
} }

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.TokenEnv != "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")
@@ -37,9 +37,9 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
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)
@@ -50,14 +50,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
cliGitRun(t, repository, "add", "docs/releases/"+version+".md") cliGitRun(t, repository, "add", "docs/releases/"+version+".md")
cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery") cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery")
state := &deliveryServerState{product: "ReleaseKit"} state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
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.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")
remote := filepath.Join(t.TempDir(), "origin.git") remote := filepath.Join(t.TempDir(), "origin.git")
@@ -78,7 +78,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
} }
env := map[string]string{ env := map[string]string{
"CI_WORKSPACE": repository, "CI_WORKSPACE": repository,
"CI_COMMIT_SHA": state.commit, "CI_COMMIT_SHA": cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version),
"CI_COMMIT_TAG": version, "CI_COMMIT_TAG": version,
"RELEASEKIT_GITEA_TOKEN": "fixture-token", "RELEASEKIT_GITEA_TOKEN": "fixture-token",
"GOTOOLCHAIN": "local", "GOTOOLCHAIN": "local",
@@ -87,14 +87,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
} }
command := strings.ReplaceAll(block, "$${", "${") command := strings.ReplaceAll(block, "$${", "${")
state.remoteCommit = strings.Repeat("f", 40) state.update(func(state *deliveryServerData) { state.remoteCommit = strings.Repeat("f", 40) })
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil { if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output) t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output)
} }
if state.releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.commit { if state.snapshot().releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.snapshot().commit {
t.Fatal("delivery failure changed hosted release state or source tag") t.Fatal("delivery failure changed hosted release state or source tag")
} }
state.remoteCommit = "" state.update(func(state *deliveryServerData) { state.remoteCommit = "" })
for attempt := 0; attempt < 2; attempt++ { for attempt := 0; attempt < 2; attempt++ {
output := runWoodpeckerBlock(t, command, repository, env) output := runWoodpeckerBlock(t, command, repository, env)
@@ -102,14 +102,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
t.Fatalf("delivery attempt %d output = %q", attempt+1, output) t.Fatalf("delivery attempt %d output = %q", attempt+1, output)
} }
} }
if state.releaseCreates != 1 || state.assetUploads != 0 || state.assetListReads != 0 { if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 || state.snapshot().assetListReads != 0 {
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.releaseCreates, state.assetUploads, state.assetListReads) t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads, state.snapshot().assetListReads)
} }
if state.noteBody != note { if state.snapshot().noteBody != note {
t.Fatalf("hosted note body = %q, want complete note %q", state.noteBody, note) t.Fatalf("hosted note body = %q, want complete note %q", state.snapshot().noteBody, note)
} }
if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.commit { if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.snapshot().commit {
t.Fatalf("source tag moved after delivery: %s, want %s", got, state.commit) t.Fatalf("source tag moved after delivery: %s, want %s", got, state.snapshot().commit)
} }
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" { if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
t.Fatalf("tagged checkout became dirty after delivery: %s", status) t.Fatalf("tagged checkout became dirty after delivery: %s", status)

View File

@@ -0,0 +1,34 @@
package main
import (
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestNativeCheckFromChildUsesRootProfileAndSuite(t *testing.T) {
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
repository := newCLIRepository(t)
writeRepositoryFile(t, repository, "candidate_test.go", "package candidate\nimport \"testing\"\nfunc TestFixture(t *testing.T) { t.Fatal(\"root suite failure\") }\n")
writeRepositoryFile(t, repository, "releasekit.json", `{"product":"Example Product"}`)
writeRepositoryFile(t, repository, "apps/widget/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
writeRepositoryFile(t, repository, "apps/widget/widget_test.go", "package widget\nimport \"testing\"\nfunc TestWidget(t *testing.T) {}\n")
cliGitRun(t, repository, "add", ".")
cliGitRun(t, repository, "commit", "-m", "Add failing root and passing child")
command := exec.Command(binary, "check", "v1.2.3")
command.Dir = filepath.Join(repository, "apps", "widget")
output, err := command.CombinedOutput()
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || !strings.Contains(string(output), "root suite failure") || !strings.Contains(string(output), "module=example.com/cli-candidate") {
t.Fatalf("child invocation error = %v, output = %s", err, output)
}
}
func TestNativeBuildClassifiesInvalidVersionBeforeSourceAccess(t *testing.T) {
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
command := exec.Command(binary, "build", "--repo", filepath.Join(t.TempDir(), "absent"), "bad-version")
output, err := command.CombinedOutput()
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "stable vMAJOR.MINOR.PATCH") {
t.Fatalf("invalid build error = %v, output = %s", err, output)
}
}

View File

@@ -0,0 +1,111 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestDeliveryTokenFileSelection(t *testing.T) {
for _, test := range []struct {
name, env, contents, file, want string
status int
}{
{name: "relative file", contents: "fixture-token\n", file: "token", want: "fixture-token"},
{name: "absolute file", contents: "fixture-token\n", file: "absolute", want: "fixture-token"},
{name: "environment overrides missing file", env: "env-token", file: "missing", want: "env-token"},
{name: "blank environment falls back", env: " \t", contents: "fixture-token\n", file: "token", want: "fixture-token"},
{name: "missing file", file: "missing", status: 2},
{name: "blank file", contents: " \n\t", file: "token", status: 2},
{name: "empty file", file: "token", status: 2},
{name: "unreadable as file", file: ".", status: 2},
{name: "no credential", status: 2},
} {
t.Run(test.name, func(t *testing.T) {
repository := t.TempDir()
if err := os.WriteFile(filepath.Join(repository, "token"), []byte(test.contents), 0o600); err != nil {
t.Fatal(err)
}
name := test.file
if name == "absolute" {
name = filepath.Join(repository, "token")
}
t.Setenv("RELEASEKIT_TEST_TOKEN", test.env)
var stderr bytes.Buffer
destination, status := deliveryDestination(repository, cli.Settings{Delivery: &cli.DeliverySettings{Forge: "gitea",
BaseURL: "https://gitea.example", Owner: "owner", Repository: "example",
TokenEnv: "RELEASEKIT_TEST_TOKEN", TokenFile: name,
}}, &stderr)
if status != test.status || destination.Token != test.want {
t.Fatalf("status=%d token matches=%t, want status=%d; diagnostics=%s", status, destination.Token == test.want, test.status, &stderr)
}
for _, secret := range []string{"fixture-token", "env-token"} {
if strings.Contains(stderr.String(), secret) {
t.Fatal("diagnostics exposed a 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", 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 TestDeliverAndCIDeliverReadTokenFileFromRepositoryRoot(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", TokenFile: ".releasekit/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 })
writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n")
t.Setenv("RELEASEKIT_GITEA_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,10 +39,10 @@ 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.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)
@@ -51,8 +51,8 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
if !strings.Contains(output, "state complete") { if !strings.Contains(output, "state complete") {
t.Fatalf("delivery output=%q", output) t.Fatalf("delivery output=%q", output)
} }
if state.releaseCreates != 1 || state.assetUploads != 0 { if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads) t.Fatalf("source-only calls = creates:%d uploads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads)
} }
assertModuleBootstrap(t, repository, goLog, moduleBefore) assertModuleBootstrap(t, repository, goLog, moduleBefore)
}) })
@@ -70,10 +70,10 @@ 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.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)
@@ -88,14 +88,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
t.Fatalf("second delivery did not reuse matching assets: %q", output) t.Fatalf("second delivery did not reuse matching assets: %q", output)
} }
} }
if state.releaseCreates != 1 || state.assetUploads != 2 { if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 2 {
t.Fatalf("binary calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads) t.Fatalf("binary calls = creates:%d uploads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads)
} }
if _, ok := state.assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok { if _, ok := state.snapshot().assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
t.Fatalf("binary asset was not delivered: %#v", state.assets) t.Fatalf("binary asset was not delivered: %#v", state.snapshot().assets)
} }
if _, ok := state.assets["SHA256SUMS"]; !ok { if _, ok := state.snapshot().assets["SHA256SUMS"]; !ok {
t.Fatalf("checksum manifest was not delivered: %#v", state.assets) t.Fatalf("checksum manifest was not delivered: %#v", state.snapshot().assets)
} }
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore) assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
}) })
@@ -104,10 +104,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
repository := newCLIRepository(t) repository := newCLIRepository(t)
selectReleaseKitModule(t, repository, root, false) selectReleaseKitModule(t, repository, root, false)
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
cliGitRun(t, repository, "commit", "--allow-empty", "-m", "unrelated event commit")
unrelated := cliGitOutput(t, repository, "rev-parse", "HEAD")
goDir, goLog := installControlledGoBootstrapShim(t) goDir, goLog := installControlledGoBootstrapShim(t)
env := templateEnvironment(repository, strings.Repeat("f", len(commit)), goDir, goLog) env := templateEnvironment(repository, unrelated, goDir, goLog)
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) {
t.Fatalf("tag mismatch omitted commit identities: %s", output)
} }
assertNoCommands(t, goLog) assertNoCommands(t, goLog)
}) })
@@ -126,30 +130,66 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
}) })
t.Run("selected executable receives event arguments and its status", func(t *testing.T) { t.Run("selected executable receives event arguments and its status", func(t *testing.T) {
repository := newCLIRepository(t) for _, event := range []struct {
selectReleaseKitModule(t, repository, root, false) name, tag string
commit := pushTaggedCLIRepository(t, repository) tagObject bool
goDir, goLog := installControlledGoBootstrapShim(t) }{
toolArgs := filepath.Join(t.TempDir(), "tool-arguments") {"lightweight commit", "v1.2.3", false},
env := templateEnvironment(repository, strings.ToUpper(commit), goDir, goLog) {"annotated commit", "v1.2.4", false},
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs {"annotated tag object", "v1.2.4", true},
env["RELEASEKIT_TOOL_EXIT"] = "37" } {
output, err := executeWoodpeckerBlock(command, repository, env) t.Run(event.name, func(t *testing.T) {
var exitError *exec.ExitError repository := newCLIRepository(t)
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 { selectReleaseKitModule(t, repository, root, false)
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output) commit := pushTaggedCLIRepository(t, repository)
if event.tag == "v1.2.4" {
cliGitRun(t, repository, "tag", "-a", event.tag, "-m", "annotated release")
cliGitRun(t, repository, "push", "origin", "refs/tags/"+event.tag)
}
eventID := commit
if event.tagObject {
eventID = cliGitOutput(t, repository, "rev-parse", "refs/tags/"+event.tag)
}
goDir, goLog := installControlledGoBootstrapShim(t)
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
env := templateEnvironment(repository, strings.ToUpper(eventID), goDir, goLog)
env["CI_COMMIT_TAG"] = event.tag
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
env["RELEASEKIT_TOOL_EXIT"] = "37"
output, err := executeWoodpeckerBlock(command, repository, env)
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 {
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output)
}
args := readWoodpeckerFixtureFile(t, toolArgs)
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--prepared>", "<" + event.tag + ">"} {
if !strings.Contains(args, expected) {
t.Errorf("selected executable arguments %q omit %q", args, expected)
}
}
if !strings.Contains(strings.ToLower(args), "<--commit>\n<"+commit+">") {
t.Errorf("selected executable did not receive source commit %s: %q", commit, args)
}
assertGoSelection(t, repository, goLog)
})
} }
args := readWoodpeckerFixtureFile(t, toolArgs)
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--commit>", "<" + strings.ToUpper(commit) + ">", "<v1.2.3>"} {
if !strings.Contains(args, expected) {
t.Errorf("selected executable arguments %q omit %q", args, expected)
}
}
assertGoSelection(t, repository, goLog)
}) })
} }
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) { func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
// Synthetic downloads must leave the caller's module cache untouched.
callerCache := t.TempDir()
t.Setenv("GOMODCACHE", callerCache)
t.Cleanup(func() {
entries, err := os.ReadDir(callerCache)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Errorf("synthetic module downloads modified the caller's cache: %v", entries)
}
})
root := cliRepositoryRoot(t) root := cliRepositoryRoot(t)
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml")) contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml"))
if err != nil { if err != nil {
@@ -165,7 +205,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")
@@ -185,7 +225,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["GOPROXY"] = "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
output := runWoodpeckerBlock(t, command, repository, env) output := runWoodpeckerBlock(t, command, repository, env)
@@ -199,7 +239,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
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")
@@ -207,7 +247,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["GOPROXY"] = "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
output := runWoodpeckerBlock(t, command, repository, env) output := runWoodpeckerBlock(t, command, repository, env)
@@ -245,21 +285,15 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
defer proxy.Close() defer proxy.Close()
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+dependency+" v1.0.0\n") writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+dependency+" v1.0.0\n")
writeRepositoryFile(t, repository, "cmd/releasekit/main.go", "package main\n\nimport (\"fmt\"; \"os\"; helper \""+dependency+"\")\n\nfunc main() {\n\tfmt.Println(\"self-bootstrap \" + helper.Message)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n") writeRepositoryFile(t, repository, "cmd/releasekit/main.go", "package main\n\nimport (\"fmt\"; \"os\"; helper \""+dependency+"\")\n\nfunc main() {\n\tfmt.Println(\"self-bootstrap \" + helper.Message)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n")
preparationEnv := map[string]string{ preparationEnv := map[string]string{}
"GOPROXY": proxy.URL, "GOSUMDB": "off", "GONOPROXY": "none", "GOPRIVATE": "", useSyntheticModuleProxy(t, preparationEnv, proxy.URL)
"GOWORK": "off", "GOTOOLCHAIN": "local", "GOENV": "off", "GOFLAGS": "-modcacherw",
"GOMODCACHE": t.TempDir(),
}
runWoodpeckerBlock(t, "go mod download "+dependency, repository, preparationEnv) runWoodpeckerBlock(t, "go mod download "+dependency, repository, preparationEnv)
cliGitRun(t, repository, "add", "cmd/releasekit/main.go", "go.mod", "go.sum") cliGitRun(t, repository, "add", "cmd/releasekit/main.go", "go.mod", "go.sum")
cliGitRun(t, repository, "commit", "-m", "add the self-bootstrapped command") cliGitRun(t, repository, "commit", "-m", "add the self-bootstrapped command")
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)
for key, value := range preparationEnv { useSyntheticModuleProxy(t, env, proxy.URL)
env[key] = value
}
env["GOMODCACHE"] = t.TempDir()
proxyRequests.Store(0) proxyRequests.Store(0)
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit)) env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil { if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
@@ -277,7 +311,7 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
if proxyRequests.Load() == 0 { if proxyRequests.Load() == 0 {
t.Fatal("self-bootstrap did not prepare its dependency from the local proxy") t.Fatal("self-bootstrap did not prepare its dependency from the local proxy")
} }
if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"v1.2.3"`) { if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"--prepared"`) || !strings.Contains(output, `"v1.2.3"`) {
t.Fatalf("self-bootstrapped command arguments = %q", output) t.Fatalf("self-bootstrapped command arguments = %q", output)
} }
log := readWoodpeckerFixtureFile(t, goLog) log := readWoodpeckerFixtureFile(t, goLog)
@@ -426,6 +460,19 @@ esac
return shimDir, goLog return shimDir, goLog
} }
func useSyntheticModuleProxy(t *testing.T, environment map[string]string, proxyURL string) {
t.Helper()
environment["GOMODCACHE"] = t.TempDir()
environment["GOPROXY"] = proxyURL
environment["GOSUMDB"] = "off"
environment["GONOPROXY"] = "none"
environment["GOPRIVATE"] = ""
environment["GOWORK"] = "off"
environment["GOTOOLCHAIN"] = "local"
environment["GOENV"] = "off"
environment["GOFLAGS"] = "-modcacherw"
}
func templateEnvironment(repository, commit, shimDir, goLog string) map[string]string { func templateEnvironment(repository, commit, shimDir, goLog string) map[string]string {
realGo, _ := exec.LookPath("go") realGo, _ := exec.LookPath("go")
return map[string]string{ return map[string]string{
@@ -433,7 +480,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",
@@ -466,8 +513,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.25.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.26.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 {
@@ -479,7 +526,7 @@ 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"
@@ -587,7 +634,7 @@ func assertGoSelection(t *testing.T, repository, goLog string) {
log := readWoodpeckerFixtureFile(t, goLog) log := readWoodpeckerFixtureFile(t, goLog)
list := "list -mod=mod -modfile=" list := "list -mod=mod -modfile="
build := "build -mod=mod -modfile=" build := "build -mod=mod -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)
} }

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,30 +29,84 @@ 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 RepositoryDir string // directory within the tagged source Git checkout.
Product string // ModuleDir selects a repository-relative module directory; empty selects
Version string // the repository root.
Destination GiteaDestination ModuleDir string
Product string
Version string
// ExpectedTag optionally requires the full CI event tag to match the
// selected module's derived tag before building or making hosted requests.
ExpectedTag string
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.
@@ -58,11 +116,16 @@ 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 {
Version string RepositoryDir string
ModuleDir string
ModulePath string
Tag string // complete derived Git tag.
Version string // selected stable semantic version.
CandidateCommit string CandidateCommit string
ReleaseURL string ReleaseURL string
State DeliveryState State DeliveryState
@@ -78,16 +141,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.
// Page-only delivery can use a sparse checkout with available committed objects;
// 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 {
@@ -95,13 +164,19 @@ 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,
Product: request.Product, Product: request.Product,
Version: request.Version, Version: request.Version,
Destination: destination, ExpectedTag: request.ExpectedTag,
Backend: backend,
Build: internalBuildSpec(request.Build), Build: internalBuildSpec(request.Build),
Prebuilt: prebuilt, Prebuilt: prebuilt,
Output: request.Output, Output: request.Output,
}) })
result.RepositoryDir = internalResult.RepositoryDir
result.ModuleDir = internalResult.ModuleDir
result.ModulePath = internalResult.ModulePath
result.Tag = internalResult.Tag
result.CandidateCommit = internalResult.CandidateCommit result.CandidateCommit = internalResult.CandidateCommit
result.ReleaseURL = internalResult.ReleaseURL result.ReleaseURL = internalResult.ReleaseURL
result.State = DeliveryState(internalResult.State) result.State = DeliveryState(internalResult.State)
@@ -110,10 +185,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, publicPreflightError(err)
} }
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

@@ -8,15 +8,186 @@ import (
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
"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()
@@ -40,11 +211,12 @@ func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.
if err != nil { if err != nil {
t.Fatalf("Deliver() error = %v; result = %#v", err, result) t.Fatalf("Deliver() error = %v; result = %#v", err, result)
} }
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit { observed := remote.snapshot()
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != observed.commit {
t.Fatalf("delivery result = %#v", result) t.Fatalf("delivery result = %#v", result)
} }
if len(result.Uploaded) != 2 || len(remote.assets) != 2 { if len(result.Uploaded) != 2 || len(observed.assets) != 2 {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets)) t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
} }
if !strings.Contains(progress.String(), "checking fixture version output") { if !strings.Contains(progress.String(), "checking fixture version output") {
t.Fatalf("build progress = %q", progress.String()) t.Fatalf("build progress = %q", progress.String())
@@ -78,7 +250,8 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Deliver() error = %v; result = %#v", err, result) t.Fatalf("Deliver() error = %v; result = %#v", err, result)
} }
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit { observed := remote.snapshot()
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != observed.commit {
t.Fatalf("delivery result = %#v", result) t.Fatalf("delivery result = %#v", result)
} }
wantAssets := []string{ wantAssets := []string{
@@ -86,12 +259,12 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
"fixture-v1.2.3-linux-arm64", "fixture-v1.2.3-linux-arm64",
"SHA256SUMS", "SHA256SUMS",
} }
if len(result.Uploaded) != len(wantAssets) || len(remote.assets) != len(wantAssets) { if len(result.Uploaded) != len(wantAssets) || len(observed.assets) != len(wantAssets) {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets)) t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
} }
for _, name := range wantAssets { for _, name := range wantAssets {
if _, ok := remote.assets[name]; !ok { if _, ok := observed.assets[name]; !ok {
t.Errorf("hosted assets omit %q: %v", name, mapKeys(remote.assets)) t.Errorf("hosted assets omit %q: %v", name, mapKeys(observed.assets))
} }
} }
if !strings.Contains(progress.String(), "checking fixture version output") { if !strings.Contains(progress.String(), "checking fixture version output") {
@@ -134,6 +307,78 @@ 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) {
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: filepath.Join(t.TempDir(), "caller-owned-assets"),
})
if err != nil {
t.Fatalf("Build() error = %v", err)
}
contents, err := os.ReadFile(prebuilt.Artifacts[0].Path)
if err != nil {
t.Fatal(err)
}
if len(contents) == 0 {
t.Fatal("built artifact is empty")
}
contents[0] ^= 0xff
if err := os.WriteFile(prebuilt.Artifacts[0].Path, contents, 0o600); err != nil {
t.Fatal(err)
}
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),
Prebuilt: &prebuilt,
})
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)
}
if remote.snapshot().writes != 0 {
t.Fatalf("hosted writes = %d, want none before local verification", remote.snapshot().writes)
}
}
func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) { func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
name string name string
@@ -146,6 +391,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
repository := newTaggedDeliveryConsumer(t) repository := newTaggedDeliveryConsumer(t)
prebuilt := test.prebuilt
if prebuilt != nil {
built, err := releasekit.Build(context.Background(), releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3"})
if err != nil {
t.Fatalf("Build() for page-only prebuilt identity = %#v, %v", built, err)
}
prebuilt = &built
}
temporaryRoot := t.TempDir() temporaryRoot := t.TempDir()
t.Setenv("TMPDIR", temporaryRoot) t.Setenv("TMPDIR", temporaryRoot)
server, remote := newFacadeDeliveryServer(t, repository) server, remote := newFacadeDeliveryServer(t, repository)
@@ -158,14 +411,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
Version: "v1.2.3", Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL), Destination: facadeDeliveryDestination(server.URL),
Build: test.build, Build: test.build,
Prebuilt: test.prebuilt, Prebuilt: prebuilt,
Output: &progress, Output: &progress,
}) })
if err != nil || result.State != releasekit.DeliveryComplete { if err != nil || result.State != releasekit.DeliveryComplete {
t.Fatalf("Deliver() = %#v, %v", result, err) t.Fatalf("Deliver() = %#v, %v", result, err)
} }
if len(remote.assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 { if len(remote.snapshot().assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 {
t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.assets)) t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.snapshot().assets))
} }
if progress.Len() != 0 { if progress.Len() != 0 {
t.Fatalf("page-only delivery emitted build progress: %q", progress.String()) t.Fatalf("page-only delivery emitted build progress: %q", progress.String())
@@ -177,6 +430,131 @@ 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) {
repository := newTwoModuleDeliveryConsumer(t)
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
wrongTag, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository,
Product: "Fixture",
Version: "v1.2.3",
ExpectedTag: "integrations/wrong/v1.2.3",
Destination: facadeDeliveryDestination(server.URL),
})
if err == nil || wrongTag.Tag != "v1.2.3" || remote.snapshot().requests != 0 {
t.Fatalf("delivery with inconsistent expected tag = %#v, %v; hosted requests %d", wrongTag, err, remote.snapshot().requests)
}
rootResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository,
Product: "Fixture",
Version: "v1.2.3",
ExpectedTag: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL),
})
if err != nil || rootResult.State != releasekit.DeliveryComplete || rootResult.Tag != "v1.2.3" {
t.Fatalf("root delivery = %#v, %v", rootResult, err)
}
nestedTag := "integrations/ckconfig/v1.2.3"
remote.update(func(remote *facadeDeliveryData) {
remote.tag = nestedTag
remote.noteBody = "# Fixture v1.2.3\n\nNested delivery fixture.\n"
})
nestedResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository,
ModuleDir: "integrations/ckconfig",
Product: "Fixture",
Version: "v1.2.3",
ExpectedTag: nestedTag,
Destination: facadeDeliveryDestination(server.URL),
})
if err != nil || nestedResult.State != releasekit.DeliveryComplete || nestedResult.Tag != nestedTag || nestedResult.ModulePath != "example.com/ckconfig" {
t.Fatalf("nested delivery = %#v, %v", nestedResult, err)
}
if len(remote.snapshot().pages) != 2 || !remote.snapshot().pages["v1.2.3"] || !remote.snapshot().pages[nestedTag] {
t.Fatalf("created hosted pages = %#v", remote.snapshot().pages)
}
}
func TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests(t *testing.T) {
repository := newTwoModuleDeliveryConsumer(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: filepath.Join(t.TempDir(), "root-artifacts"),
})
if err != nil || !prebuilt.SourceVerified {
t.Fatalf("root Build() = %#v, %v", prebuilt, err)
}
server, remote := newFacadeDeliveryServer(t, repository)
defer server.Close()
remote.update(func(remote *facadeDeliveryData) { remote.tag = "integrations/ckconfig/v1.2.3" })
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
RepositoryDir: repository,
ModuleDir: "integrations/ckconfig",
Product: "Fixture",
Version: "v1.2.3",
ExpectedTag: remote.snapshot().tag,
Destination: facadeDeliveryDestination(server.URL),
Prebuilt: &prebuilt,
})
if err == nil || !strings.Contains(err.Error(), "selected tagged module") || result.Tag != remote.snapshot().tag {
t.Fatalf("nested delivery with root artifacts = %#v, %v", result, err)
}
if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests before prebuilt identity rejection = %d", remote.snapshot().requests)
}
}
func newTwoModuleDeliveryConsumer(t *testing.T) string {
t.Helper()
repository := newTaggedDeliveryConsumer(t)
writeNestedBuildConsumer(t, repository, "integrations/ckconfig", "example.com/ckconfig", `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()) } }
`)
writeBuildFixture(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Fixture v1.2.3\n\nNested delivery fixture.\n")
buildGit(t, repository, "add", "--all")
buildGit(t, repository, "commit", "-m", "add nested release module")
buildGit(t, repository, "tag", "-f", "v1.2.3")
buildGit(t, repository, "tag", "integrations/ckconfig/v1.2.3")
return repository
}
func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T) { func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T) {
repository := newTaggedDeliveryConsumer(t) repository := newTaggedDeliveryConsumer(t)
writeBuildFixture(t, repository, "local-change.txt", "dirty source") writeBuildFixture(t, repository, "local-change.txt", "dirty source")
@@ -198,19 +576,20 @@ func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T)
}, },
Output: &progress, Output: &progress,
}) })
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit { if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
t.Fatalf("Deliver() = %#v, %v; want preflight failure for known commit", result, err) t.Fatalf("Deliver() = %#v, %v; want preflight failure for known commit", result, err)
} }
if progress.Len() != 0 { if progress.Len() != 0 {
t.Fatalf("build started before source eligibility passed: %q", progress.String()) t.Fatalf("build started before source eligibility passed: %q", progress.String())
} }
if remote.requests != 0 { if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests) t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
} }
} }
func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) { func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) {
repository := newTaggedDeliveryConsumer(t) repository := newTaggedDeliveryConsumer(t)
tagCommit := buildGit(t, repository, "rev-parse", "HEAD")
writeBuildFixture(t, repository, "later-change.txt", "new commit") writeBuildFixture(t, repository, "later-change.txt", "new commit")
buildGit(t, repository, "add", "--all") buildGit(t, repository, "add", "--all")
buildGit(t, repository, "commit", "-m", "advance checkout after release tag") buildGit(t, repository, "commit", "-m", "advance checkout after release tag")
@@ -232,14 +611,14 @@ func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T
}, },
Output: &progress, Output: &progress,
}) })
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == remote.commit { if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == tagCommit {
t.Fatalf("Deliver() = %#v, %v; want tag/HEAD mismatch", result, err) t.Fatalf("Deliver() = %#v, %v; want tag/HEAD mismatch", result, err)
} }
if progress.Len() != 0 { if progress.Len() != 0 {
t.Fatalf("build started before tag/HEAD agreement: %q", progress.String()) t.Fatalf("build started before tag/HEAD agreement: %q", progress.String())
} }
if remote.requests != 0 { if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests) t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
} }
} }
@@ -263,14 +642,14 @@ func TestDeliverRejectsInvalidCommittedNoteBeforeBuildOrHostedWrites(t *testing.
}, },
Output: &progress, Output: &progress,
}) })
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit { if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.snapshot().commit {
t.Fatalf("Deliver() = %#v, %v; want committed-note preflight failure", result, err) t.Fatalf("Deliver() = %#v, %v; want committed-note preflight failure", result, err)
} }
if progress.Len() != 0 { if progress.Len() != 0 {
t.Fatalf("build started before committed-note validation: %q", progress.String()) t.Fatalf("build started before committed-note validation: %q", progress.String())
} }
if remote.requests != 0 { if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests) t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
} }
} }
@@ -304,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.requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.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)
@@ -330,11 +709,11 @@ func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *te
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}, Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
}, },
}) })
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.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.requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.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)
@@ -366,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.requests != 0 { if remote.snapshot().writes != 0 {
t.Fatalf("hosted requests = %d, want none", remote.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)
@@ -390,8 +769,8 @@ func TestDeliverRejectsBothBuildSourcesBeforeHostedWrites(t *testing.T) {
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") { if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") {
t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err) t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err)
} }
if remote.requests != 0 { if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests) t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
} }
} }
@@ -405,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()) } }
`) `)
@@ -416,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 }
@@ -427,35 +806,109 @@ 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 {
t *testing.T mu sync.Mutex
commit string data facadeDeliveryData
page bool }
requests int
assets map[string][]byte func (state *facadeDeliveryServer) update(change func(*facadeDeliveryData)) {
url string state.mu.Lock()
defer state.mu.Unlock()
change(&state.data)
}
func (state *facadeDeliveryServer) snapshot() facadeDeliveryData {
state.mu.Lock()
defer state.mu.Unlock()
result := state.data
result.assets = make(map[string][]byte, len(state.data.assets))
for key, value := range state.data.assets {
result.assets[key] = append([]byte(nil), value...)
}
result.pages = make(map[string]bool, len(state.data.pages))
for key, value := range state.data.pages {
result.pages[key] = value
}
return result
}
type facadeDeliveryData struct {
t *testing.T
commit string
tag string
version string
noteBody string
createdBody string
pages map[string]bool
requests int
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) {
t.Helper() t.Helper()
state := &facadeDeliveryServer{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), assets: make(map[string][]byte)} state := &facadeDeliveryServer{data: facadeDeliveryData{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), tag: "v1.2.3", version: "v1.2.3", noteBody: "# Fixture v1.2.3\n\nDelivery fixture.\n", pages: make(map[string]bool), assets: make(map[string][]byte)}}
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP)) server := httptest.NewUnstartedServer(http.HandlerFunc(state.serveHTTP))
state.url = server.URL state.data.url = "http://" + server.Listener.Addr().String()
server.Start()
return server, state return server, state
} }
func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Request) { func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
defer state.mu.Unlock()
data := &state.data
if strings.HasPrefix(r.URL.Path, "/api/") { if strings.HasPrefix(r.URL.Path, "/api/") {
state.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" {
state.t.Errorf("authorization = %q", r.Header.Get("Authorization")) data.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
} }
} }
switch r.URL.Path { switch r.URL.EscapedPath() {
case "/api/v1/repos/owner/example/tags/v1.2.3": case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_, _ = fmt.Fprintf(w, `{"name":"v1.2.3","commit":{"sha":%q}}`, state.commit) _ = json.NewEncoder(w).Encode(map[string]any{
case "/api/v1/repos/owner/example/releases/tags/v1.2.3": "id": 1, "name": "example", "full_name": "owner/example",
if !state.page { "owner": map[string]string{"login": "owner"},
})
case "/api/v1/repos/owner/example/tags/" + url.PathEscape(data.tag):
_, _ = fmt.Fprintf(w, `{"name":%q,"commit":{"sha":%q}}`, data.tag, data.commit)
case "/api/v1/repos/owner/example/releases/tags/" + url.PathEscape(data.tag):
if !data.pages[data.tag] {
http.NotFound(w, r) http.NotFound(w, r)
return return
} }
@@ -468,20 +921,21 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
Body string `json:"body"` Body string `json:"body"`
} }
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
state.t.Errorf("decode release payload: %v", err) data.t.Errorf("decode release payload: %v", err)
http.Error(w, "invalid payload", http.StatusBadRequest) http.Error(w, "invalid payload", http.StatusBadRequest)
return return
} }
if payload.Tag != "v1.2.3" || payload.Target != state.commit || payload.Name != "Fixture v1.2.3" { if payload.Tag != data.tag || payload.Target != data.commit || payload.Name != "Fixture "+data.version {
state.t.Errorf("release payload = %#v", payload) data.t.Errorf("release payload = %#v", payload)
} }
state.page = true data.createdBody = payload.Body
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":
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
list := make([]map[string]any, 0, len(state.assets)) list := make([]map[string]any, 0, len(data.assets))
for name, content := range state.assets { for name, content := range data.assets {
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": state.url + "/files/" + name}) list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": data.url + "/files/" + name})
} }
_ = json.NewEncoder(w).Encode(list) _ = json.NewEncoder(w).Encode(list)
return return
@@ -489,22 +943,22 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
name := r.URL.Query().Get("name") name := r.URL.Query().Get("name")
file, _, err := r.FormFile("attachment") file, _, err := r.FormFile("attachment")
if err != nil { if err != nil {
state.t.Errorf("read upload %q: %v", name, err) data.t.Errorf("read upload %q: %v", name, err)
http.Error(w, "invalid multipart upload", http.StatusBadRequest) http.Error(w, "invalid multipart upload", http.StatusBadRequest)
return return
} }
content, err := io.ReadAll(file) content, err := io.ReadAll(file)
_ = file.Close() _ = file.Close()
if err != nil { if err != nil {
state.t.Errorf("read upload %q: %v", name, err) data.t.Errorf("read upload %q: %v", name, err)
} }
state.assets[name] = content data.assets[name] = content
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{"id": len(state.assets), "name": name, "size": len(content)}) _ = json.NewEncoder(w).Encode(map[string]any{"id": len(data.assets), "name": name, "size": len(content)})
default: default:
if strings.HasPrefix(r.URL.Path, "/files/") { if strings.HasPrefix(r.URL.Path, "/files/") {
name := strings.TrimPrefix(r.URL.Path, "/files/") name := strings.TrimPrefix(r.URL.Path, "/files/")
content, ok := state.assets[name] content, ok := data.assets[name]
if !ok { if !ok {
http.NotFound(w, r) http.NotFound(w, r)
return return
@@ -512,18 +966,24 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
_, _ = w.Write(content) _, _ = w.Write(content)
return return
} }
state.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL) data.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL)
http.NotFound(w, r) http.NotFound(w, r)
} }
} }
func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) { func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
// The request handler holds state.mu.
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": state.url + "/releases/10", "tag_name": "v1.2.3", "html_url": data.url + "/releases/10", "tag_name": data.tag,
"target_commitish": state.commit, "name": "Fixture v1.2.3", "target_commitish": data.commit, "name": "Fixture " + data.version,
"body": "# Fixture v1.2.3\n\nDelivery fixture.\n", "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

@@ -0,0 +1,111 @@
# ADR 0005: Select a Go module as the unit of release
## Status
Accepted.
## Date
2026-10-09
## Context
A Go repository can contain independently versioned modules. CommandKit plans
to release its core and optional integrations from one repository. Each module
needs its own validation, release note, semantic version, and Git tag.
ReleaseKit currently couples the semantic version to the Git tag and uses the
repository directory for Go validation and release-note discovery. Supporting
independent modules through consumer-owned publication code would duplicate
ReleaseKit's responsibilities.
[ADR 0002](0002-routine-releases.md) prioritizes routine releases with little
application-owned code or recurring decision-making.
[ADR 0003](0003-declarative-validation.md) establishes shared declarative
validation. Module selection should give those checks a coherent release scope.
## Decision
Each check or publication invocation selects one Go module within a Git
repository. Omitted module selection means the repository-root module. The
public Go API and CLI/profile interface express the same selection. Consumers
can use small per-module profiles through a shared launcher.
ReleaseKit distinguishes the repository directory, selected module directory,
semantic version, and complete Git tag. It derives the tag using Go's module
tag conventions and the selected module's committed declaration. Derivation
accounts for major-version directories. For example, a module in
`integrations/ckconfig` at `v0.2.0` uses the tag
`integrations/ckconfig/v0.2.0`. A module declared with a `/v2` suffix and stored
in `integrations/ckconfig/v2` uses `integrations/ckconfig/v2.0.0` for `v2.0.0`.
The semantic version identifies the module release. The complete tag identifies
its source in the shared repository and governs uniqueness, tag creation,
publication, source links, and recovery. Candidate evidence, publication
results, and CLI output identify the selected module and both version and tag,
alongside the existing commit and publication evidence. Failure outcomes retain
the resolved identity for recovery.
Release notes belong at `<module-directory>/docs/releases/<version>.md` and
identify the product and semantic version in their title. ReleaseKit reads the
selected note from the captured candidate. Root-module releases retain the
existing note layout and unprefixed tags. Modules can publish equal semantic
versions through their distinct notes and tags.
Mandatory and optional release validation share the selected module's scope.
Go tests, selected vet, and package compilation execute in that module with
the existing offline environment. File checks inspect the module's committed
contents and relevant release materials. Independently released nested modules
are excluded from their parent's validation scope. Selecting the root module
follows the same rule.
A check may inspect referenced material outside the selected module when needed
to validate an in-scope item. Resolving a Markdown link to shared repository
documentation does not add that destination's documents to the validation input
set. The checkout remains the boundary for checks of outside-checkout links.
Shared release materials follow established conventions and documented
consumer requirements.
Product-specific checks receive the selected module context and repository
context for deliberate composition checks. ReleaseKit applies module selection
consistently across its shared checks, avoiding separate scope settings for
each check.
Publication guards cover the shared repository: cleanliness, branch, candidate
commit, authoritative endpoint, and the complete selected tag. The standard
suite runs once for the selected candidate and module. Successful source-tag
publication remains the completion point, with existing failure and uncertain
publication outcomes preserved. Consumers prepare released sibling dependencies
and choose their publication order.
## Alternatives considered
- Consumer-owned module publication gives each application responsibility for
tag conventions, validation, and recovery, duplicating shared mechanics.
- Module-local Go execution with repository-wide optional validation lets
unrelated modules block a selected release and gives checks inconsistent
scopes.
- Independent scope settings for each check require consumers to coordinate
multiple declarations of the same release boundary.
- Coordinated multi-module publication adds release-set and dependency-ordering
responsibilities beyond the demonstrated need for individual releases.
## Consequences
Consumers describe the module and product being released while ReleaseKit owns
the common procedure. Existing single-module repositories retain their default
behavior. Root modules containing independently released nested modules gain
module-scoped validation; release notes and migration guidance must explain
that change.
The shared candidate and publication paths must carry module scope and separate
version and tag identity throughout validation, diagnostics, and recovery.
Verification must cover root defaults, nested-module failures, equal versions
across modules, major-version directories, validation boundaries, and exact-tag
publication outcomes.
GoDoc and consumer documentation will own exact API and scope contracts.
Configuration and CLI documentation will own profile fields, commands, and
output. Implementation planning will define interactions with artifact builds
and hosted delivery. ReleaseKit's maintainer release policy continues to govern
ReleaseKit's own releases; consumers document their adopted module conventions.

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

@@ -21,9 +21,10 @@ go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
``` ```
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the `VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the
version. The repository defaults to the current directory, and the profile version. The repository argument defaults to the current directory. ReleaseKit
defaults to `<repository>/releasekit.json`. A successful command prints the resolves its containing Git checkout root before selecting the module or profile;
captured local commit and version. It checks the committed release note and 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
local Git state, runs the standard offline Go test suite (with `-race` when local Git state, runs the standard offline Go test suite (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
@@ -31,17 +32,28 @@ 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
module directory; omission selects the root module. Validation and configured
product checks use that module selection. Additional check commands run with
the selected module as their working directory and receive
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
`RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
environment. These values are added to each child environment without changing
the ReleaseKit process environment.
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
mode with cgo disabled. This check produces no artifacts and does not execute mode with cgo disabled. This check produces no artifacts and does not execute
target binaries. Compilation failures use the `package-compile` identity and target binaries. Compilation failures use the `package-compile` identity and
show the selected target. When `validation.go_format` is true, `check` examines show the selected target. When `validation.go_format` is true, `check` examines
regular committed Go files with the Go formatter after tests, vet, and package regular committed Go files with the Go formatter after tests, vet, and package
compilation. It includes vendor and nested-module source, ignores the worktree compilation. It uses the selected module and shared-file inputs, including
vendored source, and ignores the worktree
and symlink blobs, and reports unformatted paths as `go-format` without and symlink blobs, and reports unformatted paths as `go-format` without
modifying files. When `validation.module_distribution.workspace_files` is true, modifying files. When `validation.module_distribution.workspace_files` is true,
`check` reports committed `go.work` and `go.work.sum` blobs, including nested `check` reports committed `go.work` and `go.work.sum` blobs in those inputs,
and symlink entries, as `workspace-files`. This inspection is independent of including symlink entries, as `workspace-files`. Automatic file inputs stop at
independent nested modules. This inspection is independent of
`GOWORK` and ignores uncommitted files. Any artifact build selected by the `GOWORK` and ignores uncommitted files. Any artifact build selected by the
separate `build` setting runs after shared validation and configured checks. separate `build` setting runs after shared validation and configured checks.
When `validation.markdown` is a non-null object, `check` checks committed local When `validation.markdown` is a non-null object, `check` checks committed local
@@ -63,7 +75,7 @@ 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] VERSION go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] VERSION
``` ```
`publish` reads the same product, remote, validation, and additional-check `publish` reads the same product, remote, validation, and additional-check
@@ -75,11 +87,12 @@ 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 tag object. It prints the confirmed version, and pushes only its exact full tag object. It prints the confirmed semantic
candidate commit, and tag object version, 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
@@ -95,9 +108,11 @@ go.work.sum paths as `workspace-files`. Formatting failures are reported as
`go-format` with affected paths and preserve parser or source-inspection causes. `go-format` with affected paths and preserve parser or source-inspection causes.
When `validation.module_distribution.local_replacements` is true, the command When `validation.module_distribution.local_replacements` is true, the command
parses committed `go.mod` declarations, including nested and vendor modules, parses committed `go.mod` declarations in the selected module after
after workspace-file inspection. Filesystem replacements use the workspace-file inspection. Vendored contents remain in scope, while
`local-replacements` identity and include the declaration path, source line, automatic inputs stop at independently released nested modules. Explicit shared
files join the file-check inputs without expanding Go scope. Filesystem replacements use
the `local-replacements` identity and include the declaration path, source line,
and target; versioned replacements are permitted. Committed module symlinks are and target; versioned replacements are permitted. Committed module symlinks are
resolved within the candidate, regardless of `GOWORK`. resolved within the candidate, regardless of `GOWORK`.
When `validation.file_size` is a non-null object, the command checks each When `validation.file_size` is a non-null object, the command checks each
@@ -112,6 +127,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
against the profile's `module_dir` before candidate work. Both paths are
normalized relative to the repository; the profile remains the source of module
selection. 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;
mismatches fail during preflight before Go validation or tag creation. Git URL mismatches fail during preflight before Go validation or tag creation. Git URL
@@ -135,8 +155,8 @@ go run ./cmd/releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSIO
targets with the requested version injected, checks the native `version` targets with the requested version injected, checks the native `version`
invocation, and writes binaries plus the private `.releasekit-build.json` invocation, and writes binaries plus the private `.releasekit-build.json`
receipt into `dist` by default. `--output` selects a different directory; receipt into `dist` by default. `--output` selects a different directory;
relative paths are resolved from the repository. Selected artifact filenames relative paths are resolved from the selected module directory. Selected
are regenerated while unrelated files are preserved. A complete nonempty build artifact filenames are regenerated while unrelated files are preserved. A complete nonempty build
writes a receipt only after compilation and smoke checking succeed. On partial writes a receipt only after compilation and smoke checking succeed. On partial
failure, standard error lists completed outputs and prior receipts in that failure, standard error lists completed outputs and prior receipts in that
output directory are invalidated; no new receipt is written. An output directory are invalidated; no new receipt is written. An
@@ -149,14 +169,17 @@ 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: 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 environment
variable or token 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
@@ -169,20 +192,34 @@ the tagged source into temporary storage, removes it when the operation ends,
and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is
supplied, that directory must contain the private `.releasekit-build.json` supplied, that directory must contain the private `.releasekit-build.json`
receipt and matching unchanged artifacts; this keeps the caller's original receipt and matching unchanged artifacts; this keeps the caller's original
bytes available for retries. Profiles without targets use page-only delivery bytes available for retries. Relative `--assets` paths use the selected module
directory, matching `build --output`; absolute paths retain their supplied base.
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
@@ -197,29 +234,45 @@ 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] --commit OID VERSION releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG
``` ```
`ci-deliver` fetches `VERSION` from the selected Git remote (default `origin`), `TAG` is the complete Git tag name, including any module path prefix. Its last
requires the tag's peeled commit to match the required full `--commit` object path component must be a stable semantic version; other commands continue to
ID, and checks out that commit detached. It then loads the profile from the take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from
prepared checkout, validates delivery settings and the configured token, and the selected Git remote (default `origin`), requires its peeled commit to match
downloads application dependencies only when the profile selects build targets. the required full `--commit` object ID, checks out that commit detached, then
Binary profiles are built and delivered through the same facade path as verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
`deliver`; source-only profiles skip dependency downloads and binary builds. checks read-only against the existing checkout and does not fetch or check out.
Preparation diagnostics mask userinfo in HTTP(S) remote URLs.
In either mode, it loads the profile from the verified source. `--expected-module`
optionally checks that the profile selects the module chosen by a launcher;
module selection itself remains profile-owned. The command compares the selected
module's derived release tag with the full event tag before forge access or
dependency preparation, then validates explicit forge selection and resolves
the configured 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.
`--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. This command explicitly from `--repo`, and absolute paths are used as-is. The default mode prepares and
prepares and changes the selected checkout. Ordinary `deliver` continues to changes the selected checkout; `--prepared` reuses a verified checkout.
operate on already prepared source without fetching, checking out, or Ordinary `deliver` continues to operate on already prepared source without
downloading dependencies. fetching, checking out, or downloading dependencies.
In Woodpecker, pass `CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the In Woodpecker, pass `CI_WORKSPACE`, the source commit resolved from
repository, expected commit, and version arguments. The CLI does not read `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the repository, expected commit, and full
tag arguments. The event ID may identify an annotated tag object; see the
[delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for resolution
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 builds the ReleaseKit version already

View File

@@ -1,20 +1,29 @@
# Configuration # Configuration
ReleaseKit reads a JSON profile from `<repository>/releasekit.json` by default. ReleaseKit reads a JSON profile from `<repository-root>/releasekit.json` by default.
The repository directory defaults to the current directory. A relative profile The repository argument defaults to the current directory; the CLI resolves its
path is resolved from that repository directory; an absolute path is used as-is. containing Git checkout root. A relative profile path is resolved from that root;
an absolute path is used as-is.
The current profile fields are: 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). |
| `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. |
`module_dir` names the selected module's physical location in the repository;
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
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
a module map.
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
@@ -28,6 +37,17 @@ target requires the package and binary name; each target is written as one
`GOOS/GOARCH` pair. An omitted or empty target list means no binary work. `GOOS/GOARCH` pair. An omitted or empty target list means no binary work.
The optional `validation` object selects shared checks implemented by ReleaseKit. The optional `validation` object selects shared checks implemented by ReleaseKit.
`validation.shared_files` is a committed file list resolved from the repository
root. Omission or `null` uses `COPYRIGHT`, `LICENSE`, and
`docs/oss/attribution.md` when present for enabled file checks; `[]` selects no
shared files. An explicit list replaces those defaults. Each explicit file must
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
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
scope. Automatic file inputs stop at independent nested-module boundaries;
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
@@ -40,7 +60,8 @@ 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.
`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 includes vendor and nested-module source, ignores used to build ReleaseKit. It uses the selected file inputs, including vendor and
explicit shared files, and ignores
symlink blobs and the worktree, and reports every selected path whose bytes symlink blobs and the worktree, and reports every selected path whose bytes
change under formatting. It never writes formatted bytes back. Omitted or false change under formatting. It never writes formatted bytes back. Omitted or false
disables the check. It runs after tests, selected full vet, and selected package disables the check. It runs after tests, selected full vet, and selected package
@@ -69,12 +90,14 @@ Anchors keep Unicode letters and numbers, underscores, and hyphens; spaces
become hyphens, and repeated headings receive numeric suffixes. become hyphens, and repeated headings receive numeric suffixes.
When `validation.module_distribution.workspace_files` is true, it reports When `validation.module_distribution.workspace_files` is true, it reports
committed blob entries whose basename is `go.work` or `go.work.sum`, including committed `go.work` and `go.work.sum` files in the selected module inputs,
nested paths and symlinks. It checks candidate distribution contents regardless including nested paths and symlinks. It checks the captured candidate regardless
of `GOWORK`; it does not select or change the workspace used by Go commands, of `GOWORK`; it does not select or change the workspace used by Go commands,
and it does not alter existing vendor behavior. Omitted or false disables it. and vendored contents remain in scope. Omitted or false disables it. When
When `validation.module_distribution.local_replacements` is true, it parses all `validation.module_distribution.local_replacements` is true, it parses the
committed `go.mod` declarations, including vendor and nested modules, and reports selected module's committed `go.mod` declarations. Vendored contents remain in
scope; an explicit shared-file selection can include an individual declaration
from another module. It reports
`replace` directives whose replacement has no version. These filesystem `replace` directives whose replacement has no version. These filesystem
replacements include relative and absolute paths; versioned module replacements replacements include relative and absolute paths; versioned module replacements
are permitted. Committed `go.mod` symlinks are resolved within the candidate, are permitted. Committed `go.mod` symlinks are resolved within the candidate,
@@ -109,8 +132,8 @@ check; `{}` enables it with a default of 1,000,000 bytes. A missing or null
`limit_bytes` selects that default, zero is a valid limit, and negative limits `limit_bytes` selects that default, zero is a valid limit, and negative limits
are invalid. are invalid.
`validation.file_size.exclusions` contains literal repository-relative file or `validation.file_size.exclusions` contains literal paths relative to the
directory paths. Directory exclusions include committed descendants, using path selected module. Directory exclusions include committed descendants, using path
boundaries (`assets` does not exclude `assets-old`). Ordinary relative path boundaries (`assets` does not exclude `assets-old`). Ordinary relative path
normalization applies; metacharacters are literal and unmatched paths have no normalization applies; metacharacters are literal and unmatched paths have no
effect. The check measures regular and symlink blobs, including small binaries; effect. The check measures regular and symlink blobs, including small binaries;
@@ -118,12 +141,52 @@ 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.
The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and
optional `token_env` and `token_file`. A delivery request must set `forge` to
`"gitea"`; omission, an empty or whitespace-only value, and unsupported values
are errors when `deliver` or `ci-deliver` is requested. The URL does not select
the forge. These semantic checks run only for delivery, so `check`, `publish`,
and `build` do not require a delivery object, selection, or credentials.
`token_env` names the environment variable containing the Gitea token and
defaults to `RELEASEKIT_GITEA_TOKEN`. A nonblank environment value takes
precedence. When it is unset or blank, `token_file` selects a plain
token-containing file; relative paths resolve from the Git repository root,
and absolute paths are used as supplied. The CLI trims leading and trailing
whitespace from file contents. An unreadable or blank file, or the absence of
both credential sources, returns status 2. Omission of `token_file` retains
environment-only loading.
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.
Credential loading runs only for `deliver` and `ci-deliver`. `check`, `publish`,
and `build` do not read the token file or require a 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
@@ -173,14 +236,21 @@ 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` uses the same profile after preparing the selected tag in the `ci-deliver` takes a full Git `TAG`; its final path component is the stable
checkout. It checks out the tag only after its peeled commit matches the semantic version and the complete value is checked against the profile's
provider-supplied commit ID, then loads the profile and validates delivery derived tag. By default it fetches the selected tag, confirms its peeled commit
settings and credentials. It runs `go mod download` only when the profile has matches the provider-supplied commit ID, checks it out detached, and verifies
selected build targets; source-only delivery does not need application the tag, HEAD, and clean worktree. With `--prepared`, it performs the same
dependencies. This preparation may access the network and may update checks against an existing checkout without fetching or checking out. It then
`go.sum`. The command takes CI values as arguments, so profile settings remain loads the profile from that source and validates delivery settings and
independent of Woodpecker environment variable names. See the credentials. An optional `--expected-module` checks a launcher's module
selection against the profile. It runs `go mod download` only when the profile
has selected build targets; source-only delivery does not need application
dependencies. Default preparation may access the network and may update
`go.sum`. For binary tagged delivery, prepare and commit that module's sums
before tagging so dependency preparation leaves the tagged checkout clean. The
command takes CI values as arguments, so profile settings remain independent of
Woodpecker environment variable names. See the
[CLI contract](cli.md) for the invocation and exit statuses. [CLI contract](cli.md) for the invocation and exit statuses.
This application dependency preparation is separate from bootstrapping the This application dependency preparation is separate from bootstrapping the

102
docs/consumers/adoption.md Normal file
View File

@@ -0,0 +1,102 @@
# Adopt ReleaseKit
Use a versioned Go tool dependency when ReleaseKit provides the repository's
release commands. This records the CLI in `go.mod` and keeps it available to
maintainers without adding imports to application or library code.
## CLI tool dependency
From the consumer module's root, select the ReleaseKit version to adopt:
```sh
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
go get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
go mod tidy
go tool releasekit version
```
Select a release that implements the API, profile, and workflow you are adopting.
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;
pre-feature versions through v0.3.0 use their corresponding historical interface.
Go records the executable package in
a `tool` directive and the module version in a `require` directive. The tool
declaration retains the dependency through `go mod tidy`. Commit the resulting
`go.mod` and `go.sum` changes. To upgrade, repeat the command with the chosen
version and review the module changes.
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
release. Tool dependencies share the consumer's module graph: their requirements
participate in dependency version selection and can raise the consumer module's
Go minimum. See the
[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
version. Follow the [CLI contract](../cli.md) for commands and exit statuses,
and the [configuration reference](../config.md) for the release profile.
## Go API consumers
Consumers importing the root `releasekit` API or
[`buildinfo`](runtime-version.md) use ordinary package dependencies. Add the
required imports and select the module version:
```sh
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
go get "go.maximumdirect.net/releasekit@${RELEASEKIT_TOOL_VERSION}"
go mod tidy
```
API consumers can also register the CLI with `go get -tool` as above. Both uses
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. The Go consumer minimum remains 1.26.0.
## CI adoption
The maintained [consumer tag-delivery workflow](delivery.md#woodpecker-tag-workflows)
supports both tool and ordinary package dependencies. It builds ReleaseKit from
the tagged consumer's module selection, 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.
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.
Keep its immutable module files and tag intact. See the
[delivery guide](delivery.md#woodpecker-tag-workflows) for tagged-source bootstrap
and the [example's source verification](../../examples/multi-module/README.md#local-source-verification)
for testing an unreleased checkout in a disposable consumer repository.

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,19 +36,26 @@ func build(ctx context.Context) error {
} }
``` ```
`Build` records the repository's current `HEAD`, injects the selected stable `Build` resolves `ModuleDir` and the selected module's working-tree declaration
version into `buildinfo.Version`, and returns the compiler identity, normalized once, records the repository's current `HEAD`, injects the selected stable
targets, artifact paths, filenames, and SHA-256 digests. Names follow version into `buildinfo.Version`, and returns repository/module identity, the
derived tag, compiler identity, normalized targets, artifact paths, filenames,
and SHA-256 digests. It does not require a release note, unused tag, clean
`main`, or publication. Names follow
`<binary>-<version>-<goos>-<goarch>`; Windows targets add `.exe`. A repeated `<binary>-<version>-<goos>-<goarch>`; Windows targets add `.exe`. A repeated
target pair is built once, at its first position. Local builds may use modified 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.
The default output directory is `<repository>/dist`; a relative `OutputDir` is Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
resolved from the repository. Selected artifact filenames are regenerated. Other files in the output module. The default output directory is `<module>/dist`; a relative `OutputDir`
directory are left in place. A failed later build or native version check returns the binaries already is resolved from the module, while an absolute path is used as supplied.
generated in `BuildResult.Artifacts`. Selected artifact filenames are regenerated. Other files in the output
directory are left in place. A failed later build or native version check
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
@@ -72,10 +79,14 @@ The [`build` command](../cli.md) reads the same build specification from the
profile and writes a private receipt alongside its artifacts. `check` and profile and writes a private receipt alongside its artifacts. `check` and
`publish` run selected builds after the standard suite and any additional `publish` run selected builds after the standard suite and any additional
checks using temporary output outside the worktree. Candidate checks do not checks using temporary output outside the worktree. Candidate checks do not
write a receipt or leave build files in the repository. write a receipt or leave build files in the repository. Disposable native
version-check output also remains outside the whole repository when `TMPDIR`
points inside the source tree.
For delivery from a tagged checkout, `deliver` builds selected tagged-source For delivery from a tagged checkout, `deliver` builds selected tagged-source
targets into temporary storage by default. Use `--assets DIR` to deliver a targets into temporary storage by default. Use `--assets DIR` to deliver a
separate build output; ReleaseKit requires its receipt and verifies the source, separate build output; ReleaseKit requires the current module-bound receipt and
build settings, and artifact hashes before the first Gitea write. See the checks its source identity and normalized build settings. It verifies artifact
bytes and sizes during delivery before the first Gitea write. Older receipts
must be regenerated with the updated `build` command. See the
[delivery consumer guide](delivery.md) for page-only delivery and retry states. [delivery consumer guide](delivery.md) for page-only delivery and retry states.

View File

@@ -21,14 +21,27 @@ if err != nil {
fmt.Println(result.Version, result.Commit) fmt.Println(result.Version, result.Commit)
``` ```
The repository must have a clean index and worktree on `main`, and the selected Set `ReleaseRequest.ModuleDir` to select a nested module using a
version must be stable `vMAJOR.MINOR.PATCH`. The committed repository-relative physical directory; omission or `.` selects the root
`docs/releases/<version>.md` note must have a first Markdown H1 containing the module. ReleaseKit reads that module's committed `go.mod` and returns its
product name and exact version as complete title elements. No local tag with physical `ModuleDir`, declared `ModulePath`, semantic `Version`, and complete
that version may already exist. `Tag` in the candidate and result. A physical `/v2` directory is removed from
the tag prefix only when the declared module path also ends in `/v2`. For
example, both `integrations/core/v2` and `integrations/core` can declare
`example.com/project/integrations/core/v2` and use the tag
`integrations/core/v2.1.0`. The release note lives under the physical module at
`<module>/docs/releases/<version>.md`.
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite with the The repository must have a clean index and worktree on `main`, and the selected
available compatible local Go toolchain. Set `Validation.Go.Race` to run that version must be stable `vMAJOR.MINOR.PATCH`. The module-local committed
`<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
the derived complete tag may already exist. Different modules may use the same
semantic version with distinct notes and tags.
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite from the
selected module directory with the available compatible local Go toolchain.
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
`go vet -mod=readonly ./...` after successful tests, with test-time vet disabled `go vet -mod=readonly ./...` after successful tests, with test-time vet disabled
for the suite. Set `Validation.Go.CompileTargets` to compile packages for each for the suite. Set `Validation.Go.CompileTargets` to compile packages for each
@@ -37,28 +50,32 @@ complete target pair after tests and vet. Package compilation uses
failures use the `package-compile` identity and include the target. The zero failures use the `package-compile` identity and include the target. The zero
values retain the ordinary native test behavior and select no compilation. values retain the ordinary native test behavior and select no compilation.
Set `Validation.GoFormat` to check committed regular Go files using the Go Set `Validation.GoFormat` to check committed regular Go files using the Go
formatter built into ReleaseKit. It includes vendor and nested-module source, formatter built into ReleaseKit. It uses the selected file inputs, including
vendor and explicit shared files, and
ignores symlink blobs and worktree changes, and reports unformatted paths as ignores symlink blobs and worktree changes, and reports unformatted paths as
`go-format` without rewriting files. Its zero value disables the check; it runs `go-format` without rewriting files. Its zero value disables the check; it runs
after tests, selected vet, and package compilation, before `AdditionalChecks`. after tests, selected vet, and package compilation, before `AdditionalChecks`.
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
`go.work` and `go.work.sum` blobs, including nested and symlink entries. It `go.work` and `go.work.sum` files in the selected module inputs, including
examines the captured candidate even when `GOWORK=off`, ignores uncommitted symlink entries. It examines the captured candidate even when
files, and does not change Go test workspace selection or vendor behavior. The `GOWORK=off`, ignores uncommitted files, and does not change Go test workspace
zero value disables the check; failures use `workspace-files`. selection; vendored contents remain in scope. The zero value disables the check;
failures use `workspace-files`.
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
committed `go.mod` declarations throughout the candidate, including nested and the selected module's committed `go.mod` declarations. Vendored contents remain
vendor modules. It reports filesystem `replace` directives with their source in scope; automatic inputs stop at independently released nested modules. An
path, line, and target as `local-replacements`; versioned replacements are explicit shared-file selection can include another module's declaration. It reports
filesystem `replace` directives with their source path, line, and target as
`local-replacements`; versioned replacements are
permitted. Committed module symlinks are resolved within the candidate. Parse permitted. Committed module symlinks are resolved within the candidate. Parse
and inspection errors retain their causes, and the rule applies even when and inspection errors retain their causes, and the rule applies even when
`GOWORK=off`. Its zero value disables the check. `GOWORK=off`. Its zero value disables the check.
Set `Validation.FileSize` to check each committed blob against a byte limit. Set `Validation.FileSize` to check each committed blob against a byte limit.
Nil disables the check; an empty object enables the default of 1,000,000 Nil disables the check; an empty object enables the default of 1,000,000
decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects
negative values. `Exclusions` contains literal repository-relative files or negative values. `Exclusions` contains literal files or directories relative to
directories; excluded directories include descendants. Symlink blobs are the selected module; excluded directories include descendants. Symlink blobs are
measured by link-text bytes, and gitlinks are omitted. The check applies to the measured by link-text bytes, and gitlinks are omitted. The check applies to the
captured candidate and reports one oversized file with its measurement as captured candidate and reports one oversized file with its measurement as
`file-size`; it does not measure historical or aggregate size. `file-size`; it does not measure historical or aggregate size.
@@ -76,7 +93,32 @@ 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.
ReleaseKit calls `AdditionalChecks` once after shared validation when supplied. The `Candidate` supplies both `RepositoryDir` and `ModuleDir`, plus the declared
`ModulePath`, semantic `Version`, and full `Tag`; use its module directory for
module-local product checks. ReleaseKit calls `AdditionalChecks` once after
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
ReleaseKit's optional file checks without enabling any checks. A nil slice
selects the optional defaults `COPYRIGHT`, `LICENSE`, and
`docs/oss/attribution.md`, when present; a non-nil empty slice selects none.
Explicit files replace those defaults, must exist even when file checks are
disabled, and may be in another module. Combined inputs are deduplicated by
repository-relative path.
Automatic file inputs stop at independent nested-module boundaries, including
fixture modules. Vendored files remain included. Shared selection affects file
inputs only; Go validation retains the selected module's scope. Reference reads
can inspect destinations elsewhere in the captured repository without adding
those destinations to the input set.
It does not download a different toolchain automatically. If race prerequisites It does not download a different toolchain automatically. If race prerequisites
are unavailable, the `go-test` check fails rather than being skipped; a selected are unavailable, the `go-test` check fails rather than being skipped; a selected
full-vet failure is reported as `go-vet`. The suite uses the Go host target, full-vet failure is reported as `go-vet`. The suite uses the Go host target,
@@ -86,6 +128,9 @@ settings are preserved, including values from Go's persistent environment
file. The check revalidates the branch, commit, and cleanliness after file. The check revalidates the branch, commit, and cleanliness after
validation. validation.
For checksum failures during dependency preparation, use the
[module checksum investigation guide](delivery.md#investigating-module-checksum-mismatches).
A successful check is evidence about the local candidate only. It does not A successful check is evidence about the local candidate only. It does not
check whether a remote branch or tag is available and does not create a tag. check whether a remote branch or tag is available and does not create a tag.
The [`check` command](../cli.md) reads the product and optional additional The [`check` command](../cli.md) reads the product and optional additional
@@ -94,10 +139,11 @@ commands from `releasekit.json`.
## Publishing the source tag ## Publishing the source tag
`releasekit.Publish` uses the same request and validation order: the standard `releasekit.Publish` uses the same request and validation order: the standard
suite runs first, followed by `AdditionalChecks` when supplied. It then performs suite runs first, followed by `AdditionalChecks` when supplied. It surrounds
authoritative remote checks, annotated-tag creation, and an exact tag push. The validation with authoritative remote guards before annotated-tag creation and
an exact tag push. The
selected remote must publish `main` at the captured commit and must not already selected remote must publish `main` at the captured commit and must not already
contain the selected version tag. A successful result includes the endpoint and contain the selected complete tag. A successful result includes the endpoint and
tag object ID. Publication states distinguish an unattempted push, a tag that tag object ID. Publication states distinguish an unattempted push, a tag that
was created locally but not pushed, a successful push, a guard conflict, and an was created locally but not pushed, a successful push, a guard conflict, and an
unresolved push error. See the [publication guide](publish.md) for the complete unresolved push error. See the [publication guide](publish.md) for the complete

View File

@@ -1,12 +1,21 @@
# 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
captured commit. `Version` remains the semantic version; the full tag includes
the selected module's repository-relative physical path when it is nested. The
profile or API request selects the physical module directory. The optional API
`ExpectedTag` checks that a CI event's literal tag agrees with the derived tag
before any build or hosted request.
## CI preparation ## CI preparation
Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified
@@ -20,7 +29,7 @@ or hosted content.
```go ```go
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{ err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
RepositoryDir: repositoryDir, RepositoryDir: repositoryDir,
Version: version, Tag: "integrations/example/v1.2.3",
ExpectedCommit: ciCommit, ExpectedCommit: ciCommit,
}) })
if err != nil { if err != nil {
@@ -28,16 +37,31 @@ if err != nil {
} }
``` ```
For binary profiles, call `PrepareBuildDependencies(ctx, repositoryDir)` after For binary profiles, call `PrepareBuildDependencies` with a
checkout preparation and before delivery. It runs `go mod download` with `DependencyPreparationRequest` selecting the repository and module after
workspace discovery disabled and the available compatible local Go toolchain. checkout preparation and before delivery. It runs `go mod download` in that
The operation may use the network and updates the Go module cache while module with workspace discovery disabled and the available compatible local Go
preserving the caller's proxy, private-module, credential, and cache settings. toolchain. Inside a Git checkout, `RepositoryDir` can name a subdirectory;
If checksums are missing, Go may update `go.sum`; see the `ModuleDir` is interpreted relative to the containing checkout root, and an
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
and commit the selected module's `go.sum` before tagging: delivery verifies the
tagged source remains clean after dependency preparation. See the
[Go Modules Reference](https://go.dev/ref/mod#go-mod-download). Cancellation [Go Modules Reference](https://go.dev/ref/mod#go-mod-download). Cancellation
and command errors are returned. Page-only profiles do not need dependency and command errors are returned. Page-only profiles do not need dependency
preparation. preparation.
Set `TaggedCheckoutRequest.VerifyOnly` when a bootstrap step already fetched and
detached the event tag. This mode checks the exact tag, expected commit, `HEAD`,
and clean worktree without fetching or changing the checkout. Both modes require
the full `Tag` and expected commit.
## Command line ## Command line
Add a Gitea destination to the profile: Add a Gitea destination to the profile:
@@ -46,6 +70,7 @@ 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",
@@ -61,14 +86,45 @@ git checkout --detach v1.2.3
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3 RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3
``` ```
The CLI reads the named token variable only for `deliver`; its default name is The CLI resolves the token for delivery using the configured environment
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before variable or token file. 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",
"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 can continue supplying the environment token. See the
[configuration reference](../config.md) for precedence, 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
`docs/releases/<version>.md`, and the hosted page is keyed by its complete tag.
With no build targets, delivery is page-only: no builder, version smoke check, With no build targets, delivery is page-only: no builder, version smoke check,
receipt, binary asset, or checksum manifest is involved. With selected targets, receipt, binary asset, or checksum manifest is involved. Committed module
directories and declaration links can be resolved from a sparse checkout;
page-only delivery needs the committed objects and note. Managed builds require
the selected source files to be materialized. With selected targets,
one `deliver` invocation builds the tagged source through the facade into one `deliver` invocation builds the tagged source through the facade into
temporary storage and delivers the result. To retain artifacts for a retry or temporary storage and delivers the result. To retain artifacts for a retry or
separate credentials between build and delivery, use two invocations: separate credentials between build and delivery, use two invocations:
@@ -80,10 +136,14 @@ RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" 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 the receipt's repository, commit, version, resolved `build`. ReleaseKit checks its schema, repository, commit, version, resolved
build settings, and file hashes before making a remote request; caller-owned module directory and path, full tag, normalized build settings, and artifact
files remain available for retries. Ordinary `deliver` does not download declarations. Old receipts must be regenerated with the updated `build`
application dependencies or change the checkout. command. Delivery verifies the artifact bytes and sizes after read-only
preflight and before any hosted write; caller-owned files remain available for
retries.
Ordinary `deliver` does not download application dependencies or change the
checkout.
The result reports `complete`, `partial`, `conflict`, `unknown`, or The result reports `complete`, `partial`, `conflict`, `unknown`, or
`not_attempted`, along with matching, uploaded, pending, conflicting, and `not_attempted`, along with matching, uploaded, pending, conflicting, and
@@ -94,6 +154,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
@@ -101,29 +165,84 @@ 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 that it identifies the selected repository, tagged commit, and ReleaseKit checks its repository, module directory, declared module path, full
version, that its source was verified clean and unchanged during compilation, tag, semantic version, tagged commit, normalized settings, and artifact evidence
and that the current files still match their recorded digests. The files remain against the selected committed module. Binary results must record verified
caller-owned, so callers can retain the original bytes for retries and are source. After cheap local and source checks, delivery performs read-only
responsible for cleanup. With neither artifact source, an empty managed target credential preflight, verifies the local artifacts in full, and then makes
set, or an empty prebuilt result, delivery is page-only. Do not set both `Build` hosted writes. The current files are checked against their recorded digests
and `Prebuilt` in one request. before those writes. Preflight confirms only the access evidence available from
the service, as described above. The files remain caller-owned, so callers can
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{
RepositoryDir: "/work/example", RepositoryDir: "/work/example",
ModuleDir: "integrations/example",
Product: "Example", Product: "Example",
Version: "v1.2.3", Version: "v1.2.3",
Destination: releasekit.GiteaDestination{ ExpectedTag: "integrations/example/v1.2.3", // optional CI event check
Destination: releasekit.DeliveryDestination{
Forge: releasekit.ForgeGitea,
BaseURL: "https://gitea.example", BaseURL: "https://gitea.example",
Owner: "example", Owner: "example",
Repository: "example", Repository: "example",
@@ -150,34 +269,58 @@ exit codes, and transport behavior.
Use the maintained [tag-delivery workflow](../../examples/woodpecker/tag-delivery.yml) Use the maintained [tag-delivery workflow](../../examples/woodpecker/tag-delivery.yml)
in the consumer repository's `.woodpecker/` directory. Set `GO_IMAGE` to an in the consumer repository's `.woodpecker/` directory. Set `GO_IMAGE` to an
image with Go 1.25 or newer, Git, and a local Go version compatible with the image with Git and a Go toolchain compatible with the consumer module and its
consumer module. It uses `GOTOOLCHAIN=local`; Go does not download a different selected ReleaseKit version. Choose the patch used for the consumer's release
toolchain. The tag's `go.mod` must select ReleaseKit as a module dependency. build and validation. The template uses `GOTOOLCHAIN=local`; Go does not download
a different toolchain. The tag's `go.mod` must select ReleaseKit as a module
dependency. For CLI-only consumers, use the versioned Go tool dependency
described in the [adoption guide](adoption.md). Ordinary package dependencies
also work with this template.
Select a tool release implementing this workflow's interface before adopting it;
the [adoption guide](adoption.md#ci-adoption) owns coordinated tool/workflow
upgrades. Retries of older tags use the workflow matching their recorded tool.
Configure the Woodpecker repository secret `releasekit_gitea_token`; the Configure the Woodpecker repository secret `releasekit_gitea_token`; the
template maps it to `RELEASEKIT_GITEA_TOKEN` for delivery. The repository needs template maps it to `RELEASEKIT_GITEA_TOKEN` for delivery. The repository needs
a `delivery` profile. Page-only and binary behavior both use this template; the a `delivery` profile. Page-only and binary behavior both use this template; the
profile's build target list selects whether application binaries are built and profile's build target list selects whether application binaries are built and
delivered. delivered.
Before running Go, the template fetches the explicit event tag, compares its Before running Go, the template fetches the explicit event tag and independently
peeled commit with the provider's full commit ID without regard to hex case, resolves both the tag and `CI_COMMIT_SHA` to source commits. The event ID may
checks out that commit detached, and confirms the source tree is clean. It then identify an annotated tag object or a commit. The template requires the resolved
copies the tagged `go.mod` and any `go.sum` to a temporary directory outside commits to match, checks out that commit detached, and confirms the source tree
the checkout. `go list -m` confirms that the module selects ReleaseKit; Go uses 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
ReleaseKit; Go uses
an alternate `-modfile` to prepare dependencies and build the selected an alternate `-modfile` to prepare dependencies and build the selected
`cmd/releasekit` package without changing the tagged module files. The template `cmd/releasekit` package without changing the tagged module files. The template
invokes that executable with `CI_WORKSPACE`, `CI_COMMIT_SHA`, and invokes that executable with `CI_WORKSPACE`, the resolved event commit, and
`CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable. `CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable.
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.
Afterward, `ci-deliver` loads the profile and downloads application dependencies After the workflow verifies and checks out the event tag, the resulting CLI uses
only when build targets are selected; it builds and delivers those targets with `ci-deliver --prepared` to repeat the tag, commit, HEAD, and cleanliness checks
the note page. Source-only profiles skip application dependency downloads and without another fetch or checkout. It loads the tagged profile and downloads
binary work. Dependency preparation for binaries may use the network and may application dependencies only when build targets are selected; it builds and
update an uncommitted checksum file in the checkout. A retry still uses the delivers those targets with the note page. Source-only profiles skip application
same immutable tag and that tag's module settings, even after the default branch dependency downloads and binary work. Dependency preparation for binaries may
selects a newer ReleaseKit version. use the network. Prepare and commit the selected module's `go.sum` before
tagging; an uncommitted change makes the later delivery source check fail. A
retry still uses the same immutable tag and that tag's module settings, even
after the default branch selects a newer ReleaseKit version.
The root-only [`tag-delivery.yml`](../../examples/woodpecker/tag-delivery.yml)
keeps the small default profile and root-module bootstrap. For consumers that
release several modules from one repository, copy the contents of the maintained
[multi-module example](../../examples/multi-module/) to the consumer repository
root and use its [`woodpecker.yml`](../../examples/multi-module/woodpecker.yml),
[`release-modules.tsv`](../../examples/multi-module/release-modules.tsv), and
shared selector. The event tag chooses one row from the tagged checkout; the
profile and physical module must agree, and ReleaseKit verifies the derived tag.
The example covers source-only integration pages and a binary core module.
If the application does not declare ReleaseKit as a module dependency, install If the application does not declare ReleaseKit as a module dependency, install
the executable separately and invoke the same `ci-deliver` command. For the executable separately and invoke the same `ci-deliver` command. For
@@ -192,11 +335,13 @@ 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. A separately installed executable can be installed with
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run `go install go.maximumdirect.net/releasekit/cmd/releasekit@PIN`, then run
with the same arguments: with the same arguments. With the event object available in the CI checkout,
resolve it to its source commit before invocation:
```sh ```sh
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$CI_COMMIT_SHA" "$CI_COMMIT_TAG" expected_commit=$(git -C "$CI_WORKSPACE" rev-parse --verify "${CI_COMMIT_SHA}^{commit}")
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$expected_commit" "$CI_COMMIT_TAG"
``` ```
The module-based workflow follows the ReleaseKit version selected by the tagged The module-based workflow follows the ReleaseKit version selected by the tagged
@@ -205,6 +350,12 @@ consumer module configuration when adopting a newer ReleaseKit version and
verify it with a tag fixture. The command and profile behavior are documented verify it with a tag fixture. The command and profile behavior are documented
in the [CLI contract](../cli.md) and [configuration reference](../config.md). in the [CLI contract](../cli.md) and [configuration reference](../config.md).
Update copied workflow YAML when adopting corrected examples. A dependency
upgrade alone leaves that copy unchanged. An older tagged workflow that passes
a raw annotated tag object ID still fails on retry. Recover delivery from the
original tagged source with the resolved event commit through the command above,
preserving the published tag and existing content.
Woodpecker runs delivery after the tag event, independently from the source Woodpecker runs delivery after the tag event, independently from the source
publication result. Read its workflow status as delivery status: a delivery publication result. Read its workflow status as delivery status: a delivery
failure does not undo source publication. A failed, partial, or uncertain run failure does not undo source publication. A failed, partial, or uncertain run
@@ -214,3 +365,50 @@ move the tag to make a retry pass. See
for runner-provided tag and commit variables and for runner-provided tag and commit variables and
[workflow syntax](https://woodpecker-ci.org/docs/usage/workflow-syntax) for tag [workflow syntax](https://woodpecker-ci.org/docs/usage/workflow-syntax) for tag
events, sequential steps, and the shared workspace. events, sequential steps, and the shared workspace.
## Investigating module checksum mismatches
During tool installation or dependency preparation, a checksum mismatch means
the bytes Go read differ from a recorded checksum. The message alone does not
identify whether those bytes came from the local cache or a remote source.
Keep checksum verification enabled and retain the error, selected version,
and relevant `go.sum` entries. Go's [module authentication reference](https://go.dev/ref/mod#authenticating)
describes these checks.
To isolate a public ReleaseKit download from application settings and the
existing module cache, run the following with a compatible local Go toolchain.
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.
```sh
(
checksum_dir=$(mktemp -d) || exit 1
printf 'Checksum investigation directory: %s\n' "$checksum_dir"
cd "$checksum_dir" || exit 1
GOENV=off GOFLAGS= GOWORK=off GOTOOLCHAIN=local \
GOPRIVATE= GONOPROXY= GONOSUMDB= \
GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \
GOMODCACHE="$checksum_dir/modules" \
go mod download -json go.maximumdirect.net/releasekit@v0.5.0
)
```
A successful isolated download establishes that this version verifies through
the selected proxy. Compare its `GoMod`, `GoModSum`, and `Sum` with the affected
cache and the application's recorded checksums. Locate the original cache with
`go env GOMODCACHE`; Go stores downloaded module metadata separately from the
extracted source. See the [module cache reference](https://go.dev/ref/mod#module-cache).
Once a stale cache entry is confirmed, preserve a copy, quarantine that entry
while no Go process is using it, and retry normal dependency preparation. For
a confirmed stale `.mod`, quarantine that file alone. Preserve application
checksums and published tags. Routine downloads can continue to use the normal
module cache.
If the isolated download also fails, investigate the selected proxy, tagged
source, and recorded checksums with the maintainer before changing local state.
Record any difference between proxy and direct fetching. A confirmed cache
problem can be repaired locally; changes to published source follow the
maintainer's immutable-release procedure.

View File

@@ -6,6 +6,7 @@ annotated source tag:
```go ```go
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{ result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
RepositoryDir: "/work/project", RepositoryDir: "/work/project",
ModuleDir: "integrations/example",
Product: "Example", Product: "Example",
Version: "v1.2.3", Version: "v1.2.3",
ExpectedPushURL: "ssh://git.example/owner/example.git", ExpectedPushURL: "ssh://git.example/owner/example.git",
@@ -13,15 +14,28 @@ result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
Go: releasekit.GoValidationSpec{Race: true, FullVet: true}, Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
}, },
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error { AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
return runProjectChecks(ctx, candidate.RepositoryDir) return runProjectChecks(ctx, candidate.ModuleDir)
}, },
}) })
if err != nil { if err != nil {
return err return err
} }
fmt.Println(result.Version, result.CandidateCommit, result.TagObject) fmt.Println(result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.TagObject)
``` ```
`ModuleDir` is a repository-relative physical module directory; omit it or use
`.` for a root-module release. ReleaseKit reads the selected module's committed
declaration and derives the complete Git tag from its declared module path and
physical location. `Version` remains the stable semantic version. The note is
`<module>/docs/releases/<version>.md`; an on-disk `/v2` directory is part of
the note path but is removed from the tag prefix only when the module path ends
in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared
`ModulePath`, complete `Tag`, and existing commit and tag-object evidence.
The optional `ValidationSpec.SharedFiles` selects additional committed files
for enabled file checks. Its nil and empty-slice behavior is described in the
[candidate check guide](check.md#local-candidate-check).
Publication captures a clean candidate on `main`, validates its committed Publication captures a clean candidate on `main`, validates its committed
release note, and checks the selected remote before running candidate checks. release note, and checks the selected remote before running candidate checks.
Set `ExpectedPushURL` to require the effective push destination to match an Set `ExpectedPushURL` to require the effective push destination to match an
@@ -49,22 +63,25 @@ does not execute target binaries. A failure is reported as `package-compile`
with the selected target and prevents tag creation. with the selected target and prevents tag creation.
Set `Validation.GoFormat` to check committed regular Go source using the Go Set `Validation.GoFormat` to check committed regular Go source using the Go
formatter built into ReleaseKit. It includes vendor and nested modules, ignores formatter built into ReleaseKit. It uses the selected file inputs, including
vendor and explicit shared files, and ignores
worktree changes and symlink blobs, and reports unformatted paths as worktree changes and symlink blobs, and reports unformatted paths as
`go-format` without changing files. The default is disabled. The check follows `go-format` without changing files. The default is disabled. The check follows
tests, selected vet, and package compilation, and a failure stops publication tests, selected vet, and package compilation, and a failure stops publication
before product checks or tag creation. before product checks or tag creation.
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
`go.work` and `go.work.sum` blobs, including nested paths and symlink entries. `go.work` and `go.work.sum` blobs in the selected inputs, including symlink entries.
The rule reads the captured candidate regardless of `GOWORK`; uncommitted files The rule reads the captured candidate regardless of `GOWORK`; uncommitted files
are ignored, and Go workspace selection and vendor behavior are unchanged. Its are ignored, and Go workspace selection and vendor behavior are unchanged. Its
zero value disables the check. Findings use `workspace-files` and stop zero value disables the check. Findings use `workspace-files` and stop
publication before product checks or tag creation. publication before product checks or tag creation.
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
committed `go.mod` declarations across the candidate, including nested and selected module's committed `go.mod` declarations. Vendored contents remain in
vendor modules. Filesystem `replace` directives are reported with their source scope; automatic inputs stop at independently released nested modules. Explicit
path, line, and target as `local-replacements`; versioned replacements are shared files can include another module's declaration. Filesystem
`replace` directives are reported with their source path, line, and target as
`local-replacements`; versioned replacements are
permitted. Committed module symlinks are resolved within the candidate, and permitted. Committed module symlinks are resolved within the candidate, and
parse or inspection errors retain their causes. This check is independent of parse or inspection errors retain their causes. This check is independent of
`GOWORK`; its zero value disables it, and a failure stops publication before `GOWORK`; its zero value disables it, and a failure stops publication before
@@ -72,9 +89,9 @@ product checks or tag creation.
Set `Validation.FileSize` to check each committed blob against a byte limit. Set `Validation.FileSize` to check each committed blob against a byte limit.
Nil disables the check; an empty object enables the default of 1,000,000 Nil disables the check; an empty object enables the default of 1,000,000
decimal bytes. `LimitBytes` uses strict greater-than, accepts zero, and rejects decimal bytes. `LimitBytes` uses strict greater-than, accepts zero, and rejects
negative values. `Exclusions` contains literal repository-relative files or negative values. `Exclusions` contains literal files or directories relative to
directories, including committed descendants of excluded directories. Symlink the selected module, including committed descendants of excluded directories.
blob size is its link text; gitlinks are omitted. This check measures only the Symlink blob size is its link text; gitlinks are omitted. This check measures only the
captured candidate and reports one oversized file with its measurement as captured candidate and reports one oversized file with its measurement as
`file-size`; it stops publication before product checks or tag creation. `file-size`; it stops publication before product checks or tag creation.
@@ -97,9 +114,12 @@ 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.

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

@@ -75,3 +75,17 @@ validation. The [maintainer release procedure](release.md) owns preparation,
publication, and recovery. Hosted note-page delivery is a separate prepared publication, and recovery. Hosted note-page delivery is a separate prepared
workflow and does not change the successful-tag-push completion point. ReleaseKit workflow and does not change the successful-tag-push completion point. ReleaseKit
does not declare binary deliverables. does not declare binary deliverables.
## Testing synthetic modules
Tests that serve synthetic module versions through local proxies should pass a
test-owned temporary `GOMODCACHE` to every Go subprocess that consumes those
versions. Scope fixture-specific proxy and checksum settings to those processes.
This applies the [testing policy's isolation requirements](policy/testing.md#test-execution-requirements)
to module downloads and keeps fixture metadata out of developer and CI caches.
Distinct fixture version numbers still occupy the real module's cache namespace.
Use temporary caches even when the selected versions have never been published.
Verify isolation at the shared fixture boundary; ordinary builds can continue
to use their prepared dependency cache. Consumer recovery guidance lives in the
[module checksum investigation guide](consumers/delivery.md#investigating-module-checksum-mismatches).

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 its stable 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,34 +14,71 @@ 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.
For version `vMAJOR.MINOR.PATCH`, the client first reads 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
module path, and physical repository-relative directory. For example, version
`v1.2.3` in `integrations/ckconfig` uses
`integrations/ckconfig/v1.2.3`; a root module uses `v1.2.3`. A `/v2` module
stored at `integrations/core/v2` uses `integrations/core/v2.1.0`; the same
declared module stored at `integrations/core` derives the same tag. ReleaseKit
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>/docs/releases/<version>.md`, including a physical `/v2` directory.
The default shared validation convention uses repository-root `COPYRIGHT`,
`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
source ref and the actual repository-relative file paths in those links.
Shared-file selection controls validation inputs; delivery preserves the
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. 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 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
@@ -49,12 +87,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

@@ -1,15 +1,51 @@
# Go command environments # Go command environments
`internal/gotool` resolves effective Go settings once for a validation or build `internal/gotool` resolves effective Go settings when an operation first needs
operation and applies the shared environment to its Go commands. It uses a Go command and applies the shared environment to its commands. Candidate
validation and its build callback share an operation-local owner while the
inherited environment and persistent Go settings file remain unchanged.
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.
## Command output ownership
`Tool.Run` executes a status-only command. It forwards combined stdout and
stderr to the optional writer while the child runs, retaining only the last
1,048,576 bytes for failure diagnostics. A truncation notice identifies omitted
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
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
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;
the component benchmark compares full and bounded capture for modest output,
one 8 MiB write, and 8 MiB in 32 KiB writes, forwarding to `io.Discard`.
The [output benchmark](../../internal/gotool/performance_test.go)
measures total allocated bytes per operation, excluding subprocess overhead and
diagnostic strings. These totals count all allocations, including superseded
buffers. The returned slice retains the final buffer holding the complete output.
Peak live memory depends on buffer growth, garbage collection, and other command
work and is not measured by allocation totals. Failed output also formats
diagnostics into the error, so the returned bytes and diagnostic string can
coexist. Disk-backed diagnostics could reduce large failure peaks, but add file
lifecycle and cleanup work and remain a follow-up option.
Dependency preparation uses a separate command environment so proxy, private
module, checksum, cache, and other effective settings remain available. Its
`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
The owner asks the installed `go` command for `GOHOSTOS` and `GOHOSTARCH`, then The owner asks the installed `go` command for `GOHOSTOS`, `GOHOSTARCH`, and the
queries effective operational settings with that host selected. Both queries `GOENV` settings-file path, then queries effective operational settings with
use `GOTOOLCHAIN=local` and controlled `GOFLAGS`. Discovery sets that host selected. Both queries use `GOTOOLCHAIN=local` and controlled
`GOFLAGS`. Discovery sets
`GOEXPERIMENT=none` and clears architecture feature variables so an invalid or `GOEXPERIMENT=none` and clears architecture feature variables so an invalid or
nonbaseline tuning value cannot prevent settings from being read. The nonbaseline tuning value cannot prevent settings from being read. The
experiment override is discovery-only. experiment override is discovery-only.
@@ -20,6 +56,13 @@ and native cgo/C-tool configuration into its settings. This captures values
supplied by either the process environment or the persistent Go environment supplied by either the process environment or the persistent Go environment
file. file.
The operation-local owner snapshots the inherited environment and selected
settings file. It reuses the resolved tool across validation and its following
build callback while those inputs match. Subsequent Go acquisition rediscovers
settings when a consumer callback changes either input. An unavailable snapshot
disables reuse while discovery follows the Go tool's accepted configuration.
Ownership is operation-local.
Configuration discovery parses JSON from stdout. Stderr is captured separately Configuration discovery parses JSON from stdout. Stderr is captured separately
and included in command-failure diagnostics, so a successful query can emit and included in command-failure diagnostics, so a successful query can emit
warnings while supplying valid configuration. warnings while supplying valid configuration.
@@ -41,9 +84,10 @@ baseline values. Effective `GOCACHE`, `GOCACHEPROG`, `GOMODCACHE`, `GOPATH`,
`GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain `GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain
available to child commands. available to child commands.
Candidate validation uses native mode for the offline `go test` suite and Candidate validation runs the offline `go test` suite and selected full
selected full `go vet` pass. Package-compilation checks use static mode for each `go vet` pass from the selected module directory using native mode.
selected target and direct Go's output to the operating system null device, so Package-compilation checks use static mode for each selected target and direct
they leave no binary artifact. Artifact builds also use static mode for Go's output to the operating system null device, so they leave no binary
selected-target compilation, then build the native version-check executable; artifact. Artifact builds also compile selected targets in static mode, then
that executable runs as a normal child process. build the native version-check executable, which runs as a normal child
process.

View File

@@ -24,8 +24,8 @@ 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.25.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal version `1.26.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:
@@ -37,18 +37,20 @@ reports these implemented packages:
| `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` | Candidate-build coordination, selected Go target compilation, version injection, native smoke check, 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` | Stable-version, note, repository-state, candidate capture, and post-validation checks. |
| `internal/delivery` | Tagged-source and release-note checks, managed builds in disposable storage outside the checkout, prebuilt artifact validation, manifest assembly, and hosted delivery coordination. | | `internal/delivery` | Read-only backend preflight, captured-commit 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/git` | Git command boundary, committed-tree and blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. | | `internal/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. |
| `internal/gitea` | Gitea API transport, hosted release pages, asset inspection, manifests, and uploads. | | `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/gotool` | Effective Go configuration discovery, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). | | `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/tempdir` | Disposable system temporary storage outside source worktrees. | | `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
| `internal/process` | Cancellable child-process execution 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/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, and recovery state. |
| `internal/runtimeinfo` | Private version lookup used by 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 stable-version rules and linker-symbol identity. |
The `buildinfo` facade depends only on its small runtime implementation. The The `buildinfo` facade depends only on its small runtime implementation. The
@@ -61,15 +63,29 @@ also recorded in [ADR 0001](../adr/0001-public-facade.md) and the
Candidate checking captures and validates one clean committed source revision Candidate checking captures and validates one clean committed source revision
in `internal/candidate`. Its validation bridge calls `internal/validation` for in `internal/candidate`. Its validation bridge calls `internal/validation` for
the default offline Go suite, then runs product-specific checks once. The the selected module's default offline Go suite, then runs product-specific
candidate package owns post-validation builds and local-state rechecks; checks once. Validation and its post-validation build callback share one local
publication owns endpoint guards, tag creation, push, and recovery around that Go settings owner. Each Go acquisition checks inherited and persistent inputs;
same candidate validation path. `internal/validation.CandidateTree` reads settings are rediscovered when subsequent Go work needs them. An unavailable
persistent-settings snapshot disables reuse. The candidate package owns builds and local-state
rechecks; publication owns endpoint guards, tag creation, push, and recovery
around that same candidate validation path. `internal/validation.CandidateTree` reads
committed blobs lazily and resolves local destinations from committed entries; committed blobs lazily and resolves local destinations from committed entries;
it does not consult neighboring files or traverse submodule checkouts. 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.
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
The following tests are representative evidence from the current offline suite, The following tests are representative evidence from the current offline suite,
@@ -78,17 +94,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`, `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` |
| 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` |
| Cross-builds, version smoke checks, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure` | | 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`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` | | Explicit destination selection, standalone and automatic preflight, and delivery ordering | `releasekit`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliveryForgeSelectionIsExplicit`, `TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout`, `TestPreflightDeliveryPreservesPublicFailureKindsAndCauses`, `TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing`, `TestDeliverUnavailablePreflightStopsBeforeManagedBuild`, `TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation`, `TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne` |
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` | | 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` |
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` | | Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout` | | Shared module identity and tag derivation | `internal/releaseidentity`, `internal/candidate`, `internal/build`, `internal/delivery` | `TestDeriveUsesModuleDeclarationAndPhysicalLayout`, `TestCommittedAndWorkingTreeDeclarationsUseTheirOwnSources`, `TestSelectedNestedModuleDoesNotRequireRootDeclaration`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages` |
| 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` |
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
check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise

View File

@@ -8,59 +8,101 @@ post-validation build callback and local-state recheck. `internal/publish`
adds its endpoint guards, tag creation, push, and recovery around that same adds its endpoint guards, tag creation, push, and recovery around that same
candidate path. candidate path.
The executor runs one offline Go suite, optionally with the race detector when The executor runs one offline Go suite from the captured module directory,
selected. When full vet is selected, it disables test-time vet for that suite optionally with the race detector when selected. When full vet is selected, it
and runs native `go vet -mod=readonly ./...` after the suite succeeds. It then disables test-time vet for that suite and runs native
runs `go build -mod=readonly -o <os.DevNull> ./...` in static mode for each `go vet -mod=readonly ./...` from the same directory after the suite succeeds.
selected package-compilation target, preserving target order and stopping on It then runs `go build -mod=readonly -o <os.DevNull> ./...` there in static mode
the first failure. This compiles source without producing an artifact or for each selected package-compilation target, preserving target order and
executing a target binary. Test, vet, and package-compilation failures retain stopping on the first failure. This compiles source without producing an
their `go-test`, `go-vet`, and `package-compile` identities, selected target artifact or executing a target binary. Test, vet, and package-compilation
where applicable, and underlying causes. Its failures retain their `go-test`, `go-vet`, and `package-compile` identities,
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 includes vendor and nested-module files, skips the Go-format check loads the candidate tree once, reads regular Go blobs from
symlink blobs, reports all unformatted paths, and stops with a contextual cause the captured commit, and compares them with go/format output. It uses the
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.
## Selected validation inputs
`CandidateTree` keeps the full committed repository lookup separate from the
ordered file input set. The selected module's committed inputs
exclude independently released nested modules, while vendored contents stay
in scope. Selection indexes boundary directories once and checks each entry's
ancestors, so unrelated boundaries are not scanned for each file. The
[scope benchmark](../../internal/validation/scope_performance_test.go) varies
boundary count while retaining 20,000 input files.
Explicit shared-file selections are normalized from repository-root
paths, added as individual files, and deduplicated with module inputs by path.
File-size exclusions are normalized from the selected module directory. Link
resolution can still inspect a committed destination outside the selected input
set without adding that destination's content to the checks. The public
selection, nil/empty behavior, and profile path bases belong to the
[configuration reference](../config.md) and the root facade's GoDoc.
The workspace-file check uses that same candidate inventory and reports blob The workspace-file check uses that same candidate inventory and reports blob
entries named go.work or go.work.sum, including nested paths and symlink blobs. entries named go.work or go.work.sum, including nested paths and symlink blobs.
It does not read workspace contents or depend on the workspace selected for Go It does not read workspace contents or depend on the workspace selected for Go
commands. commands.
The local-replacement check parses every committed go.mod blob with The local-replacement check parses selected go.mod blobs with
`golang.org/x/mod/modfile`, including nested modules and vendor declarations. `golang.org/x/mod/modfile`, including vendor and explicitly shared declarations.
It follows committed symlink declarations through the captured tree and fails It follows committed symlink declarations through the captured tree and fails
with an inspection cause when their selected contents are unavailable. A with an inspection cause when their selected contents are unavailable. A
replacement with no parsed version is reported with its go.mod path, line, replacement with no parsed version is reported with its go.mod path, line,
directive, and target; versioned replacements are allowed. It runs after the directive, and target; versioned replacements are allowed. It runs after the
workspace-file check using the same candidate inventory. workspace-file check using the same candidate inventory. Resolved module bodies
The optional file-size check uses each blob's captured Git size, including are parsed once per blob object ID; only owned filesystem-replacement targets
symlink link-text bytes, and skips entries without a blob size such as gitlinks. and line numbers remain cached. Each declaration path receives findings from
It applies normalized literal file/directory exclusions with path-boundary that summary in its own path context.
matching, then returns the first oversized path with `FileSizeMeasurement`. 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
exclusions with path-boundary matching, then requests local Git sizes for the
remaining selected blobs. Sizes include symlink link-text bytes; gitlinks are
omitted. The check returns the first oversized path with `FileSizeMeasurement`.
The optional Markdown check follows file-size inspection and uses the same The optional Markdown check follows file-size inspection and uses the same
candidate tree. It parses regular Markdown blobs, resolves local destinations, candidate tree. It parses regular Markdown blobs, resolves local destinations,
and checks supported anchors; outside-checkout and submodule observations are and checks supported anchors; outside-checkout and submodule observations are
written to the shared output writer. A nil writer keeps library use quiet. written to the shared output writer. A nil writer keeps library use quiet.
`CandidateTree` gets metadata and bytes from Git objects, reads blob bytes `CandidateTree` enumerates full repository path, type, mode, and object metadata
lazily, and resolves destinations without consulting the worktree or without requiring blob contents or sizes. Checks acquire sizes and bytes for
neighboring files. their selected inputs and required references. Unreferenced blobs in excluded
modules remain outside those reads. Destinations resolve without consulting
the worktree or neighboring files. Each tree owns one lazy Git blob reader;
direct tree users must close it when finished. The shared validation executor
closes its tree on every return before product checks or build callbacks run.
A metadata-only selection never starts the reader. Per-read contexts cancel
an in-flight blob exchange. The context supplied when creating the tree governs
the reader lifetime, including shutdown and child reaping.
Regular-file reads return independent caller-owned byte slices and are not
retained by the tree. Symlink targets are retained as immutable owned strings
by blob object ID; explicitly reading a symlink still returns independent
bytes. The Go-format check caches only whether each successfully inspected
object is formatted, then reports every unformatted path that refers to it.
The internal Markdown parser uses Goldmark to record inline, reference, and The internal Markdown parser uses Goldmark to record inline, reference, and
autolinks, images, titles, and their source use sites, and to build heading autolinks, images, titles, and their source use sites, and to build heading
anchors from visible AST text. It supports ATX and Setext headings, decodes anchors from visible AST text. It supports ATX and Setext headings, decodes
Markdown text through the parser, and assigns collision-free numeric suffixes Markdown text through the parser, and assigns collision-free numeric suffixes
to repeated anchors. Link locations use one-based line and byte-column values. to repeated anchors. Link locations use one-based line and byte-column values.
A per-path cache retains parsed records and anchors for candidate documents. The Markdown cache shares parsed records and anchors by regular blob object ID,
with a path lookup for callers. Retained destinations and titles own their
string storage, and parsed records contain content-relative locations only.
`checkMarkdownLinks` examines regular `.md` blobs from the captured tree. It `checkMarkdownLinks` examines regular `.md` blobs from the captured tree. It
skips schemed and protocol-relative URIs, strips query components, and decodes skips schemed and protocol-relative URIs, strips query components, and decodes
percent escapes once in local paths and fragments. It resolves destinations percent escapes once in local paths and fragments. It resolves destinations
through `CandidateTree.ResolveDestination`; decoded fragments are compared in through `CandidateTree.ResolveDestination` relative to the current source path;
lowercase against anchors from the resolved regular Markdown document. Missing decoded fragments are compared in lowercase against anchors from the resolved
regular Markdown document. Missing
paths, symlink cycles, and missing anchors produce `markdown-links` findings at paths, symlink cycles, and missing anchors produce `markdown-links` findings at
the source use site. Outside-checkout links produce out-of-scope observations by the source use site. Outside-checkout links produce out-of-scope observations by
default and findings when boundary enforcement is selected. Submodule-content default and findings when boundary enforcement is selected. Submodule-content
@@ -68,10 +110,13 @@ 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.
Public validation errors convert their diagnostic fields to the internal Public validation errors convert their diagnostic fields to the internal
failure model for shared formatting. Converted failures retain their original failure model for shared formatting. Converted failures retain their original
@@ -133,7 +178,8 @@ directories, missing paths, checkout boundaries, submodule paths, and symlink
cycles; the caller selects which observations fail validation or are reported cycles; the caller selects which observations fail validation or are reported
as out of scope. as out of scope.
Resolution walks committed components and symlink targets in order. Active The shared Git path resolver walks committed components and symlink targets
in order using the tree's indexed metadata and lazy symlink reader. Active
symlink expansion detects cycles, and traversal honors cancellation. Absolute symlink expansion detects cycles, and traversal honors cancellation. Absolute
destinations and symlink targets within the repository directory map back to destinations and symlink targets within the repository directory map back to
candidate-relative paths; existence still comes from committed entries. candidate-relative paths; existence still comes from committed entries.

View File

@@ -29,6 +29,9 @@ License and notices: [MIT](licenses/MIT.txt) |
Material: policy documents under `docs/policy/`, the root `AGENTS.md` orientation, Material: policy documents under `docs/policy/`, the root `AGENTS.md` orientation,
and the Policy Reading Guide in `docs/development.md`, adapted for this repository. and the Policy Reading Guide in `docs/development.md`, adapted for this repository.
The release policy incorporates revision `e833faddf120c789a9b45348edaf75720de16348`;
the remaining material incorporates revision
`d84a38ebab26f048cafbe59a2246700c35d29843`.
Copyright (C) 2026 Eric Rakestraw Copyright (C) 2026 Eric Rakestraw
@@ -38,4 +41,9 @@ License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) | [COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE). [LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE).
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843). Release-policy notices:
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/LICENSE).
[Release-policy source](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md) |
[Other policy material source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).

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

@@ -2,7 +2,7 @@
**Base Policy Version:** 1.8 **Base Policy Version:** 1.8
**Last Updated**: 2026-10-07 **Last Updated**: 2026-10-08
**Upstream Source:** [oss.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/oss.md) **Upstream Source:** [oss.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/oss.md)
@@ -55,7 +55,7 @@ provides texts to copy for applicable licenses and their companions.
ReleaseKit's selected grant is LGPL version 3 or later, recorded in ReleaseKit's selected grant is LGPL version 3 or later, recorded in
[COPYRIGHT](../../COPYRIGHT). It applies to the library and release [COPYRIGHT](../../COPYRIGHT). It applies to the library and release
executable. Adapted policy documents, agent orientation, and the policy reading executable. Adapted policy documents, agent orientation, and the policy reading
guide retain their CC-BY-SA-4.0 scope as identified there and in the guide retain their CC-BY-SA-4.0 scope as identified in the
[attribution document](../oss/attribution.md). [attribution document](../oss/attribution.md).
Unless the author specifies otherwise, use **GPL version 3 or later** Unless the author specifies otherwise, use **GPL version 3 or later**
@@ -90,9 +90,9 @@ fields; the standard reference collection remains unchanged. Keep `COPYRIGHT`,
grant. This convention introduces no blanket requirement for per-file headers; grant. This convention introduces no blanket requirement for per-file headers;
preserve notices or add them where the applicable terms require them. preserve notices or add them where the applicable terms require them.
Identify separately licensed documentation or assets in the project grant, with Identify separately licensed documentation or assets in the attribution
links to their attribution and license information. An application's default document, with links to their license information. The project grant uses the
code license does not override the terms of incorporated documentation. upstream template's third-party statement.
## Upstream Attribution House Format ## Upstream Attribution House Format

View File

@@ -1,10 +1,10 @@
# Release Policy # Release Policy
**Base Policy Version:** 1.4 **Base Policy Version:** 1.6
**Last Updated**: 2026-10-07 **Last Updated**: 2026-10-08
**Upstream Source:** [release.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/release.md) **Upstream Source:** [release.md](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md)
## Purpose ## Purpose
@@ -12,6 +12,9 @@ This policy defines a proportionate workflow for validating and publishing an
intended source revision under a fresh version. Releases should require little intended source revision under a fresh version. Releases should require little
routine intervention, avoid repeated work, and preserve published contents. routine intervention, avoid repeated work, and preserve published contents.
Adopt stronger verification or reproducibility requirements through an explicit
project-specific decision justified by the intended audience and support needs.
The repository-specific commands belong in `docs/release.md`. Historical release The repository-specific commands belong in `docs/release.md`. Historical release
summaries belong in `docs/releases/`. The procedure must agree with the adopted summaries belong in `docs/releases/`. The procedure must agree with the adopted
policy and link to it rather than introduce additional release requirements. policy and link to it rather than introduce additional release requirements.
@@ -69,7 +72,8 @@ requires a deliberate update to the policy and procedure where needed.
For releases at or after `v1.0.0`: For releases at or after `v1.0.0`:
- a major release may make intentional incompatible changes; - a major release may make intentional incompatible changes;
- a minor release may add backward-compatible behavior; and - a minor release may add backward-compatible behavior or raise the Go consumer
minimum as described below; and
- a patch release may make backward-compatible fixes. - a patch release may make backward-compatible fixes.
Before `v1.0.0`, a minor release may change a documented public, operational, Before `v1.0.0`, a minor release may change a documented public, operational,
@@ -81,6 +85,43 @@ Additional compatibility promises and deliberate exceptions belong in the
adopted policy or canonical contract documentation. Release notes explain adopted policy or canonical contract documentation. Release notes explain
changes; they do not redefine current compatibility contracts. changes; they do not redefine current compatibility contracts.
## Consumer Minimum And Release Toolchain
ReleaseKit provides reasonable support for routine build and release needs,
following [ADR 0002](../adr/0002-routine-releases.md). Distinguish the minimum Go
toolchain supported for consumers from the toolchain maintainers use to build
and validate a release. The consumer minimum belongs in [go.mod](../../go.mod);
the [maintainer runbook](../release.md) defines the selected release toolchain
and its setup commands.
Select the Go series during release preparation. When advancing the consumer
minimum, use the latest locally available stable series and record its initial
stable version in `go.mod`, such as `go 1.26.0`. Use a higher patch minimum when
a dependency requirement or identified correctness fix requires it, and document
the reason.
Build the maintainer release executable and validate the candidate with the
same latest locally available patch of the selected series. Keep that toolchain
active throughout preparation, tool bootstrap, and validation, using local
toolchain selection. CI jobs performing release builds and validation use the
selected toolchain; maintained CI images follow that choice. A newer validation
patch version alone leaves the consumer minimum unchanged.
For release-policy purposes, successful build and release validation on that
patch are sufficient to presume support across the selected Go series, subject
to the declared consumer minimum and concrete evidence of incompatibility.
This relies on Go's [release policy](https://go.dev/doc/devel/release#policy) and
[compatibility commitments](https://go.dev/doc/go1compat). Investigate specific
compatibility concerns as they arise. Routine releases require no patch-version
matrix. Record the actual validation toolchain in the release evidence.
A minor release may raise the Go consumer minimum, including from one Go series
to the next, both before and after `v1.0.0`. This is an explicit exception to the
backward-compatibility requirement for minor releases. Patch releases preserve
the consumer minimum. Explain an increase's impact and required consumer action
in the release note. Other incompatible changes remain subject to the versioning
rules above.
## Release Documentation And Preparation ## Release Documentation And Preparation
Every new release must include `docs/releases/<version>.md` in the tagged Every new release must include `docs/releases/<version>.md` in the tagged
@@ -132,8 +173,8 @@ checks when their distinct protection justifies their cost. A one-time migration
check must not silently become a permanent release requirement. check must not silently become a permanent release requirement.
Release tests must not require real credentials, mutable application services, Release tests must not require real credentials, mutable application services,
paid APIs, or live service probes. The procedure may describe dependency paid APIs, live service probes, or inference calls. The procedure may describe
preparation separately from offline validation. dependency preparation separately from offline validation.
Avoid duplicate validation across release phases. Successful checks for the Avoid duplicate validation across release phases. Successful checks for the
same final candidate need not be repeated solely to satisfy another phase; same final candidate need not be repeated solely to satisfy another phase;
@@ -200,7 +241,8 @@ release without replacing its contents or reusing its version.
Create and maintain `docs/release.md` with the first working publication command Create and maintain `docs/release.md` with the first working publication command
as a short, executable maintainer runbook. It must identify: as a short, executable maintainer runbook. It must identify:
1. prerequisites, primary branch, and authoritative remote; 1. prerequisites, selected release toolchain, primary branch, and authoritative
remote;
2. version and release-note preparation; 2. version and release-note preparation;
3. one publication command with its selected local checks and automated guards; 3. one publication command with its selected local checks and automated guards;
4. declared deliverables, required build targets, and automation responsibilities; 4. declared deliverables, required build targets, and automation responsibilities;

View File

@@ -1,27 +1,63 @@
# 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.
## Prepare a candidate ## Prepare a candidate
Use a local Go 1.25 toolchain and a clean clone. Start on `main`, choose an For local hosted-page delivery, save a Gitea personal access token in
unused stable `vMAJOR.MINOR.PATCH` version, and add `.releasekit/gitea-token` with owner-only file permissions. The file contains
only the token. ReleaseKit's profile selects this file as a fallback to
`RELEASEKIT_GITEA_TOKEN`; `.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.26.10. Make that
local installation the active `go` command for preparation, building the release
executable, and candidate validation:
```sh
export GOTOOLCHAIN=local
go version
```
Record the reported version with the validation results. The
[Go support policy](policy/release.md#consumer-minimum-and-release-toolchain) owns
series selection, consumer minima, patch exceptions, and validation scope.
The maintained [source-delivery image](../examples/woodpecker/releasekit-source-delivery.yml)
and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the
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).
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).
When increasing it, update `go.mod` to the first stable version of the selected
series, or to a higher patch when a dependency or specific fix requires one.
Make module changes before committing the candidate. Minimum increases must fit the
[compatibility policy](policy/release.md#versioning-and-compatibility); before
v1.0.0, an increase belongs in a minor release.
Choose an unused stable `vMAJOR.MINOR.PATCH` version, and add
`docs/releases/<version>.md` with a first heading containing `ReleaseKit` and `docs/releases/<version>.md` with a first heading containing `ReleaseKit` and
the exact version. Summarize the change and any compatibility or upgrade impact. 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
@@ -72,6 +108,22 @@ 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.
## Deliver the hosted release page
After source publication succeeds, deliver the hosted page locally when
Woodpecker automation is inactive. From the same repository root, keep the
worktree clean and `HEAD` at the published tag's commit. Reuse the executable
built by the publication command:
```sh
.releasekit/bin/releasekit deliver vX.Y.Z
```
The command uses the configured Gitea destination and token source to deliver
the complete checked-in release note. Report its result separately from the
completed source release. For failed or uncertain delivery, follow the recovery
instructions below using the same immutable version.
## Resolve failures ## Resolve failures
A failed push triggers a URL-resolution check against the captured endpoint, A failed push triggers a URL-resolution check against the captured endpoint,
@@ -107,6 +159,9 @@ with `git tag -d vX.Y.Z` before correcting the candidate or retrying. Do not
move, overwrite, or delete a tag that exists remotely. If a different object move, overwrite, or delete a tag that exists remotely. If a different object
uses the version, choose a new version after resolving the conflict. uses the version, choose a new version after resolving the conflict.
If local tag inspection fails after creation, the reported ref may remain even
when no tag object ID was obtained. Inspect that ref before recovery.
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 the authoritative-state check above before removal;
@@ -124,7 +179,15 @@ git checkout --detach "vX.Y.Z"
GOTOOLCHAIN=local go mod download GOTOOLCHAIN=local go mod download
mkdir -p .releasekit/bin mkdir -p .releasekit/bin
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z" .releasekit/bin/releasekit deliver "vX.Y.Z"
```
For an older tag whose CLI predates `token_file`, supply the token through its
environment variable when retrying that tagged tool:
```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

117
docs/releases/v0.3.0.md Normal file
View File

@@ -0,0 +1,117 @@
# ReleaseKit v0.3.0
## Summary
ReleaseKit reduces repeated Git processes, validation memory retention, artifact
hashing, output copying, and runtime metadata parsing. It also improves
cancellation during validation shutdown and documents module-selected CLI
adoption and checksum recovery.
## Changes
- Committed-file checks share one lazy Git batch reader per validation operation.
Metadata-only checks start no content reader. Cancellation remains active
through reader shutdown, and cleanup reaps the child before validation returns.
- Validation releases regular-file source bytes after inspection and reuses
compact or parsed results by blob identity for Go formatting, module
replacements, Markdown documents, and symlink targets. Findings retain each
source path's locations and destination context.
- Managed and prebuilt delivery use one local asset verification pass before
hosted requests, removing the adjacent declaration-time hashing pass. Changed
assets still fail verification; exact remote comparisons, additive retries,
and partial-delivery reporting retain their behavior.
- Go commands transfer completed output buffers without an additional full
copy. Status-only successes release their captures, while failures retain
complete diagnostics and underlying causes. Capture remains in memory;
allocation costs depend on output size and write chunking.
- The runtime version accessor caches its build-metadata fallback safely across
calls. Linker-injected versions retain precedence, and the development fallback
remains unchanged.
- Shutdown errors are attributed to the last validation check that actually read
content. Selecting a later check with no applicable files preserves that
attribution, and an earlier check failure remains the primary error.
- CLI-only consumers have documented adoption through versioned Go tool
dependencies. The Woodpecker template supports both tool dependencies and
ordinary package dependencies selected by the tagged consumer module.
- Synthetic-module workflow tests use isolated module caches. New checksum
investigation guidance explains how to distinguish stale local metadata from
a download failure while preserving checksum verification and published tags.
Performance gains depend on the consumer's workload. The changes preserve
complete in-memory diagnostics and existing validation selections.
## Compatibility
The declared minimum Go version increases from 1.25.0 to 1.26.0. Consumers
require Go 1.26.0 or newer; dependency versions are unchanged from v0.2.0.
ReleaseKit's maintainer build toolchain and maintained Woodpecker template images
use Go 1.26.8; consumers select a local toolchain compatible with their module
and the selected ReleaseKit version.
The root orchestration facade, separate lightweight `buildinfo` facade, public
signatures, CLI commands, and profile schema are unchanged. Existing v0.2.0
callers and profiles require no source or configuration migration.
Validation cleanup may now return the caller's cancellation cause where shutdown
previously remained blocked. Cleanup failures identify the check that used the
reader. Inspect structured validation errors with `errors.As` and underlying
causes with `errors.Is`.
Source publication and hosted delivery retain their separate completion states.
ReleaseKit's deliverables remain the source tag and hosted Gitea note page.
## Upgrade guidance
1. Use Go 1.26.0 or newer for local tooling and CI before selecting v0.3.0.
Updating ReleaseKit in a shared module graph can raise the consumer's declared
Go minimum. Select the dependency form appropriate to the consumer.
Go API consumers:
```sh
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.3.0
go mod tidy
```
Consumers using ReleaseKit for repository release commands can register or
upgrade the CLI as a Go tool dependency:
```sh
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.3.0
go mod tidy
go tool releasekit version
```
Review and commit the resulting module changes. API and tool dependencies
share the consumer's module graph and selected ReleaseKit version.
A separately installed executable can be updated with:
```sh
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.3.0
```
2. Retain existing validation and delivery selections. The performance changes
apply automatically. Prepare dependencies before offline checks or builds,
and run the consumer's ordinary tests after upgrading.
3. For module-selected Woodpecker delivery, commit the dependency upgrade before
tagging the consumer. Choose a compatible local Go image; delivery and retries
continue to use the triggering tag's module selection. CLI-only consumers can
use the tool declaration to retain ReleaseKit through `go mod tidy`.
4. If dependency preparation reports a checksum mismatch, follow the
[checksum investigation guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/delivery.md#investigating-module-checksum-mismatches).
Repair a confirmed stale cache entry while retaining checksum verification
and the application's recorded checksums.
See the
[adoption guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/adoption.md),
[candidate check guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/check.md),
[delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/delivery.md),
and [runtime version guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/runtime-version.md)
for supported behavior and usage.
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/oss/attribution.md)

141
docs/releases/v0.4.0.md Normal file
View File

@@ -0,0 +1,141 @@
# ReleaseKit v0.4.0
## Summary
ReleaseKit supports releasing individual Go modules within a repository, with
module-specific validation, builds, tags, and Gitea release pages. Root-module
consumers retain the simple default configuration. This release also improves
path resolution, offline source inspection, failure diagnostics, and efficiency.
## Changes
- `Check`, `Publish`, `Build`, and `Deliver` accept `ModuleDir` and expose the
resolved module directory, declared module path, and complete tag in their
results. Each operation resolves its module identity once. Product commands
receive repository and module context, and candidate callbacks receive module
identity.
- Release tags follow the selected module's physical location and declared major
version. For example, `v2.1.0` for
`example.com/project/integrations/core/v2` uses
`integrations/core/v2.1.0` whether its physical directory is
`integrations/core` or `integrations/core/v2`. Its note remains at that physical
module's `docs/releases/v2.1.0.md`. Binary version output and asset names retain
the semantic version; Git publication and Gitea delivery use the complete tag.
- Profiles add `module_dir`. Go checks and configured product commands run from
the selected module. Automatic committed-file inputs stop at independent
nested modules; vendored files remain included. Nested fixtures remain
available to the parent module's product tests.
- `ValidationSpec.SharedFiles` and profile `validation.shared_files` select
repository-relative literal files for optional file checks. Omission selects
the available root copyright, license, and attribution defaults; an explicit
list replaces them, and an explicit empty list selects none. Explicit files
must exist even with checks disabled. Selection preserves the enabled checks
and Go test scope; reference inspection can read destinations elsewhere in
the captured repository.
- Module releases receive separate Gitea pages, including source-only modules.
Relative build output and prebuilt delivery paths share the selected module
as their base. Prebuilt receipts bind artifacts to module identity, semantic
version, complete tag, source commit, and normalized build settings.
- `ci-deliver` accepts the complete event tag. Prepared mode verifies a checkout
already detached at that tag, and expected-module and expected-tag checks bind
delivery to the CI selection before building or contacting Gitea. The
multi-module example shares a module map between its local launcher and
Woodpecker workflow. The workflow verifies the tag before reading the mapping,
profile, or tool selection, preserving the tagged configuration for retries.
## Reliability and efficiency
- Operations resolve the containing Git checkout root when invoked from a child
directory. Working-tree and committed module paths resolve symlinks consistently,
including paths containing `..`. Committed identity comes from Git objects;
page-only delivery can use committed module metadata absent from the worktree.
Valid local main-module paths are accepted.
- Build failures preserve available identity and settings alongside completed
artifacts. Invalid versions retain the public error identity and the CLI's
usage-error status. Prebuilt delivery accepts equivalent checkout paths while
retaining source and module verification.
- Committed release-note and validation reads remain offline in partial clones.
Validation reads blob contents and sizes as needed for selected inputs and
referenced destinations. Unavailable blobs outside that inspection scope do
not prevent applicable checks.
- Module-file selection uses ancestor boundary lookups. Operations reuse Go
environment discovery while its inputs remain suitable for reuse and acquire
Go settings only when Go work needs them. Delivery reuses its local asset
verification when uploading missing assets, removing a repeated hashing pass.
These improvements depend on the repository and workload. Artifact verification,
exact remote comparisons, additive retries, and partial-delivery reporting retain
their behavior.
## Compatibility
This pre-1.0 minor release introduces a clean API and receipt cutover:
- `TaggedCheckoutRequest.Version` becomes `Tag`, containing the complete Git
tag. `VerifyOnly` adds verification of an already prepared checkout.
- `PrepareBuildDependencies` now accepts `DependencyPreparationRequest` with
repository and module directories.
- The private build receipt requires schema version 1 and module identity.
Existing receipts must be regenerated before prebuilt delivery.
- Root-module committed-file checks exclude independent nested modules. Select
those modules separately when their files need release validation.
The Go minimum remains 1.26.0. Root-module releases retain their existing note
path, unprefixed tags, profile defaults, and ordinary workflow without a module
map. The root orchestration facade and separate lightweight `buildinfo` facade
retain their roles; runtime version access requires no migration.
Source-tag publication remains the source-release completion point. Hosted page
and asset delivery remains asynchronous and can be retried from the same
immutable tag. ReleaseKit's deliverables remain its source tag and hosted note
page.
## Upgrade guidance
1. Select v0.4.0 in each consumer module that uses ReleaseKit. For API consumers:
```sh
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.4.0
go mod tidy
```
For consumers using the CLI as a Go tool dependency:
```sh
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.4.0
go mod tidy
```
Review and commit the resulting module and checksum changes together with
caller, profile, and workflow updates. Keep historical tag retries paired
with the tool and workflow recorded at that tag.
2. Update preparation API calls for `Tag` and `DependencyPreparationRequest`.
For nested modules, set `ModuleDir` or profile `module_dir` to the physical
module location, with its own `go.mod` declaration. Keep ordinary `Version`
arguments as semantic versions. Use result `ModuleDir`, `ModulePath`, and
`Tag` where module identity is needed. Product commands can distinguish their
contexts through `RELEASEKIT_REPOSITORY_DIR` and `RELEASEKIT_MODULE_DIR`.
3. Update `ci-deliver` invocations to pass the full event tag and required
`--commit OID`. Use `--prepared` after bootstrap verification and
`--expected-module DIR` for mapped launchers. Prepare and commit each binary
module's checksums before tagging so dependency preparation leaves tagged
source clean. Root-only consumers can retain the ordinary tag workflow.
4. Rebuild existing prebuilt outputs with the v0.4.0 `build` command before
`deliver --assets DIR`. Relative output and asset paths both resolve from the
selected module. Review optional shared-file selections and nested-module
validation coverage, then run the consumer's ordinary checks.
See the
[adoption guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/adoption.md),
[configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/config.md),
[CLI contract](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/cli.md),
[delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/delivery.md),
and [multi-module example](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/examples/multi-module/README.md)
for supported usage.
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/oss/attribution.md)

29
docs/releases/v0.4.1.md Normal file
View File

@@ -0,0 +1,29 @@
# ReleaseKit v0.4.1
## Summary
This patch synchronizes shared state in the delivery and Gitea HTTP test
fixtures. It makes the test suite reliable under concurrent request handling
and the Go race detector. Production code and public behavior are unchanged.
## Changes
- Protect delivery fixture state with mutexes and independent snapshots; use
atomic observations for independent Gitea fixture counters and flags.
- Keep fatal test assertions in the test goroutine and ensure release test
servers close with their owning tests.
- Preserve existing delivery, conflict, retry, and source-tag assertions while
exercising the synchronized fixtures.
## Compatibility
There are no API, configuration, or runtime behavior changes, and no consumer
migration is required. The Go minimum remains 1.26.0. The published v0.4.0 tag
and its contents are unchanged.
Consumers may upgrade to v0.4.1 with their existing API, profile, and workflow
configuration.
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.1/docs/oss/attribution.md)

36
docs/releases/v0.4.2.md Normal file
View File

@@ -0,0 +1,36 @@
# ReleaseKit v0.4.2
## Summary
This patch corrects Woodpecker delivery bootstrap for events whose
`CI_COMMIT_SHA` identifies an annotated tag object. The maintained workflows
resolve the event object to its source commit before verification and delivery.
## Changes
- Correct module-selected, multi-module, and ReleaseKit source delivery
workflows to resolve event and tag commits independently and pass the
resolved event commit to `ci-deliver`.
- Report both commit identities when an event and its selected tag disagree.
- Extend executable-workflow regression coverage for annotated tag-object
events, annotated and lightweight commit events, resolved delivery arguments,
and rejection of unrelated commits.
## Compatibility and upgrade guidance
Public APIs, CLI contracts, configuration formats, and the Go 1.26.0 consumer
minimum retain their v0.4 definitions. `ci-deliver --commit` continues to accept
the expected source commit ID.
Update copied workflow YAML from the maintained examples when adopting this
patch. Upgrading the ReleaseKit dependency alone leaves copied workflows
unchanged. The [delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/docs/consumers/delivery.md#woodpecker-tag-workflows)
describes event resolution, workflow adoption, and delivery recovery.
Existing published tags and contents remain unchanged. Recover a failed older
workflow from its original tagged source using the resolved event commit through
the documented delivery command, preserving existing hosted content.
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.2/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)

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.

View File

@@ -0,0 +1,133 @@
# Multi-module release example
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
from the selected module declaration and physical location; the table only
selects the corresponding profile and checkout directory.
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 launcher from that checkout.
The sample modules declare Go 1.26.0, matching the current ReleaseKit consumer
minimum.
## Select the release tool
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
ReleaseKit version at or after the v0.5.0 vanity-path migration, then register
that tool in each consumer module before running the launcher or workflow:
```sh
: "${RELEASEKIT_TOOL_VERSION:?Select a ReleaseKit release with module-release support}"
for module_dir in . integrations/ckconfig integrations/core/v2; do
go -C "$module_dir" get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
go -C "$module_dir" mod tidy
done
```
Review and commit the generated tool, dependency, and checksum declarations.
The [adoption guide](../../docs/consumers/adoption.md) owns tool registration and
coordinated tool/workflow upgrades. The
[v0.4.0 release note](../../docs/releases/v0.4.0.md) describes module-release
support and migration from earlier versions.
## Module mapping and publication
`release-modules.tsv` is literal tab-separated text with four columns:
1. Local selector.
2. Shell pattern matched against a complete event tag.
3. Repository-relative physical module directory (`.` means the root module).
4. Repository-relative profile path.
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`, and
`integrations/core/v2.*`. The helper passes pattern text to the shell's `case`
matcher without `eval`. A tag must match exactly one row; missing and ambiguous
matches are configuration errors. Module and profile paths may contain spaces.
The `core-v2` row places the Go module physically under `integrations/core/v2`
and declares a `/v2` module path. ReleaseKit derives the versioned tag under
`integrations/core`, while the table retains the full physical path.
Before running candidate checks offline, prepare each module's dependencies in
its own directory:
```sh
go -C . mod download
go -C integrations/ckconfig mod download
go -C integrations/core/v2 mod download
```
Commit each generated `go.sum` with its module files. The binary delivery
profile prepares application dependencies in the tagged module before building;
the committed sums keep that prepared checkout clean for delivery verification.
Then select a module and semantic version with the shared launcher:
```sh
./release.sh root v1.2.3
./release.sh ckconfig v1.2.3
./release.sh core-v2 v2.1.0
```
The launcher copies the selected module's `go.mod` and `go.sum` to temporary
alternate module files outside the checkout, resolves ReleaseKit from that
module's local dependency selection, and builds the tool there. It invokes
`publish` with the repository profile and `--expected-module` so the library
can verify that the profile agrees with the selected table row. The temporary
files and tool are removed 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,
then publish the integration with the version that consumes it. For example,
publish the core release before an integration that requires that release.
This declaration does not infer dependency order or rerun the standard suite.
The maintained [Woodpecker example](woodpecker.yml) uses the same map and
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
outside the checkout, and builds the ReleaseKit version selected there. It then
uses `ci-deliver --prepared` with the mapped profile and expected physical module.
The `core-v2` profile demonstrates binary delivery; the other profiles are
page-only. Before enabling the workflow, configure each selected profile's
`delivery` object with `"forge": "gitea"`, its `base_url`, owner, and repository,
then add the Woodpecker repository secret
`releasekit_gitea_token`; the workflow exposes it as
`RELEASEKIT_GITEA_TOKEN` only in the delivery step.
Retries use the selected tag's module files and matching workflow. Tags whose
tool predates this interface use their corresponding historical workflow.
## Local source verification
For verification before a compatible release is published, copy this example
into a disposable consumer checkout. Set `RELEASEKIT_SOURCE` to the absolute
path of a prepared ReleaseKit checkout, then select its source in those fixture
modules:
```sh
: "${RELEASEKIT_SOURCE:?Set the absolute ReleaseKit checkout path}"
for module_dir in . integrations/ckconfig integrations/core/v2; do
go -C "$module_dir" mod edit \
-require=go.maximumdirect.net/releasekit@v0.0.0 \
-replace="go.maximumdirect.net/releasekit=$RELEASEKIT_SOURCE" \
-tool=go.maximumdirect.net/releasekit/cmd/releasekit
GOTOOLCHAIN=local GOWORK=off go -C "$module_dir" mod tidy
done
```
Here `v0.0.0` is a fixture placeholder resolved by the local replacement.
Keep these declarations in the disposable checkout. Add representative product
source and each selected product's module-local release note, then commit the
fixture and run the source-selected tool without publishing:
```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
go -C integrations/core/v2 tool releasekit check --config releasekit-core-v2.json v2.1.0
```
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
version. Prepared dependencies allow this verification with `GOPROXY=off` and
`GOSUMDB=off`.

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,11 @@
package main
import (
"fmt"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() {
fmt.Printf("core %s\n", buildinfo.Version())
}

View File

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

View File

@@ -0,0 +1,48 @@
#!/bin/sh
set -eu
usage() {
echo "usage: release.sh SELECTOR VERSION" >&2
exit 2
}
[ "$#" -eq 2 ] || usage
selector=$1
version=$2
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repository_dir=$(git -C "$script_dir" rev-parse --show-toplevel)
bootstrap_dir=$(mktemp -d "$(dirname "$repository_dir")/.releasekit-bootstrap.XXXXXX")
selection_file=$bootstrap_dir/module-selection.tsv
trap 'rm -rf "$bootstrap_dir"' EXIT
"$script_dir/select-module.sh" selector "$selector" > "$selection_file"
tab=$(printf '\t')
IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file"
module_path=$repository_dir
if [ "$module_dir" != . ]; then
module_path=$repository_dir/$module_dir
fi
cp "$module_path/go.mod" "$bootstrap_dir/releasekit.mod"
if [ -f "$module_path/go.sum" ]; then
cp "$module_path/go.sum" "$bootstrap_dir/releasekit.sum"
else
: > "$bootstrap_dir/releasekit.sum"
fi
releasekit_module=go.maximumdirect.net/releasekit
(
cd "$module_path"
export GOWORK=off
export GOTOOLCHAIN=local
go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -m "$releasekit_module"
go build -mod=mod -modfile="$bootstrap_dir/releasekit.mod" \
-o "$bootstrap_dir/releasekit" "$releasekit_module/cmd/releasekit"
)
"$bootstrap_dir/releasekit" publish \
--repo "$repository_dir" \
--config "$profile_path" \
--expected-module "$module_dir" \
"$version"

View File

@@ -0,0 +1,4 @@
{
"product": "Example Consumer Integration",
"module_dir": "integrations/ckconfig"
}

View File

@@ -0,0 +1,9 @@
{
"product": "Example Consumer Core v2",
"module_dir": "integrations/core/v2",
"build": {
"main_package": ".",
"binary_name": "core",
"targets": ["linux/amd64"]
}
}

View File

@@ -0,0 +1,4 @@
{
"product": "Example Consumer",
"module_dir": "."
}

View File

@@ -0,0 +1,70 @@
#!/bin/sh
set -eu
usage() {
echo "usage: select-module.sh selector|tag VALUE" >&2
exit 2
}
[ "$#" -eq 2 ] || usage
mode=$1
value=$2
case "$mode" in
selector|tag) ;;
*) usage ;;
esac
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
mapping=${RELEASEKIT_MODULE_MAP:-$script_dir/release-modules.tsv}
[ -f "$mapping" ] || { echo "module map not found: $mapping" >&2; exit 2; }
tab=$(printf '\t')
matches=0
selected_selector=
selected_pattern=
selected_module=
selected_profile=
while IFS="$tab" read -r selector pattern module profile || [ -n "${selector:-}${pattern:-}${module:-}${profile:-}" ]; do
case "${selector:-}" in
''|\#*) continue ;;
esac
fields=$(awk -F '\t' '{ print NF }' <<EOF
$selector$tab$pattern$tab$module$tab$profile
EOF
)
[ "$fields" -eq 4 ] || { echo "module map row must have four tab-separated fields" >&2; exit 2; }
[ -n "$pattern" ] && [ -n "$module" ] && [ -n "$profile" ] || {
echo "module map row has an empty field for selector $selector" >&2
exit 2
}
matched=false
if [ "$mode" = selector ]; then
[ "$selector" = "$value" ] && matched=true
else
# The value remains a shell pattern in this case statement; it is never eval'd.
case "$value" in
$pattern) matched=true ;;
esac
fi
if [ "$matched" = true ]; then
matches=$((matches + 1))
selected_selector=$selector
selected_pattern=$pattern
selected_module=$module
selected_profile=$profile
fi
done < "$mapping"
if [ "$matches" -ne 1 ]; then
if [ "$matches" -eq 0 ]; then
echo "no module map row matches $mode $value" >&2
else
echo "module map has ambiguous rows for $mode $value" >&2
fi
exit 2
fi
printf '%s\t%s\t%s\t%s\n' \
"$selected_selector" "$selected_pattern" "$selected_module" "$selected_profile"

View File

@@ -0,0 +1,67 @@
when:
- event: tag
ref:
include:
- refs/tags/v[01].*
- refs/tags/integrations/ckconfig/v*
- refs/tags/integrations/core/v2.*
steps:
- name: deliver
image: golang:1.26.10-bookworm
environment:
RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token
commands:
- |
set -eu
test -n "$${CI_COMMIT_TAG}"
test -n "$${CI_COMMIT_SHA}"
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(git rev-parse --verify "$${CI_COMMIT_SHA}^{commit}")
if [ "$${tag_commit}" != "$${expected_commit}" ]; then
printf 'Tag %s resolves to commit %s; event %s resolves to commit %s\n' \
"$${CI_COMMIT_TAG}" "$${tag_commit}" "$${CI_COMMIT_SHA}" "$${expected_commit}" >&2
exit 1
fi
git checkout --detach "$${tag_commit}"
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
test -z "$(git status --porcelain --untracked-files=all)"
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-bootstrap.XXXXXX")
trap 'rm -rf "$${bootstrap_dir}"' EXIT
selection_file="$${bootstrap_dir}/module-selection.tsv"
"$${CI_WORKSPACE}/select-module.sh" tag "$${CI_COMMIT_TAG}" > "$${selection_file}"
tab=$(printf '\t')
IFS="$${tab}" read -r selector tag_pattern module_dir profile_path < "$${selection_file}"
module_path="$${CI_WORKSPACE}"
if [ "$${module_dir}" != . ]; then
module_path="$${CI_WORKSPACE}/$${module_dir}"
fi
cp "$${module_path}/go.mod" "$${bootstrap_dir}/go.mod"
if [ -f "$${module_path}/go.sum" ]; then
cp "$${module_path}/go.sum" "$${bootstrap_dir}/go.sum"
else
: > "$${bootstrap_dir}/go.sum"
fi
cp "$${bootstrap_dir}/go.mod" "$${bootstrap_dir}/releasekit.mod"
cp "$${bootstrap_dir}/go.sum" "$${bootstrap_dir}/releasekit.sum"
export GOWORK=off
export GOTOOLCHAIN=local
releasekit_module=go.maximumdirect.net/releasekit
(
cd "$${module_path}"
go list -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" -m "$${releasekit_module}"
go build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
)
"$${bootstrap_dir}/releasekit" ci-deliver \
--repo "$${CI_WORKSPACE}" \
--config "$${profile_path}" \
--expected-module "$${module_dir}" \
--prepared \
--commit "$${expected_commit}" \
"$${CI_COMMIT_TAG}"

View File

@@ -7,6 +7,7 @@
"targets": ["linux/amd64", "linux/arm64", "darwin/arm64"] "targets": ["linux/amd64", "linux/arm64", "darwin/arm64"]
}, },
"delivery": { "delivery": {
"forge": "gitea",
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",

View File

@@ -2,6 +2,7 @@
"product": "Example", "product": "Example",
"remote": "origin", "remote": "origin",
"delivery": { "delivery": {
"forge": "gitea",
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",

View File

@@ -4,7 +4,7 @@ when:
steps: steps:
- name: deliver - name: deliver
image: golang:1.25.0-bookworm image: golang:1.26.10-bookworm
environment: environment:
RELEASEKIT_GITEA_TOKEN: RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token from_secret: releasekit_gitea_token
@@ -15,9 +15,13 @@ steps:
test -n "$${CI_COMMIT_SHA}" test -n "$${CI_COMMIT_SHA}"
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}" git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}" git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}") tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]') expected_commit=$(git rev-parse --verify "$${CI_COMMIT_SHA}^{commit}")
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}" if [ "$${tag_commit}" != "$${expected_commit}" ]; then
printf 'Tag %s resolves to commit %s; event %s resolves to commit %s\n' \
"$${CI_COMMIT_TAG}" "$${tag_commit}" "$${CI_COMMIT_SHA}" "$${expected_commit}" >&2
exit 1
fi
git checkout --detach "$${tag_commit}" git checkout --detach "$${tag_commit}"
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}" test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
test -z "$(git status --porcelain --untracked-files=all)" test -z "$(git status --porcelain --untracked-files=all)"
@@ -29,5 +33,6 @@ steps:
go build -mod=readonly -o "$${bootstrap_dir}/releasekit" ./cmd/releasekit go build -mod=readonly -o "$${bootstrap_dir}/releasekit" ./cmd/releasekit
"$${bootstrap_dir}/releasekit" ci-deliver \ "$${bootstrap_dir}/releasekit" ci-deliver \
--repo "$${CI_WORKSPACE}" \ --repo "$${CI_WORKSPACE}" \
--commit "$${CI_COMMIT_SHA}" \ --prepared \
--commit "$${expected_commit}" \
"$${CI_COMMIT_TAG}" "$${CI_COMMIT_TAG}"

View File

@@ -1,6 +1,6 @@
matrix: matrix:
include: include:
- GO_IMAGE: golang:1.25.0-bookworm - GO_IMAGE: golang:1.26.10-bookworm
when: when:
- event: tag - event: tag
@@ -19,9 +19,13 @@ steps:
test -n "$${CI_COMMIT_SHA}" test -n "$${CI_COMMIT_SHA}"
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}" git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}" git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}") tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]') expected_commit=$(git rev-parse --verify "$${CI_COMMIT_SHA}^{commit}")
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}" if [ "$${tag_commit}" != "$${expected_commit}" ]; then
printf 'Tag %s resolves to commit %s; event %s resolves to commit %s\n' \
"$${CI_COMMIT_TAG}" "$${tag_commit}" "$${CI_COMMIT_SHA}" "$${expected_commit}" >&2
exit 1
fi
git checkout --detach "$${tag_commit}" git checkout --detach "$${tag_commit}"
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}" test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
test -z "$(git status --porcelain --untracked-files=all)" test -z "$(git status --porcelain --untracked-files=all)"
@@ -39,11 +43,12 @@ steps:
export GOWORK=off export GOWORK=off
export GOTOOLCHAIN=local export GOTOOLCHAIN=local
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit releasekit_module=go.maximumdirect.net/releasekit
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 build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit" -o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
"$${bootstrap_dir}/releasekit" ci-deliver \ "$${bootstrap_dir}/releasekit" ci-deliver \
--repo "$${CI_WORKSPACE}" \ --repo "$${CI_WORKSPACE}" \
--commit "$${CI_COMMIT_SHA}" \ --prepared \
--commit "$${expected_commit}" \
"$${CI_COMMIT_TAG}" "$${CI_COMMIT_TAG}"

4
go.mod
View File

@@ -1,6 +1,6 @@
module gitea.maximumdirect.net/eric/ReleaseKit module go.maximumdirect.net/releasekit
go 1.25.0 go 1.26.0
require ( require (
github.com/yuin/goldmark/v2 v2.1.6 github.com/yuin/goldmark/v2 v2.1.6

View File

@@ -15,7 +15,7 @@ import (
"strings" "strings"
) )
const modulePath = "gitea.maximumdirect.net/eric/ReleaseKit" const modulePath = "go.maximumdirect.net/releasekit"
var facades = []string{modulePath, modulePath + "/buildinfo"} var facades = []string{modulePath, modulePath + "/buildinfo"}
@@ -226,6 +226,33 @@ func checkImportDirections(packages []listedPackage) error {
} }
visit(modulePath + "/buildinfo") visit(modulePath + "/buildinfo")
for _, root := range []string{
modulePath + "/internal/delivery",
modulePath + "/internal/forge",
modulePath + "/internal/artifact",
} {
seen := make(map[string]bool)
var visitDelivery func(string)
visitDelivery = func(path string) {
if seen[path] {
return
}
seen[path] = true
if path == modulePath+"/internal/gitea" {
violations = append(violations, fmt.Sprintf("shared package %s depends on Gitea adapter", root))
return
}
pkg, ok := byPath[path]
if !ok {
return
}
for _, imported := range pkg.Imports {
visitDelivery(imported)
}
}
visitDelivery(root)
}
if len(violations) == 0 { if len(violations) == 0 {
return nil return nil
} }
@@ -254,7 +281,7 @@ func commandInternalRoot(path string) string {
func forbiddenRuntimeDependency(path string) bool { func forbiddenRuntimeDependency(path string) bool {
for _, part := range strings.Split(strings.ToLower(path), "/") { for _, part := range strings.Split(strings.ToLower(path), "/") {
switch part { switch part {
case "orchestration", "orchestrator", "engine", "release", "process", "build", "builder", "gitea", "delivery", "cli": case "orchestration", "orchestrator", "engine", "release", "process", "build", "builder", "gitea", "forge", "delivery", "cli":
return true return true
} }
} }

View File

@@ -10,6 +10,26 @@ import (
"testing" "testing"
) )
func TestRuntimeFacadeCannotDependOnForge(t *testing.T) {
for _, indirect := range []bool{false, true} {
name := "direct"
dependency := modulePath + "/internal/forge"
packages := []listedPackage{{ImportPath: dependency}}
if indirect {
name = "transitive"
packages = append(packages, listedPackage{ImportPath: modulePath + "/internal/runtime", Imports: []string{dependency}})
dependency = modulePath + "/internal/runtime"
}
packages = append(packages, listedPackage{ImportPath: modulePath + "/buildinfo", Imports: []string{dependency}})
t.Run(name, func(t *testing.T) {
err := checkImportDirections(packages)
if err == nil || !strings.Contains(err.Error(), "buildinfo") || !strings.Contains(err.Error(), "/internal/forge") {
t.Fatalf("dependency check = %v, want excluded forge runtime dependency", err)
}
})
}
}
func TestExportedContractBoundaries(t *testing.T) { func TestExportedContractBoundaries(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -162,6 +182,30 @@ func TestRuntimeFacadeCannotDependOnExternalPackages(t *testing.T) {
} }
} }
func TestSharedDeliveryPackagesCannotDependOnGitea(t *testing.T) {
allowed := []listedPackage{
{ImportPath: modulePath + "/internal/delivery", Imports: []string{modulePath + "/internal/forge", modulePath + "/internal/artifact"}},
{ImportPath: modulePath + "/internal/forge"},
{ImportPath: modulePath + "/internal/artifact"},
{ImportPath: modulePath + "/internal/gitea"},
}
if err := checkImportDirections(allowed); err != nil {
t.Fatalf("shared delivery boundary rejected neutral dependencies: %v", err)
}
violating := []listedPackage{
{ImportPath: modulePath + "/internal/delivery", Imports: []string{modulePath + "/internal/policy"}},
{ImportPath: modulePath + "/internal/policy", Imports: []string{modulePath + "/internal/gitea"}},
{ImportPath: modulePath + "/internal/forge"},
{ImportPath: modulePath + "/internal/artifact"},
{ImportPath: modulePath + "/internal/gitea"},
}
err := checkImportDirections(violating)
if err == nil || !strings.Contains(err.Error(), "shared package "+modulePath+"/internal/delivery depends on Gitea adapter") {
t.Fatalf("checkImportDirections() error = %v, want transitive shared-delivery violation", err)
}
}
func checkFixture(t *testing.T, facadeSource string) []string { func checkFixture(t *testing.T, facadeSource string) []string {
t.Helper() t.Helper()
fset := token.NewFileSet() fset := token.NewFileSet()

View File

@@ -3,21 +3,51 @@ package artifact
import ( import (
"fmt" "fmt"
"path/filepath"
"strings" "strings"
) )
const ManifestFilename = "SHA256SUMS" const ManifestFilename = "SHA256SUMS"
// OutputDirectory resolves build output and prebuilt asset directories from
// the absolute selected module directory.
func OutputDirectory(moduleDir, directory string) string {
if directory == "" {
directory = "dist"
}
if !filepath.IsAbs(directory) {
directory = filepath.Join(moduleDir, directory)
}
return filepath.Clean(directory)
}
type Target struct { type Target struct {
OS string OS string
Arch string Arch string
} }
// Settings contains normalized inputs shared by build execution and evidence.
type Settings struct {
MainPackage string
BinaryName string
Targets []Target
}
type Declaration struct { type Declaration struct {
Target Target Target Target
Filename string Filename string
} }
// NormalizeSettings copies build inputs and removes duplicate targets while
// preserving their first occurrence.
func NormalizeSettings(mainPackage, binaryName string, targets []Target) Settings {
return Settings{
MainPackage: mainPackage,
BinaryName: binaryName,
Targets: NormalizeTargets(targets),
}
}
// NormalizeTargets removes duplicate targets while preserving their first // NormalizeTargets removes duplicate targets while preserving their first
// occurrence. // occurrence.
func NormalizeTargets(targets []Target) []Target { func NormalizeTargets(targets []Target) []Target {
@@ -60,3 +90,30 @@ func ExpectedBuild(binaryName, version string, targets []Target) []Declaration {
} }
return declarations return declarations
} }
// ValidateDeclarations matches recorded artifact identities to selected targets.
func ValidateDeclarations(binaryName, version string, targets []Target, recorded []Declaration) error {
if len(recorded) != len(targets) {
return fmt.Errorf("artifact and target counts do not match")
}
want := make(map[Target]string, len(targets))
for _, declaration := range ExpectedBuild(binaryName, version, targets) {
target := declaration.Target
if !ValidComponent(target.OS) || !ValidComponent(target.Arch) {
return fmt.Errorf("invalid target %q/%q", target.OS, target.Arch)
}
if _, exists := want[target]; exists {
return fmt.Errorf("repeats target %q/%q", target.OS, target.Arch)
}
want[target] = declaration.Filename
}
seen := make(map[Target]bool, len(recorded))
for _, declaration := range recorded {
name, ok := want[declaration.Target]
if !ok || seen[declaration.Target] || declaration.Filename != name {
return fmt.Errorf("artifact %q does not match a selected target and its declared name", declaration.Filename)
}
seen[declaration.Target] = true
}
return nil
}

View File

@@ -17,6 +17,22 @@ func TestNormalizeTargetsPreservesOrderAndFirstOccurrence(t *testing.T) {
} }
} }
func TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets(t *testing.T) {
settings := NormalizeSettings("./cmd/app", "app", []Target{
{OS: "linux", Arch: "amd64"},
{OS: "windows", Arch: "arm64"},
{OS: "linux", Arch: "amd64"},
})
want := Settings{
MainPackage: "./cmd/app",
BinaryName: "app",
Targets: []Target{{OS: "linux", Arch: "amd64"}, {OS: "windows", Arch: "arm64"}},
}
if !reflect.DeepEqual(settings, want) {
t.Fatalf("NormalizeSettings() = %#v, want %#v", settings, want)
}
}
func TestExpectedBuildUsesSharedNamesInTargetOrder(t *testing.T) { func TestExpectedBuildUsesSharedNamesInTargetOrder(t *testing.T) {
targets := []Target{{OS: "windows", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}} targets := []Target{{OS: "windows", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}}
want := []Declaration{ want := []Declaration{
@@ -40,3 +56,31 @@ func TestValidComponentPreservesBuildAndReceiptRules(t *testing.T) {
} }
} }
} }
func TestValidateDeclarationsMatchesTargetsAndNames(t *testing.T) {
linux := Target{OS: "linux", Arch: "amd64"}
windows := Target{OS: "windows", Arch: "arm64"}
first := Declaration{Target: linux, Filename: "app-v1.2.3-linux-amd64"}
second := Declaration{Target: windows, Filename: "app-v1.2.3-windows-arm64.exe"}
for _, test := range []struct {
name string
targets []Target
recorded []Declaration
valid bool
}{
{"reordered", []Target{linux, windows}, []Declaration{second, first}, true},
{"count", []Target{linux, windows}, []Declaration{first}, false},
{"duplicate target", []Target{linux, linux}, []Declaration{first, first}, false},
{"duplicate artifact", []Target{linux, windows}, []Declaration{first, first}, false},
{"incorrect name", []Target{linux}, []Declaration{{Target: linux, Filename: "other"}}, false},
{"unknown target", []Target{linux}, []Declaration{second}, false},
{"unsafe target", []Target{{OS: "linux/other", Arch: "amd64"}}, []Declaration{{Target: linux, Filename: first.Filename}}, false},
} {
t.Run(test.name, func(t *testing.T) {
err := ValidateDeclarations("app", "v1.2.3", test.targets, test.recorded)
if (err == nil) != test.valid {
t.Fatalf("ValidateDeclarations() error = %v, valid = %t", err, test.valid)
}
})
}
}

141
internal/artifact/assets.go Normal file
View File

@@ -0,0 +1,141 @@
package artifact
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sort"
"strings"
)
var (
// ErrInvalidAsset identifies an invalid asset declaration or unreadable
// local path.
ErrInvalidAsset = errors.New("invalid asset")
// ErrAssetConflict identifies local content that does not match its
// declared identity.
ErrAssetConflict = errors.New("asset content conflict")
)
// ExpectedAsset describes the local content declared for hosted delivery.
// Content is populated for inline assets such as the generated checksum
// manifest; Path identifies file content for later streaming uploads.
type ExpectedAsset struct {
Filename string
SHA256 string
Size int64
Path string
Content []byte
}
// BuildManifest creates the deterministic checksum file for the declared
// binaries. An empty binary set produces no manifest.
func BuildManifest(binaries []ExpectedAsset) (ExpectedAsset, error) {
if len(binaries) == 0 {
return ExpectedAsset{}, nil
}
ordered := append([]ExpectedAsset(nil), binaries...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i].Filename < ordered[j].Filename })
var body strings.Builder
seen := make(map[string]struct{}, len(ordered))
for _, binary := range ordered {
if !validAssetName(binary.Filename) || binary.Filename == ManifestFilename || !validSHA256(binary.SHA256) {
return ExpectedAsset{}, fmt.Errorf("%w: invalid binary identity for %q", ErrInvalidAsset, binary.Filename)
}
if _, exists := seen[binary.Filename]; exists {
return ExpectedAsset{}, fmt.Errorf("%w: duplicate binary filename %q", ErrInvalidAsset, binary.Filename)
}
seen[binary.Filename] = struct{}{}
fmt.Fprintf(&body, "%s %s\n", binary.SHA256, binary.Filename)
}
content := []byte(body.String())
return ExpectedAsset{Filename: ManifestFilename, SHA256: digest(content), Size: int64(len(content)), Content: content}, nil
}
// ValidateExpectedAssets checks the declarations before they are compared
// with remote content or uploaded.
func ValidateExpectedAssets(expected []ExpectedAsset) error {
seen := make(map[string]struct{}, len(expected))
for _, item := range expected {
if !validAssetName(item.Filename) || !validSHA256(item.SHA256) || item.Size < 0 {
return fmt.Errorf("%w: %q", ErrInvalidAsset, item.Filename)
}
if _, duplicate := seen[item.Filename]; duplicate {
return fmt.Errorf("%w: duplicate expected asset %q", ErrInvalidAsset, item.Filename)
}
seen[item.Filename] = struct{}{}
if len(item.Content) > 0 && (int64(len(item.Content)) != item.Size || digest(item.Content) != item.SHA256) {
return fmt.Errorf("%w: expected content does not match identity for %q", ErrInvalidAsset, item.Filename)
}
}
return nil
}
// VerifyLocalAssets checks that every expected file still matches its declared
// size and digest before hosted writes begin.
func VerifyLocalAssets(assets []ExpectedAsset) error {
if err := ValidateExpectedAssets(assets); err != nil {
return err
}
for _, asset := range assets {
if err := verifyLocalAsset(asset); err != nil {
return err
}
}
return nil
}
func verifyLocalAsset(asset ExpectedAsset) error {
if len(asset.Content) > 0 {
if int64(len(asset.Content)) != asset.Size || digest(asset.Content) != asset.SHA256 {
return fmt.Errorf("%w: local content does not match declared asset %q", ErrAssetConflict, asset.Filename)
}
return nil
}
if asset.Path == "" || filepath.Base(asset.Path) != asset.Filename {
return fmt.Errorf("%w: local path for %q does not match its filename", ErrInvalidAsset, asset.Filename)
}
file, err := os.Open(asset.Path)
if err != nil {
return fmt.Errorf("%w: open %q: %w", ErrInvalidAsset, asset.Filename, err)
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return fmt.Errorf("%w: stat %q: %w", ErrInvalidAsset, asset.Filename, err)
}
if !info.Mode().IsRegular() || info.Size() != asset.Size {
return fmt.Errorf("%w: local file does not match declared size for %q", ErrAssetConflict, asset.Filename)
}
hasher := sha256.New()
size, err := io.Copy(hasher, file)
if err != nil {
return fmt.Errorf("%w: read %q: %w", ErrInvalidAsset, asset.Filename, err)
}
if size != asset.Size || hex.EncodeToString(hasher.Sum(nil)) != asset.SHA256 {
return fmt.Errorf("%w: local content does not match declared asset %q", ErrAssetConflict, asset.Filename)
}
return nil
}
func validAssetName(name string) bool {
return name != "" && name != "." && name != ".." && path.Base(name) == name && !strings.ContainsAny(name, "\\\r\n\x00")
}
func validSHA256(value string) bool {
if len(value) != sha256.Size*2 {
return false
}
_, err := hex.DecodeString(value)
return err == nil && strings.ToLower(value) == value
}
func digest(content []byte) string {
sum := sha256.Sum256(content)
return hex.EncodeToString(sum[:])
}

View File

@@ -0,0 +1,93 @@
package artifact
import (
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"strings"
"testing"
)
func TestBuildManifestSortsNamesAndOmitsEmptySourceOnlyManifest(t *testing.T) {
manifest, err := BuildManifest([]ExpectedAsset{
assetFor("zeta.bin", []byte("zeta")),
assetFor("alpha.bin", []byte("alpha")),
})
if err != nil {
t.Fatal(err)
}
want := assetDigest([]byte("alpha")) + " alpha.bin\n" + assetDigest([]byte("zeta")) + " zeta.bin\n"
if string(manifest.Content) != want || manifest.Filename != ManifestFilename || manifest.SHA256 != assetDigest([]byte(want)) || manifest.Size != int64(len(want)) {
t.Fatalf("manifest = %#v, want content %q", manifest, want)
}
empty, err := BuildManifest(nil)
if err != nil || empty.Filename != "" || len(empty.Content) != 0 {
t.Fatalf("empty manifest = %#v, error = %v", empty, err)
}
}
func TestBuildManifestRejectsInvalidOrDuplicateDeclarations(t *testing.T) {
for _, test := range []struct {
name string
assets []ExpectedAsset
}{
{name: "invalid filename", assets: []ExpectedAsset{assetFor("../app.bin", []byte("app"))}},
{name: "manifest filename", assets: []ExpectedAsset{assetFor(ManifestFilename, []byte("app"))}},
{name: "invalid digest", assets: []ExpectedAsset{{Filename: "app.bin", SHA256: "not-a-digest"}}},
{name: "duplicate filename", assets: []ExpectedAsset{assetFor("app.bin", []byte("one")), assetFor("app.bin", []byte("two"))}},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := BuildManifest(test.assets); err == nil {
t.Fatal("BuildManifest() succeeded for invalid declarations")
}
})
}
}
func TestVerifyLocalAssetsRejectsSameSizeTampering(t *testing.T) {
path := filepath.Join(t.TempDir(), "app.bin")
original := []byte("alpha")
if err := os.WriteFile(path, original, 0o600); err != nil {
t.Fatal(err)
}
asset := assetFor(filepath.Base(path), original)
asset.Content = nil
asset.Path = path
if err := VerifyLocalAssets([]ExpectedAsset{asset}); err != nil {
t.Fatal(err)
}
tampered := []byte("bravo")
if err := os.WriteFile(path, tampered, 0o600); err != nil {
t.Fatal(err)
}
if err := VerifyLocalAssets([]ExpectedAsset{asset}); err == nil || !strings.Contains(err.Error(), "does not match declared asset") {
t.Fatalf("VerifyLocalAssets() error = %v, want content mismatch", err)
}
}
func TestValidateExpectedAssetsRejectsDuplicateAndMismatchedInlineContent(t *testing.T) {
asset := assetFor("app.bin", []byte("alpha"))
if err := ValidateExpectedAssets([]ExpectedAsset{asset, asset}); err == nil || !strings.Contains(err.Error(), "duplicate") {
t.Fatalf("ValidateExpectedAssets() error = %v, want duplicate", err)
}
asset.Content = []byte("bravo")
if err := ValidateExpectedAssets([]ExpectedAsset{asset}); err == nil || !strings.Contains(err.Error(), "does not match identity") {
t.Fatalf("ValidateExpectedAssets() error = %v, want content mismatch", err)
}
}
func assetFor(filename string, content []byte) ExpectedAsset {
return ExpectedAsset{
Filename: filename,
SHA256: assetDigest(content),
Size: int64(len(content)),
Content: append([]byte(nil), content...),
}
}
func assetDigest(content []byte) string {
sum := sha256.Sum256(content)
return hex.EncodeToString(sum[:])
}

View File

@@ -2,6 +2,7 @@
package build package build
import ( import (
"bytes"
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
@@ -9,30 +10,28 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"os/exec"
"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/candidate" "go.maximumdirect.net/releasekit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool" "go.maximumdirect.net/releasekit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/tempdir"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
type Target = artifact.Target type Target = artifact.Target
type Spec = artifact.Settings
type Spec struct {
MainPackage string
BinaryName string
Targets []Target
}
type Request struct { type Request struct {
RepositoryDir string Identity releaseidentity.Identity
Version string Spec Spec
Spec Spec OutputDir string
OutputDir string Output io.Writer
Output io.Writer ToolOwner *gotool.Owner
} }
type Artifact struct { type Artifact struct {
@@ -44,38 +43,47 @@ type Artifact struct {
type Result struct { type Result struct {
RepositoryDir string RepositoryDir string
ModuleDir string
ModulePath string
Tag string
CandidateCommit string CandidateCommit string
SourceVerified bool SourceVerified bool
Settings artifact.Settings
Version string Version string
MainPackage string
BinaryName string
OutputDir string OutputDir string
Targets []Target
Artifacts []Artifact Artifacts []Artifact
Compiler string Compiler string
} }
func Build(ctx context.Context, request Request) (Result, error) { func BuildResolved(ctx context.Context, request Request) (Result, error) {
result := Result{ return buildResolved(ctx, request, os.RemoveAll)
Version: request.Version, }
MainPackage: request.Spec.MainPackage,
BinaryName: request.Spec.BinaryName, func buildResolved(ctx context.Context, request Request, remove func(string) error) (result Result, resultErr error) {
Targets: artifact.NormalizeTargets(request.Spec.Targets), identity := request.Identity
settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets)
result = Result{
RepositoryDir: identity.RepositoryDir,
ModuleDir: identity.ModuleDir,
ModulePath: identity.ModulePath,
Tag: identity.Tag,
Settings: settings,
Version: identity.Version,
} }
if !versioncontract.ValidStableVersion(request.Version) { if !versioncontract.ValidStableVersion(identity.Version) {
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, request.Version) return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version)
} }
if request.RepositoryDir == "" { if identity.RepositoryDir == "" || identity.ModuleDir == "" || identity.ModulePath == "" {
return result, errors.New("build requires a repository directory") return result, errors.New("build requires a resolved module identity")
} }
if len(result.Targets) != 0 { if len(settings.Targets) != 0 {
if request.Spec.MainPackage == "" { if settings.MainPackage == "" {
return result, errors.New("build requires a main package when targets are selected") return result, errors.New("build requires a main package when targets are selected")
} }
if !artifact.ValidComponent(request.Spec.BinaryName) { if !artifact.ValidComponent(settings.BinaryName) {
return result, fmt.Errorf("unsafe binary name %q", request.Spec.BinaryName) return result, fmt.Errorf("unsafe binary name %q", settings.BinaryName)
} }
for _, target := range result.Targets { for _, target := range settings.Targets {
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) { if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
return result, fmt.Errorf("unsafe target %q/%q", target.OS, target.Arch) return result, fmt.Errorf("unsafe target %q/%q", target.OS, target.Arch)
} }
@@ -84,28 +92,33 @@ func Build(ctx context.Context, request Request) (Result, error) {
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return result, fmt.Errorf("build canceled: %w", err) return result, fmt.Errorf("build canceled: %w", err)
} }
repositoryDir, err := filepath.Abs(request.RepositoryDir) repositoryDir, err := filepath.Abs(identity.RepositoryDir)
if err != nil { if err != nil {
return result, fmt.Errorf("resolve repository directory: %w", err) return result, fmt.Errorf("resolve repository directory: %w", err)
} }
result.RepositoryDir = repositoryDir result.RepositoryDir = repositoryDir
commit, err := gitCommit(ctx, repositoryDir) moduleDir, err := filepath.Abs(identity.ModuleDir)
if err != nil { if err != nil {
return result, err return result, fmt.Errorf("resolve module directory: %w", err)
}
result.ModuleDir = moduleDir
commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil {
return result, fmt.Errorf("read source commit: %w", err)
} }
result.CandidateCommit = commit result.CandidateCommit = commit
cleanBefore, err := cleanSource(ctx, repositoryDir) statusBefore, err := git.WorktreeStatus(ctx, repositoryDir)
if err != nil { if err != nil {
return result, err return result, fmt.Errorf("inspect build source: %w", err)
} }
if len(result.Targets) == 0 { if len(settings.Targets) == 0 {
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir) result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
return result, nil return result, nil
} }
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir) result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
declarations := artifact.ExpectedBuild(request.Spec.BinaryName, request.Version, result.Targets) declarations := artifact.ExpectedBuild(settings.BinaryName, identity.Version, settings.Targets)
filenames := make([]string, len(declarations)) filenames := make([]string, len(declarations))
for i, declaration := range declarations { for i, declaration := range declarations {
filenames[i] = declaration.Filename filenames[i] = declaration.Filename
@@ -114,11 +127,15 @@ func Build(ctx context.Context, request Request) (Result, error) {
return result, fmt.Errorf("create build output directory %q: %w", result.OutputDir, err) return result, fmt.Errorf("create build output directory %q: %w", result.OutputDir, err)
} }
goTool, err := gotool.New(ctx, repositoryDir) owner := request.ToolOwner
if owner == nil {
owner = gotool.NewOwner(moduleDir)
}
goTool, err := owner.Acquire(ctx)
if err != nil { if err != nil {
return result, fmt.Errorf("prepare Go toolchain: %w", err) return result, fmt.Errorf("prepare Go toolchain: %w", err)
} }
compiler, err := goTool.Run(ctx, repositoryDir, gotool.Native, gotool.Target{}, nil, "version") compiler, err := goTool.Output(ctx, moduleDir, gotool.Native, gotool.Target{}, nil, "version")
if err != nil { if err != nil {
return result, fmt.Errorf("identify Go compiler: %w", err) return result, fmt.Errorf("identify Go compiler: %w", err)
} }
@@ -126,7 +143,7 @@ func Build(ctx context.Context, request Request) (Result, error) {
goHost := goTool.HostTarget() goHost := goTool.HostTarget()
host := Target{OS: goHost.OS, Arch: goHost.Arch} host := Target{OS: goHost.OS, Arch: goHost.Arch}
for index, target := range result.Targets { for index, target := range settings.Targets {
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return result, fmt.Errorf("build canceled: %w", err) return result, fmt.Errorf("build canceled: %w", err)
} }
@@ -135,14 +152,14 @@ func Build(ctx context.Context, request Request) (Result, error) {
if request.Output != nil { if request.Output != nil {
fmt.Fprintf(request.Output, "building %s/%s as %s\n", target.OS, target.Arch, filename) fmt.Fprintf(request.Output, "building %s/%s as %s\n", target.OS, target.Arch, filename)
} }
if err := buildTarget(ctx, goTool, repositoryDir, request.Spec.MainPackage, path, request.Version, target); err != nil { if err := buildTarget(ctx, goTool, moduleDir, settings.MainPackage, path, identity.Version, target); err != nil {
return result, fmt.Errorf("build target %s/%s: %w", target.OS, target.Arch, err) return result, fmt.Errorf("build target %s/%s: %w", target.OS, target.Arch, err)
} }
artifact := Artifact{Path: path, Filename: filename, Target: target} artifact := Artifact{Path: path, Filename: filename, Target: target}
result.Artifacts = append(result.Artifacts, artifact) if err := hashArtifact(&artifact); err != nil {
if err := hashArtifact(&result.Artifacts[len(result.Artifacts)-1]); err != nil {
return result, fmt.Errorf("hash build output %q: %w", path, err) return result, fmt.Errorf("hash build output %q: %w", path, err)
} }
result.Artifacts = append(result.Artifacts, artifact)
} }
var smokePath string var smokePath string
@@ -153,68 +170,47 @@ func Build(ctx context.Context, request Request) (Result, error) {
} }
} }
if smokePath == "" { if smokePath == "" {
temporaryDir, err := os.MkdirTemp("", "releasekit-native-smoke-") temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-native-smoke-")
if err != nil { if err != nil {
return result, fmt.Errorf("create native smoke directory: %w", err) return result, fmt.Errorf("create native smoke directory: %w", err)
} }
defer os.RemoveAll(temporaryDir) defer func() {
smokePath = filepath.Join(temporaryDir, request.Spec.BinaryName) if err := remove(temporaryDir); err != nil {
resultErr = errors.Join(resultErr, fmt.Errorf("remove native smoke directory %q: %w", temporaryDir, err))
}
}()
smokePath = filepath.Join(temporaryDir, settings.BinaryName)
if host.OS == "windows" { if host.OS == "windows" {
smokePath += ".exe" smokePath += ".exe"
} }
if request.Output != nil { if request.Output != nil {
fmt.Fprintf(request.Output, "building temporary version check for %s/%s\n", host.OS, host.Arch) fmt.Fprintf(request.Output, "building temporary version check for %s/%s\n", host.OS, host.Arch)
} }
if err := buildTarget(ctx, goTool, repositoryDir, request.Spec.MainPackage, smokePath, request.Version, host); err != nil { if err := buildTarget(ctx, goTool, moduleDir, settings.MainPackage, smokePath, identity.Version, host); err != nil {
return result, fmt.Errorf("build native version check: %w", err) return result, fmt.Errorf("build native version check: %w", err)
} }
} }
if request.Output != nil { if request.Output != nil {
fmt.Fprintf(request.Output, "checking %s version output\n", request.Spec.BinaryName) fmt.Fprintf(request.Output, "checking %s version output\n", settings.BinaryName)
} }
if err := checkVersion(ctx, smokePath, request.Spec.BinaryName, request.Version); err != nil { if err := checkVersion(ctx, smokePath, settings.BinaryName, identity.Version); err != nil {
return result, err return result, err
} }
commitAfter, err := gitCommit(ctx, repositoryDir) commitAfter, err := git.CaptureHead(ctx, repositoryDir)
if err != nil { if err != nil {
return result, err return result, fmt.Errorf("read source commit: %w", err)
} }
cleanAfter, err := cleanSource(ctx, repositoryDir) statusAfter, err := git.WorktreeStatus(ctx, repositoryDir)
if err != nil { if err != nil {
return result, err return result, fmt.Errorf("inspect build source: %w", err)
} }
result.SourceVerified = cleanBefore && cleanAfter && commitAfter == commit result.SourceVerified = statusBefore == "" && statusAfter == "" && commitAfter == commit
return result, nil return result, nil
} }
func resolvedOutputDir(repositoryDir, outputDir string) string { func buildTarget(ctx context.Context, goTool *gotool.Tool, moduleDir, mainPackage, outputPath, version string, target Target) error {
if outputDir == "" {
outputDir = filepath.Join(repositoryDir, "dist")
} else if !filepath.IsAbs(outputDir) {
outputDir = filepath.Join(repositoryDir, outputDir)
}
resolved, err := filepath.Abs(outputDir)
if err != nil {
return filepath.Clean(outputDir)
}
return resolved
}
func gitCommit(ctx context.Context, repositoryDir string) (string, error) {
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
output, err := command.Output()
if err != nil {
if ctx.Err() != nil {
return "", fmt.Errorf("read source commit: %w", ctx.Err())
}
return "", fmt.Errorf("read source commit: %w", err)
}
return strings.TrimSpace(string(output)), nil
}
func buildTarget(ctx context.Context, goTool *gotool.Tool, repositoryDir, mainPackage, outputPath, version string, target Target) error {
ldflags := "-s -w -X " + versioncontract.InjectedVersionLinkerSymbol + "=" + version ldflags := "-s -w -X " + versioncontract.InjectedVersionLinkerSymbol + "=" + version
_, err := goTool.Run(ctx, repositoryDir, gotool.Static, gotool.Target{OS: target.OS, Arch: target.Arch}, nil, err := goTool.Run(ctx, moduleDir, gotool.Static, gotool.Target{OS: target.OS, Arch: target.Arch}, nil,
"build", "-o", outputPath, "-mod=readonly", "-trimpath", "-buildvcs=false", "-ldflags", ldflags, mainPackage) "build", "-o", outputPath, "-mod=readonly", "-trimpath", "-buildvcs=false", "-ldflags", ldflags, mainPackage)
return err return err
} }
@@ -234,26 +230,14 @@ func hashArtifact(artifact *Artifact) error {
} }
func checkVersion(ctx context.Context, binaryPath, binaryName, version string) error { func checkVersion(ctx context.Context, binaryPath, binaryName, version string) error {
command := exec.CommandContext(ctx, binaryPath, "version") var output bytes.Buffer
output, err := command.CombinedOutput() err := process.Run(ctx, process.Invocation{Args: []string{binaryPath, "version"}, Stdout: &output, Stderr: &output})
if err != nil { if err != nil {
if ctx.Err() != nil { return fmt.Errorf("run native version check: %w: %s", err, strings.TrimSpace(output.String()))
return fmt.Errorf("run native version check: %w", ctx.Err())
}
return fmt.Errorf("run native version check: %w: %s", err, strings.TrimSpace(string(output)))
} }
want := binaryName + " " + version + "\n" want := binaryName + " " + version + "\n"
if string(output) != want { if output.String() != want {
return fmt.Errorf("native version output = %q, want %q", output, want) return fmt.Errorf("native version output = %q, want %q", output.String(), want)
} }
return nil return nil
} }
func cleanSource(ctx context.Context, repositoryDir string) (bool, error) {
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "status", "--porcelain", "--untracked-files=all")
output, err := command.Output()
if err != nil {
return false, fmt.Errorf("inspect build source: %w", err)
}
return len(output) == 0, nil
}

View File

@@ -2,32 +2,59 @@ package build
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate" "go.maximumdirect.net/releasekit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/tempdir"
) )
func CandidateCallback(spec *Spec, output io.Writer) func(context.Context, candidate.Candidate) error { func CandidateCallback(spec *Spec, output io.Writer) func(context.Context, candidate.Candidate, *gotool.Owner) error {
return candidateCallback(spec, output, os.RemoveAll)
}
func candidateCallback(spec *Spec, output io.Writer, remove func(string) error) func(context.Context, candidate.Candidate, *gotool.Owner) error {
if spec == nil || len(spec.Targets) == 0 { if spec == nil || len(spec.Targets) == 0 {
return nil return nil
} }
selected := *spec selected := *spec
selected.Targets = append([]Target(nil), spec.Targets...) selected.Targets = append([]Target(nil), spec.Targets...)
return func(ctx context.Context, captured candidate.Candidate) error { return func(ctx context.Context, captured candidate.Candidate, owner *gotool.Owner) (resultErr error) {
moduleSubdir, err := filepath.Rel(captured.RepositoryDir, captured.ModuleDir)
if err != nil {
return fmt.Errorf("resolve captured module path: %w", err)
}
identity := releaseidentity.Identity{
Selection: releaseidentity.Selection{
RepositoryDir: captured.RepositoryDir,
ModuleDir: captured.ModuleDir,
ModuleSubdir: filepath.ToSlash(moduleSubdir),
},
ModulePath: captured.ModulePath,
Version: captured.Version,
Tag: captured.Tag,
NotePath: filepath.ToSlash(filepath.Join(moduleSubdir, "docs", "releases", captured.Version+".md")),
}
temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-") temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-")
if err != nil { if err != nil {
return fmt.Errorf("create temporary candidate build output: %w", err) return fmt.Errorf("create temporary candidate build output: %w", err)
} }
defer os.RemoveAll(temporaryDir) defer func() {
_, err = Build(ctx, Request{ if err := remove(temporaryDir); err != nil {
RepositoryDir: captured.RepositoryDir, resultErr = errors.Join(resultErr, fmt.Errorf("remove candidate build directory %q: %w", temporaryDir, err))
Version: captured.Version, }
Spec: selected, }()
OutputDir: temporaryDir, _, err = BuildResolved(ctx, Request{
Output: output, Identity: identity,
Spec: selected,
OutputDir: temporaryDir,
Output: output,
ToolOwner: owner,
}) })
if err != nil { if err != nil {
return fmt.Errorf("build candidate: %w", err) return fmt.Errorf("build candidate: %w", err)

View File

@@ -0,0 +1,124 @@
package build
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/candidate"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func cleanupFixture(t *testing.T, output string) releaseidentity.Identity {
t.Helper()
repo := t.TempDir()
files := map[string]string{
"go.mod": "module example.com/cleanup\n\ngo 1.25.0\n",
"main.go": fmt.Sprintf("package main\nimport \"fmt\"\nfunc main() { fmt.Println(%q) }\n", output),
}
for name, contents := range files {
if err := os.WriteFile(filepath.Join(repo, name), []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
for _, args := range [][]string{{"init", "-b", "main"}, {"config", "user.name", "Fixture"}, {"config", "user.email", "fixture@example.invalid"}, {"add", "."}, {"commit", "-m", "fixture"}} {
command := exec.Command("git", args...)
command.Dir = repo
if data, err := command.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v: %s", args, err, data)
}
}
return releaseidentity.Identity{Selection: releaseidentity.Selection{RepositoryDir: repo, ModuleDir: repo}, ModulePath: "example.com/cleanup", Version: "v1.2.3", Tag: "v1.2.3"}
}
type cancelWriter struct{ cancel context.CancelFunc }
func (writer cancelWriter) Write(p []byte) (int, error) {
if strings.Contains(string(p), "checking ") {
writer.cancel()
}
return len(p), nil
}
func TestNativeSmokeCleanupPreservesBuildOutcome(t *testing.T) {
for _, mode := range []string{"success", "smoke error", "cancellation"} {
t.Run(mode, func(t *testing.T) {
output := "fixture v1.2.3"
if mode == "smoke error" {
output = "wrong"
}
identity := cleanupFixture(t, output)
otherArch := "arm64"
if runtime.GOARCH == otherArch {
otherArch = "amd64"
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
request := Request{Identity: identity, OutputDir: t.TempDir(), Spec: Spec{MainPackage: ".", BinaryName: "fixture", Targets: []Target{{OS: runtime.GOOS, Arch: otherArch}}}}
if mode == "cancellation" {
request.Output = cancelWriter{cancel}
}
cleanupErr := errors.New("cleanup failed")
var removed string
result, err := buildResolved(ctx, request, func(path string) error {
removed = path
_ = os.RemoveAll(path)
return cleanupErr
})
if !errors.Is(err, cleanupErr) || removed == "" || !strings.Contains(err.Error(), removed) || len(result.Artifacts) != 1 || result.Artifacts[0].SHA256 == "" || result.CandidateCommit == "" {
t.Fatalf("build = %#v, cleanup = %q, error = %v", result, removed, err)
}
if mode == "success" && !result.SourceVerified {
t.Fatal("completed build lost verified source")
}
if mode == "smoke error" && !strings.Contains(err.Error(), "native version output") {
t.Fatalf("smoke failure missing: %v", err)
}
if mode == "cancellation" && !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation missing: %v", err)
}
})
}
}
func TestCandidateBuildCleanupPreservesOutcome(t *testing.T) {
for _, mode := range []string{"success", "build failure", "cancellation"} {
t.Run(mode, func(t *testing.T) {
identity := cleanupFixture(t, "fixture v1.2.3")
cleanupErr := errors.New("cleanup failed")
var removed string
spec := &Spec{MainPackage: ".", BinaryName: "fixture", Targets: []Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}
if mode == "build failure" {
spec.MainPackage = "./missing"
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
var output io.Writer
if mode == "cancellation" {
output = cancelWriter{cancel}
}
callback := candidateCallback(spec, output, func(path string) error {
removed = path
_ = os.RemoveAll(path)
return cleanupErr
})
err := callback(ctx, candidate.Candidate{RepositoryDir: identity.RepositoryDir, ModuleDir: identity.ModuleDir, ModulePath: identity.ModulePath, Version: identity.Version, Tag: identity.Tag}, nil)
if !errors.Is(err, cleanupErr) || removed == "" || !strings.Contains(err.Error(), removed) {
t.Fatalf("candidate cleanup = %q, error = %v", removed, err)
}
if mode == "build failure" && !strings.Contains(err.Error(), "build candidate") {
t.Fatalf("build failure missing: %v", err)
}
if mode == "cancellation" && !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation missing: %v", err)
}
})
}
}

View File

@@ -8,18 +8,23 @@ import (
"fmt" "fmt"
"io" "io"
"os/exec" "os/exec"
"path/filepath"
"strings" "strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process" "go.maximumdirect.net/releasekit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation" "go.maximumdirect.net/releasekit/internal/gotool"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/process"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/validation"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
var ErrInvalidVersion = errors.New("invalid stable version") var ErrInvalidVersion = errors.New("invalid stable version")
type Candidate struct { type Candidate struct {
RepositoryDir string RepositoryDir string
ModuleDir string
ModulePath string
Tag string
Commit string Commit string
Version string Version string
Note string Note string
@@ -27,29 +32,33 @@ type Candidate struct {
type Request struct { type Request struct {
RepositoryDir string RepositoryDir string
ModuleDir string
Product string Product string
Version string Version string
Validation validation.Settings Validation validation.Settings
AdditionalChecks func(context.Context, Candidate) error AdditionalChecks func(context.Context, Candidate) error
AfterValidate func(context.Context, Candidate) error AfterValidate func(context.Context, Candidate, *gotool.Owner) error
Output io.Writer Output io.Writer
ToolOwner *gotool.Owner
} }
func Check(ctx context.Context, request Request) (Candidate, error) { func Check(ctx context.Context, request Request) (Candidate, error) {
captured, err := Capture(ctx, request) captured, err := Capture(ctx, request)
if err != nil { if err != nil {
return Candidate{}, err return captured, err
} }
request.ToolOwner = gotool.NewOwner(captured.ModuleDir)
if err := Validate(ctx, request, captured); err != nil { if err := Validate(ctx, request, captured); err != nil {
return Candidate{}, err return captured, err
} }
if request.AfterValidate != nil { if request.AfterValidate != nil {
if err := request.AfterValidate(ctx, captured); err != nil { callbackErr := request.AfterValidate(ctx, captured, request.ToolOwner)
return Candidate{}, fmt.Errorf("after candidate validation: %w", err) if callbackErr != nil {
return captured, fmt.Errorf("after candidate validation: %w", callbackErr)
} }
} }
if err := Recheck(ctx, captured, ""); err != nil { if err := Recheck(ctx, captured, ""); err != nil {
return Candidate{}, err return captured, err
} }
return captured, nil return captured, nil
} }
@@ -57,59 +66,79 @@ func Check(ctx context.Context, request Request) (Candidate, error) {
// Capture validates request identity and records one clean local candidate, // Capture validates request identity and records one clean local candidate,
// including the note bytes from the captured commit. It does not run checks. // including the note bytes from the captured commit. It does not run checks.
func Capture(ctx context.Context, request Request) (Candidate, error) { func Capture(ctx context.Context, request Request) (Candidate, error) {
captured := Candidate{Version: request.Version}
if !validStableVersion(request.Version) { if !validStableVersion(request.Version) {
return Candidate{}, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version) return captured, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)
} }
if strings.TrimSpace(request.Product) == "" { if strings.TrimSpace(request.Product) == "" {
return Candidate{}, errors.New("product is required") return captured, errors.New("product is required")
} }
repositoryDir, err := filepath.Abs(request.RepositoryDir) repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
if err != nil { if err != nil {
return Candidate{}, fmt.Errorf("resolve repository directory: %w", err) return captured, fmt.Errorf("resolve repository directory: %w", err)
} }
captured.RepositoryDir = repositoryDir
state, err := inspectLocalState(ctx, repositoryDir) state, err := inspectLocalState(ctx, repositoryDir)
if err != nil { if err != nil {
return Candidate{}, err return captured, err
} }
captured.Commit = state.commit
if state.branch != "main" { if state.branch != "main" {
return Candidate{}, fmt.Errorf("release candidate must be on main; current branch is %q", state.branch) return captured, fmt.Errorf("release candidate must be on main; current branch is %q", state.branch)
} }
if state.status != "" { if state.status != "" {
return Candidate{}, fmt.Errorf("release candidate worktree and index must be clean:\n%s", state.status) return captured, fmt.Errorf("release candidate worktree and index must be clean:\n%s", state.status)
} }
path := "docs/releases/" + request.Version + ".md" identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit)
note, err := gitOutput(ctx, repositoryDir, "show", state.commit+":"+path) captured.ModuleDir = identity.ModuleDir
captured.ModulePath = identity.ModulePath
captured.Tag = identity.Tag
if err != nil { if err != nil {
return Candidate{}, fmt.Errorf("read committed release note %q: %w", path, err) return captured, fmt.Errorf("resolve selected module release identity: %w", err)
}
note, err := git.ReadCommitFile(ctx, identity.RepositoryDir, state.commit, identity.NotePath)
if err != nil {
return captured, fmt.Errorf("read committed release note %q: %w", identity.NotePath, err)
} }
if err := validateNote(note, request.Product, request.Version); err != nil { if err := validateNote(note, request.Product, request.Version); err != nil {
return Candidate{}, fmt.Errorf("release note %q: %w", path, err) return captured, fmt.Errorf("release note %q: %w", identity.NotePath, err)
} }
if exists, err := hasLocalTag(ctx, repositoryDir, request.Version); err != nil { if err := git.CheckTagRef(ctx, repositoryDir, identity.Tag); err != nil {
return Candidate{}, fmt.Errorf("inspect local tag %q: %w", request.Version, err) return captured, fmt.Errorf("validate local candidate tag: %w", err)
}
if exists, err := hasLocalTag(ctx, repositoryDir, identity.Tag); err != nil {
return captured, fmt.Errorf("inspect local tag %q: %w", identity.Tag, err)
} else if exists { } else if exists {
return Candidate{}, fmt.Errorf("local tag %q already exists", request.Version) return captured, fmt.Errorf("local tag %q already exists", identity.Tag)
} }
return Candidate{RepositoryDir: repositoryDir, Commit: state.commit, Version: request.Version, Note: string(note)}, nil captured.Note = string(note)
return captured, nil
} }
// Validate runs the selected offline Go suite, followed by AdditionalChecks // Validate runs the selected offline Go suite, followed by AdditionalChecks
// when supplied, for the captured candidate. // when supplied, for the captured candidate.
func Validate(ctx context.Context, request Request, captured Candidate) error { func Validate(ctx context.Context, request Request, captured Candidate) error {
owner := request.ToolOwner
if owner == nil {
owner = gotool.NewOwner(captured.ModuleDir)
}
if err := validation.Run(ctx, validation.Request{ if err := validation.Run(ctx, validation.Request{
RepositoryDir: captured.RepositoryDir, RepositoryDir: captured.RepositoryDir,
ModuleDir: captured.ModuleDir,
Commit: captured.Commit, Commit: captured.Commit,
Output: request.Output, Output: request.Output,
Settings: request.Validation, Settings: request.Validation,
ToolOwner: owner,
}); err != nil { }); err != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err) return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
} }
if request.AdditionalChecks != nil { if request.AdditionalChecks != nil {
if err := request.AdditionalChecks(ctx, captured); err != nil { callbackErr := request.AdditionalChecks(ctx, captured)
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err) if callbackErr != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, callbackErr)
} }
} }
return nil return nil
@@ -133,23 +162,23 @@ func Recheck(ctx context.Context, captured Candidate, expectedTagObject string)
return fmt.Errorf("worktree or index changed:\n%s", current.status) return fmt.Errorf("worktree or index changed:\n%s", current.status)
} }
if expectedTagObject == "" { if expectedTagObject == "" {
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Version); err != nil { if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Tag); err != nil {
return fmt.Errorf("recheck local tag %q: %w", captured.Version, err) return fmt.Errorf("recheck local tag %q: %w", captured.Tag, err)
} else if exists { } else if exists {
return fmt.Errorf("local tag %q appeared during validation", captured.Version) return fmt.Errorf("local tag %q appeared during validation", captured.Tag)
} }
return nil return nil
} }
object, err := gitOutput(ctx, captured.RepositoryDir, "rev-parse", "--verify", "refs/tags/"+captured.Version) object, err := gitOutput(ctx, captured.RepositoryDir, "rev-parse", "--verify", "refs/tags/"+captured.Tag)
if err != nil { if err != nil {
return fmt.Errorf("read local tag %q: %w", captured.Version, err) return fmt.Errorf("read local tag %q: %w", captured.Tag, err)
} }
tagType, err := gitOutput(ctx, captured.RepositoryDir, "cat-file", "-t", "refs/tags/"+captured.Version) tagType, err := gitOutput(ctx, captured.RepositoryDir, "cat-file", "-t", "refs/tags/"+captured.Tag)
if err != nil { if err != nil {
return fmt.Errorf("inspect local tag %q: %w", captured.Version, err) return fmt.Errorf("inspect local tag %q: %w", captured.Tag, err)
} }
if strings.TrimSpace(string(object)) != expectedTagObject || strings.TrimSpace(string(tagType)) != "tag" { if strings.TrimSpace(string(object)) != expectedTagObject || strings.TrimSpace(string(tagType)) != "tag" {
return fmt.Errorf("local tag %q no longer identifies annotated tag object %s", captured.Version, expectedTagObject) return fmt.Errorf("local tag %q no longer identifies annotated tag object %s", captured.Tag, expectedTagObject)
} }
return nil return nil
} }
@@ -165,18 +194,18 @@ func inspectLocalState(ctx context.Context, repositoryDir string) (localState, e
if err != nil { if err != nil {
return localState{}, fmt.Errorf("inspect current branch: %w", err) return localState{}, fmt.Errorf("inspect current branch: %w", err)
} }
commitOutput, err := gitOutput(ctx, repositoryDir, "rev-parse", "--verify", "HEAD^{commit}") commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil { if err != nil {
return localState{}, fmt.Errorf("capture HEAD commit: %w", err) return localState{}, fmt.Errorf("capture HEAD commit: %w", err)
} }
statusOutput, err := gitOutput(ctx, repositoryDir, "status", "--porcelain=v1", "--untracked-files=all") status, err := git.WorktreeStatus(ctx, repositoryDir)
if err != nil { if err != nil {
return localState{}, fmt.Errorf("inspect worktree and index: %w", err) return localState{}, fmt.Errorf("inspect worktree and index: %w", err)
} }
return localState{ return localState{
branch: strings.TrimSpace(string(branchOutput)), branch: strings.TrimSpace(string(branchOutput)),
commit: strings.TrimSpace(string(commitOutput)), commit: commit,
status: strings.TrimSpace(string(statusOutput)), status: status,
}, nil }, nil
} }
@@ -186,6 +215,7 @@ func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byt
err := process.Run(ctx, process.Invocation{ err := process.Run(ctx, process.Invocation{
Args: commandArgs, Args: commandArgs,
Dir: repositoryDir, Dir: repositoryDir,
Env: map[string]string{"GIT_NO_REPLACE_OBJECTS": "1"},
Stdout: &stdout, Stdout: &stdout,
Stderr: &stderr, Stderr: &stderr,
}) })
@@ -199,11 +229,12 @@ func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byt
return stdout.Bytes(), nil return stdout.Bytes(), nil
} }
func hasLocalTag(ctx context.Context, repositoryDir, version string) (bool, error) { func hasLocalTag(ctx context.Context, repositoryDir, tag string) (bool, error) {
var stderr bytes.Buffer var stderr bytes.Buffer
err := process.Run(ctx, process.Invocation{ err := process.Run(ctx, process.Invocation{
Args: []string{"git", "show-ref", "--verify", "--quiet", "refs/tags/" + version}, Args: []string{"git", "show-ref", "--verify", "--quiet", "refs/tags/" + tag},
Dir: repositoryDir, Dir: repositoryDir,
Env: map[string]string{"GIT_NO_REPLACE_OBJECTS": "1"},
Stderr: &stderr, Stderr: &stderr,
}) })
if err == nil { if err == nil {

View File

@@ -3,14 +3,18 @@ package candidate
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json"
"errors" "errors"
"fmt"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/validation"
) )
const testVersion = "v1.2.3" const testVersion = "v1.2.3"
@@ -71,7 +75,7 @@ func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
if seen != candidate { if seen != candidate {
t.Fatalf("callback candidate = %#v, returned candidate = %#v", seen, candidate) t.Fatalf("callback candidate = %#v, returned candidate = %#v", seen, candidate)
} }
if candidate.RepositoryDir != repository || candidate.Commit != commit || candidate.Version != testVersion { if candidate.RepositoryDir != repository || candidate.ModuleDir != repository || candidate.ModulePath != "example.com/candidate" || candidate.Tag != testVersion || candidate.Commit != commit || candidate.Version != testVersion {
t.Fatalf("Check() candidate = %#v", candidate) t.Fatalf("Check() candidate = %#v", candidate)
} }
if tags := gitOutputForTest(t, repository, "tag", "--list"); tags != "" { if tags := gitOutputForTest(t, repository, "tag", "--list"); tags != "" {
@@ -82,6 +86,67 @@ func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
} }
} }
func TestCaptureUsesNestedMajorModuleNoteAndTag(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRoot release.\n")
moduleDir := "integrations/ckconfig/v2"
writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/ckconfig/v2\n\ngo 1.25.0\n")
writeTestFile(t, repository, moduleDir+"/docs/releases/v2.3.4.md", "# Example Product v2.3.4\n\nNested release.\n")
gitRun(t, repository, "add", moduleDir)
gitRun(t, repository, "commit", "-m", "add nested major module")
captured, err := Capture(context.Background(), Request{
RepositoryDir: repository,
ModuleDir: moduleDir,
Product: "Example Product",
Version: "v2.3.4",
})
if err != nil {
t.Fatal(err)
}
if captured.RepositoryDir != repository || captured.ModuleDir != filepath.Join(repository, moduleDir) || captured.ModulePath != "example.com/ckconfig/v2" || captured.Tag != "integrations/ckconfig/v2.3.4" {
t.Fatalf("nested candidate identity = %#v", captured)
}
if !strings.Contains(captured.Note, "Nested release.") || strings.Contains(captured.Note, "Root release.") {
t.Fatalf("captured note = %q, want nested module note", captured.Note)
}
gitRun(t, repository, "tag", captured.Tag)
conflicted, err := Capture(context.Background(), Request{
RepositoryDir: repository,
ModuleDir: moduleDir,
Product: "Example Product",
Version: "v2.3.4",
})
if err == nil || !strings.Contains(err.Error(), captured.Tag) {
t.Fatalf("Capture() with existing nested tag returned %#v, %v", conflicted, err)
}
if conflicted.ModulePath != captured.ModulePath || conflicted.Tag != captured.Tag || conflicted.Commit != captured.Commit {
t.Fatalf("capture failure lost identity evidence: %#v", conflicted)
}
}
func TestCaptureKeepsRepositoryWideCleanlinessGuardForNestedSelection(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n")
moduleDir := "integrations/ckconfig"
writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/ckconfig\n")
writeTestFile(t, repository, moduleDir+"/docs/releases/"+testVersion+".md", "# Example Product v1.2.3\n")
gitRun(t, repository, "add", moduleDir)
gitRun(t, repository, "commit", "-m", "add nested module")
writeTestFile(t, repository, "sibling/untracked.txt", "dirty\n")
captured, err := Capture(context.Background(), Request{
RepositoryDir: repository,
ModuleDir: moduleDir,
Product: "Example Product",
Version: testVersion,
})
if err == nil || !strings.Contains(err.Error(), "must be clean") {
t.Fatalf("Capture() = %#v, %v; want repository-wide dirty-state rejection", captured, err)
}
if captured.Commit == "" {
t.Fatalf("dirty-state error lost captured commit: %#v", captured)
}
}
func TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T) { func TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n") repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
writeTestFile(t, repository, "unformatted.go", "package candidate\nfunc Value( ) int{return 1}\n") writeTestFile(t, repository, "unformatted.go", "package candidate\nfunc Value( ) int{return 1}\n")
@@ -98,7 +163,7 @@ func TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T)
productCalls++ productCalls++
return nil return nil
}, },
AfterValidate: func(context.Context, Candidate) error { AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
buildCalls++ buildCalls++
return nil return nil
}, },
@@ -130,7 +195,7 @@ func TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails(t *te
productCalls++ productCalls++
return nil return nil
}, },
AfterValidate: func(context.Context, Candidate) error { AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
buildCalls++ buildCalls++
return nil return nil
}, },
@@ -204,6 +269,147 @@ func TestCheckRunsDefaultOfflineGoValidation(t *testing.T) {
} }
} }
func TestCheckRefreshesGoSettingsAfterAdditionalChecks(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
t.Setenv("GOENV", "off")
t.Setenv("GOMODCACHE", filepath.Join(t.TempDir(), "initial-module-cache"))
selectedCache := filepath.Join(t.TempDir(), "callback-module-cache")
var observed string
_, err := Check(context.Background(), Request{
RepositoryDir: repository,
Product: "Example Product",
Version: testVersion,
AdditionalChecks: func(context.Context, Candidate) error {
t.Setenv("GOMODCACHE", selectedCache)
return nil
},
AfterValidate: func(ctx context.Context, captured Candidate, owner *gotool.Owner) error {
tool, err := owner.Acquire(ctx)
if err != nil {
return err
}
output, err := tool.Output(ctx, captured.ModuleDir, gotool.Native, gotool.Target{}, nil, "env", "GOMODCACHE")
if err != nil {
return err
}
observed = strings.TrimSpace(string(output))
return nil
},
})
if err != nil {
t.Fatal(err)
}
if observed != selectedCache {
t.Fatalf("Go settings after additional checks = %q, want %q", observed, selectedCache)
}
}
func TestCheckNeedsNoGoDiscoveryAfterFinalCallback(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
gitPath, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
gitOnly := t.TempDir()
if err := os.Symlink(gitPath, filepath.Join(gitOnly, "git")); err != nil {
t.Fatal(err)
}
_, err = Check(context.Background(), Request{
RepositoryDir: repository, Product: "Example Product", Version: testVersion,
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
t.Setenv("PATH", gitOnly)
return nil
},
})
if err != nil {
t.Fatalf("completed Go work was rediscovered after final callback: %v", err)
}
}
func TestCheckSharesGoDiscoveryWithAfterValidateCallback(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the controlled Go command fixture uses a POSIX shell")
}
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
logPath := installCandidateGoShim(t)
t.Setenv("GOENV", "off")
_, err := Check(context.Background(), Request{
RepositoryDir: repository,
Product: "Example Product",
Version: testVersion,
AfterValidate: func(ctx context.Context, captured Candidate, owner *gotool.Owner) error {
tool, err := owner.Acquire(ctx)
if err != nil {
return err
}
_, err = tool.Output(ctx, captured.ModuleDir, gotool.Native, gotool.Target{}, nil, "version")
return err
},
})
if err != nil {
t.Fatal(err)
}
contents, err := os.ReadFile(logPath)
if err != nil {
t.Fatal(err)
}
commands := strings.Split(strings.TrimSpace(string(contents)), "\n")
var discoveries, suites, callbacks int
for _, command := range commands {
switch {
case strings.HasPrefix(command, "env "):
discoveries++
case strings.HasPrefix(command, "test "):
suites++
case command == "version":
callbacks++
}
}
if discoveries != 2 || suites != 1 || callbacks != 1 {
t.Fatalf("Go invocations = %q; discovery=%d suite=%d callback=%d, want 2, 1, 1", commands, discoveries, suites, callbacks)
}
}
func installCandidateGoShim(t *testing.T) string {
t.Helper()
directory := t.TempDir()
logPath := filepath.Join(directory, "go-commands")
settings := map[string]string{
"GOHOSTOS": runtime.GOOS, "GOHOSTARCH": runtime.GOARCH, "GOENV": "off",
"CC": "", "CXX": "", "CGO_CFLAGS": "", "CGO_CPPFLAGS": "", "CGO_CXXFLAGS": "",
"CGO_ENABLED": "1", "CGO_LDFLAGS": "", "GOCACHE": "", "GOCACHEPROG": "",
"GOMODCACHE": "", "GOPATH": "", "GOROOT": "", "GOTMPDIR": "", "PKG_CONFIG": "",
}
encoded, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
script := fmt.Sprintf(`#!/bin/sh
set -eu
printf '%%s\n' "$*" >> "$RELEASEKIT_GO_LOG"
if [ "${1-}" = "env" ]; then
printf '%%s\n' '%s'
exit 0
fi
if [ "${1-}" = "version" ]; then
echo 'go version fixture'
exit 0
fi
exit 0
`, encoded)
shimPath := filepath.Join(directory, "go")
if err := os.WriteFile(shimPath, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
path := directory
if current := os.Getenv("PATH"); current != "" {
path += string(os.PathListSeparator) + current
}
t.Setenv("PATH", path)
t.Setenv("RELEASEKIT_GO_LOG", logPath)
return logPath
}
func TestDefaultValidationDoesNotInheritGOFLAGSRunFilter(t *testing.T) { func TestDefaultValidationDoesNotInheritGOFLAGSRunFilter(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n") repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
writeTestFile(t, repository, "failure_test.go", "package candidate\nimport \"testing\"\nfunc TestExpectedFailure(t *testing.T) { t.Fatal(\"expected fixture failure\") }\n") writeTestFile(t, repository, "failure_test.go", "package candidate\nimport \"testing\"\nfunc TestExpectedFailure(t *testing.T) { t.Fatal(\"expected fixture failure\") }\n")
@@ -423,7 +629,7 @@ func TestCheckRechecksHeadAndWorktreeAfterCallback(t *testing.T) {
func TestCheckRechecksLocalTagAfterCallback(t *testing.T) { func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n") repository := newRepository(t, "# Example Product v1.2.3\n")
_, err := Check(context.Background(), Request{ captured, err := Check(context.Background(), Request{
RepositoryDir: repository, RepositoryDir: repository,
Product: "Example Product", Product: "Example Product",
Version: testVersion, Version: testVersion,
@@ -435,6 +641,9 @@ func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "appeared during validation") { if err == nil || !strings.Contains(err.Error(), "appeared during validation") {
t.Fatalf("Check() error = %v, want tag recheck error", err) t.Fatalf("Check() error = %v, want tag recheck error", err)
} }
if captured.RepositoryDir != repository || captured.ModuleDir != repository || captured.ModulePath != "example.com/candidate" || captured.Tag != testVersion || captured.Commit == "" {
t.Fatalf("tag recheck failure lost candidate evidence: %#v", captured)
}
} }
func validRequest(repository string) Request { func validRequest(repository string) Request {

View File

@@ -1,82 +1,49 @@
package delivery package delivery
import ( import (
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"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/gitea"
) )
func declaredBuildAssets(result internalbuild.Result) ([]gitea.ExpectedAsset, error) { func declaredBuildAssets(result internalbuild.Result) ([]artifact.ExpectedAsset, error) {
if len(result.Targets) == 0 { settings := result.Settings
if len(settings.Targets) == 0 {
if len(result.Artifacts) != 0 { if len(result.Artifacts) != 0 {
return nil, fmt.Errorf("source-only build result contains artifacts") return nil, fmt.Errorf("source-only build result contains artifacts")
} }
return nil, nil return nil, nil
} }
if len(result.Artifacts) != len(result.Targets) { declarations := make([]artifact.Declaration, 0, len(result.Artifacts))
return nil, fmt.Errorf("build result must contain one artifact for each selected target") for _, built := range result.Artifacts {
declarations = append(declarations, artifact.Declaration{Target: built.Target, Filename: built.Filename})
} }
declarations := artifact.ExpectedBuild(result.BinaryName, result.Version, result.Targets) if err := artifact.ValidateDeclarations(settings.BinaryName, result.Version, settings.Targets, declarations); err != nil {
wantByTarget := make(map[artifact.Target]string, len(declarations)) return nil, fmt.Errorf("build result: %w", err)
for _, declaration := range declarations {
target := declaration.Target
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
return nil, fmt.Errorf("build result contains an invalid target")
}
if _, exists := wantByTarget[target]; exists {
return nil, fmt.Errorf("build result repeats target %q", target.OS+"/"+target.Arch)
}
wantByTarget[target] = declaration.Filename
} }
assets := make([]gitea.ExpectedAsset, 0, len(result.Artifacts)+1) assets := make([]artifact.ExpectedAsset, 0, len(result.Artifacts)+1)
seenTargets := make(map[artifact.Target]bool, len(result.Artifacts)) for _, builtArtifact := range result.Artifacts {
for _, artifact := range result.Artifacts { if filepath.Base(builtArtifact.Path) != builtArtifact.Filename {
wantName, ok := wantByTarget[artifact.Target] return nil, fmt.Errorf("build artifact path %q does not end with filename %q", builtArtifact.Path, builtArtifact.Filename)
if !ok || seenTargets[artifact.Target] || artifact.Filename != wantName {
return nil, fmt.Errorf("build artifact %q does not match a selected target and its declared name", artifact.Filename)
} }
seenTargets[artifact.Target] = true info, err := os.Stat(builtArtifact.Path)
if filepath.Base(artifact.Path) != artifact.Filename {
return nil, fmt.Errorf("build artifact path %q does not end with filename %q", artifact.Path, artifact.Filename)
}
info, err := os.Stat(artifact.Path)
if err != nil { if err != nil {
return nil, fmt.Errorf("inspect build artifact %q: %w", artifact.Filename, err) return nil, fmt.Errorf("inspect build artifact %q: %w", builtArtifact.Filename, err)
} }
if !info.Mode().IsRegular() { if !info.Mode().IsRegular() {
return nil, fmt.Errorf("build artifact %q is not a regular file", artifact.Filename) return nil, fmt.Errorf("build artifact %q is not a regular file", builtArtifact.Filename)
} }
file, err := os.Open(artifact.Path) assets = append(assets, artifact.ExpectedAsset{
if err != nil { Filename: builtArtifact.Filename,
return nil, fmt.Errorf("open build artifact %q: %w", artifact.Filename, err) SHA256: builtArtifact.SHA256,
}
hash := sha256.New()
_, copyErr := io.Copy(hash, file)
closeErr := file.Close()
if copyErr != nil {
return nil, fmt.Errorf("hash build artifact %q: %w", artifact.Filename, copyErr)
}
if closeErr != nil {
return nil, fmt.Errorf("close build artifact %q: %w", artifact.Filename, closeErr)
}
if artifact.SHA256 != hex.EncodeToString(hash.Sum(nil)) {
return nil, fmt.Errorf("build artifact %q does not match its declared SHA-256 digest", artifact.Filename)
}
assets = append(assets, gitea.ExpectedAsset{
Filename: artifact.Filename,
SHA256: artifact.SHA256,
Size: info.Size(), Size: info.Size(),
Path: artifact.Path, Path: builtArtifact.Path,
}) })
} }
manifest, err := gitea.BuildManifest(assets) manifest, err := artifact.BuildManifest(assets)
if err != nil { if err != nil {
return nil, fmt.Errorf("build checksum manifest: %w", err) return nil, fmt.Errorf("build checksum manifest: %w", err)
} }

View File

@@ -8,8 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" "go.maximumdirect.net/releasekit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea" internalbuild "go.maximumdirect.net/releasekit/internal/build"
) )
func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) { func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
@@ -25,8 +25,10 @@ func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
result, err := declaredBuildAssets(internalbuild.Result{ result, err := declaredBuildAssets(internalbuild.Result{
Version: "v1.2.3", BinaryName: "app", Version: "v1.2.3",
Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"}}, Settings: artifact.NormalizeSettings("./cmd/app", "app", []artifact.Target{
{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"},
}),
Artifacts: []internalbuild.Artifact{ Artifacts: []internalbuild.Artifact{
{Path: firstPath, Filename: filepath.Base(firstPath), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(first)}, {Path: firstPath, Filename: filepath.Base(firstPath), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(first)},
{Path: secondPath, Filename: filepath.Base(secondPath), Target: internalbuild.Target{OS: "darwin", Arch: "arm64"}, SHA256: assetDigest(second)}, {Path: secondPath, Filename: filepath.Base(secondPath), Target: internalbuild.Target{OS: "darwin", Arch: "arm64"}, SHA256: assetDigest(second)},
@@ -35,7 +37,7 @@ func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if len(result) != 3 || result[0].Filename != filepath.Base(firstPath) || result[1].Filename != filepath.Base(secondPath) || result[2].Filename != gitea.ManifestFilename { if len(result) != 3 || result[0].Filename != filepath.Base(firstPath) || result[1].Filename != filepath.Base(secondPath) || result[2].Filename != artifact.ManifestFilename {
t.Fatalf("assets = %#v", result) t.Fatalf("assets = %#v", result)
} }
want := assetDigest(second) + " app-v1.2.3-darwin-arm64\n" + assetDigest(first) + " app-v1.2.3-linux-amd64\n" want := assetDigest(second) + " app-v1.2.3-darwin-arm64\n" + assetDigest(first) + " app-v1.2.3-linux-amd64\n"
@@ -47,20 +49,6 @@ func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
} }
} }
func TestDeclaredBuildAssetsRejectsTamperedArtifact(t *testing.T) {
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-amd64")
if err := os.WriteFile(path, []byte("changed bytes"), 0o600); err != nil {
t.Fatal(err)
}
_, err := declaredBuildAssets(internalbuild.Result{
Version: "v1.2.3", BinaryName: "app", Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}},
Artifacts: []internalbuild.Artifact{{Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest([]byte("original bytes"))}},
})
if err == nil || !strings.Contains(err.Error(), "SHA-256") {
t.Fatalf("declaredBuildAssets() error = %v, want digest mismatch", err)
}
}
func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) { func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) {
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-arm64") path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-arm64")
contents := []byte("built application") contents := []byte("built application")
@@ -68,7 +56,7 @@ func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
_, err := declaredBuildAssets(internalbuild.Result{ _, err := declaredBuildAssets(internalbuild.Result{
Version: "v1.2.3", BinaryName: "app", Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}}, Version: "v1.2.3", Settings: artifact.NormalizeSettings("./cmd/app", "app", []artifact.Target{{OS: "linux", Arch: "amd64"}}),
Artifacts: []internalbuild.Artifact{{ Artifacts: []internalbuild.Artifact{{
Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(contents), Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(contents),
}}, }},

View File

@@ -0,0 +1,102 @@
package delivery
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
"go.maximumdirect.net/releasekit/internal/forge"
)
func deliveryCleanupFixture(t *testing.T) (string, string) {
t.Helper()
repo := t.TempDir()
files := map[string]string{
"go.mod": "module example.com/delivery\n\ngo 1.25.0\n",
"main.go": "package main\nimport \"fmt\"\nfunc main() { fmt.Println(\"fixture v1.2.3\") }\n",
"docs/releases/v1.2.3.md": "# Fixture v1.2.3\n\nNote.\n",
}
for name, contents := range files {
path := filepath.Join(repo, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
for _, args := range [][]string{{"init", "-b", "main"}, {"config", "user.name", "Fixture"}, {"config", "user.email", "fixture@example.invalid"}, {"add", "."}, {"commit", "-m", "fixture"}, {"tag", "v1.2.3"}} {
command := exec.Command("git", args...)
command.Dir = repo
if data, err := command.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v: %s", args, err, data)
}
}
command := exec.Command("git", "rev-parse", "HEAD")
command.Dir = repo
commit, err := command.Output()
if err != nil {
t.Fatal(err)
}
return repo, strings.TrimSpace(string(commit))
}
type cancelBuildOutput struct{ cancel context.CancelFunc }
func (writer cancelBuildOutput) Write(p []byte) (int, error) {
if strings.Contains(string(p), "building ") {
writer.cancel()
}
return len(p), nil
}
func TestManagedDeliveryCleanupPreservesOutcome(t *testing.T) {
for _, mode := range []string{"complete", "build failure", "cancellation"} {
t.Run(mode, func(t *testing.T) {
repo, commit := deliveryCleanupFixture(t)
note := "# Fixture v1.2.3\n\nNote.\n"
backend := &assetBackend{pageBackend: pageBackend{commit: commit, findResults: []pageFindResult{{release: forge.Release{Tag: "v1.2.3", Body: note, Handle: "release", URL: "https://example.invalid/release"}}}}, lists: []assetListResult{{}}}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
spec := internalbuild.Spec{MainPackage: ".", BinaryName: "fixture", Targets: []artifact.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}
if mode == "build failure" {
spec.MainPackage = "./missing"
}
request := Request{RepositoryDir: repo, Product: "Fixture", Version: "v1.2.3", Backend: backend, Build: &spec}
if mode == "cancellation" {
request.Output = cancelBuildOutput{cancel}
}
cleanupErr := errors.New("cleanup failed")
var removed string
result, err := deliver(ctx, request, func(path string) error {
removed = path
_ = os.RemoveAll(path)
return cleanupErr
})
if !errors.Is(err, cleanupErr) || removed == "" || !strings.Contains(err.Error(), removed) || result.CandidateCommit != commit {
t.Fatalf("delivery = %#v, cleanup = %q, error = %v", result, removed, err)
}
switch mode {
case "complete":
if result.State != Complete || len(result.Uploaded) != 2 || result.ReleaseURL == "" {
t.Fatalf("completed delivery lost observations: %#v", result)
}
case "build failure":
if result.State != NotAttempted || !strings.Contains(err.Error(), "build delivery assets") {
t.Fatalf("build failure lost: %#v, %v", result, err)
}
case "cancellation":
if result.State != NotAttempted || !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation lost: %#v, %v", result, err)
}
}
})
}
}

View File

@@ -9,12 +9,15 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build" "go.maximumdirect.net/releasekit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate" internalbuild "go.maximumdirect.net/releasekit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git" "go.maximumdirect.net/releasekit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea" "go.maximumdirect.net/releasekit/internal/forge"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir" "go.maximumdirect.net/releasekit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/tempdir"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
type State string type State string
@@ -29,27 +32,37 @@ const (
type Request struct { type Request struct {
RepositoryDir string RepositoryDir string
ModuleDir string
Product string Product string
Version string Version string
Destination gitea.Destination ExpectedTag string
Backend forge.Backend
Build *internalbuild.Spec Build *internalbuild.Spec
Prebuilt *internalbuild.Result Prebuilt *internalbuild.Result
Output io.Writer Output io.Writer
} }
type Result struct { type Result struct {
RepositoryDir string
ModuleDir string
ModulePath string
Tag string
CandidateCommit string CandidateCommit string
ReleaseURL string ReleaseURL string
State State State State
Matching []gitea.AssetIdentity Matching []AssetIdentity
Uploaded []gitea.AssetIdentity Uploaded []AssetIdentity
Pending []gitea.AssetIdentity Pending []AssetIdentity
Conflicting []gitea.AssetIdentity Conflicting []AssetIdentity
Uncertain []gitea.AssetIdentity Uncertain []AssetIdentity
} }
func Deliver(ctx context.Context, request Request) (Result, error) { func Deliver(ctx context.Context, request Request) (Result, error) {
result := Result{State: NotAttempted} return deliver(ctx, request, os.RemoveAll)
}
func deliver(ctx context.Context, request Request, remove func(string) error) (result Result, resultErr error) {
result = Result{State: NotAttempted}
if !versioncontract.ValidStableVersion(request.Version) { if !versioncontract.ValidStableVersion(request.Version) {
return result, candidate.ErrInvalidVersion return result, candidate.ErrInvalidVersion
} }
@@ -59,28 +72,60 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
if request.Build != nil && request.Prebuilt != nil { if request.Build != nil && request.Prebuilt != nil {
return result, errors.New("delivery cannot use both a managed build and prebuilt artifacts") return result, errors.New("delivery cannot use both a managed build and prebuilt artifacts")
} }
repositoryDir, err := filepath.Abs(request.RepositoryDir) if request.Backend == nil {
return result, errors.New("delivery backend is required")
}
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
if err != nil { if err != nil {
return result, fmt.Errorf("resolve repository directory: %w", err) return result, fmt.Errorf("resolve repository directory: %w", err)
} }
source, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version) result.RepositoryDir = repositoryDir
if err != nil { commit, err := git.CaptureHead(ctx, repositoryDir)
return result, fmt.Errorf("inspect tagged source: %w", err)
}
result.CandidateCommit = source.TagCommit
if source.Status != "" {
return result, fmt.Errorf("tagged checkout must be clean:\n%s", source.Status)
}
if source.Head != source.TagCommit {
return result, fmt.Errorf("checkout HEAD %s does not match tag %s commit %s", source.Head, request.Version, source.TagCommit)
}
notePath := "docs/releases/" + request.Version + ".md"
note, err := git.ReadCommitFile(ctx, repositoryDir, source.TagCommit, notePath)
if err != nil { if err != nil {
return result, err return result, err
} }
result.CandidateCommit = commit
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, commit)
result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath
result.Tag = identity.Tag
if err != nil {
return result, fmt.Errorf("resolve committed delivery identity: %w", err)
}
result.RepositoryDir = identity.RepositoryDir
result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath
result.Tag = identity.Tag
if request.ExpectedTag != "" && request.ExpectedTag != identity.Tag {
return result, fmt.Errorf("expected delivery tag %q does not match selected module tag %q", request.ExpectedTag, identity.Tag)
}
source, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
if err != nil {
return result, fmt.Errorf("inspect tagged source: %w", err)
}
if source.Status != "" {
return result, fmt.Errorf("tagged checkout must be clean:\n%s", source.Status)
}
if source.Head != commit {
return result, fmt.Errorf("checkout HEAD changed from captured commit %s to %s", commit, source.Head)
}
if source.TagCommit != commit {
return result, fmt.Errorf("checkout HEAD %s does not match tag %s commit %s", source.Head, identity.Tag, source.TagCommit)
}
note, err := git.ReadCommitFile(ctx, repositoryDir, commit, identity.NotePath)
if err != nil {
return result, fmt.Errorf("read release note %q: %w", identity.NotePath, err)
}
if err := candidate.ValidateReleaseNote(note, request.Product, request.Version); err != nil { if err := candidate.ValidateReleaseNote(note, request.Product, request.Version); err != nil {
return result, fmt.Errorf("release note %q: %w", notePath, err) return result, fmt.Errorf("release note %q: %w", identity.NotePath, err)
}
if request.Prebuilt != nil {
if err := validateBuildIdentity(identity, commit, request.Prebuilt); err != nil {
return result, err
}
}
if err := request.Backend.Preflight(ctx); err != nil {
return result, err
} }
build := request.Prebuilt build := request.Prebuilt
@@ -89,120 +134,140 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
if err != nil { if err != nil {
return result, fmt.Errorf("create temporary delivery build directory: %w", err) return result, fmt.Errorf("create temporary delivery build directory: %w", err)
} }
defer os.RemoveAll(temporaryDir) defer func() {
built, err := internalbuild.Build(ctx, internalbuild.Request{ if err := remove(temporaryDir); err != nil {
RepositoryDir: repositoryDir, resultErr = errors.Join(resultErr, fmt.Errorf("remove delivery build directory %q: %w", temporaryDir, err))
Version: request.Version, }
Spec: *request.Build, }()
OutputDir: filepath.Join(temporaryDir, "assets"), built, err := internalbuild.BuildResolved(ctx, internalbuild.Request{
Output: request.Output, Identity: identity,
Spec: *request.Build,
OutputDir: filepath.Join(temporaryDir, "assets"),
Output: request.Output,
ToolOwner: gotool.NewOwner(identity.ModuleDir),
}) })
if err != nil { if err != nil {
return result, fmt.Errorf("build delivery assets: %w", err) return result, fmt.Errorf("build delivery assets: %w", err)
} }
build = &built build = &built
} }
var assets []gitea.ExpectedAsset var assets []artifact.ExpectedAsset
if build != nil { if build != nil {
assets, err = declaredBuildAssets(*build) assets, err = declaredBuildAssets(*build)
if err != nil { if err != nil {
return result, err return result, err
} }
} }
if err := validateBuild(repositoryDir, source.TagCommit, request.Version, build, assets); err != nil { if err := validateBuild(identity, commit, build, assets); err != nil {
return result, err return result, err
} }
if len(assets) > 0 { if len(assets) > 0 {
if err := gitea.VerifyLocalAssets(assets); err != nil { if err := artifact.VerifyLocalAssets(assets); err != nil {
return result, fmt.Errorf("verify build assets: %w", err) kind := forge.FailureInvalid
if errors.Is(err, artifact.ErrAssetConflict) {
kind = forge.FailureConflict
}
return result, &forge.Failure{Kind: kind, Err: fmt.Errorf("verify build assets: %w", err)}
} }
} }
if build != nil && len(build.Targets) != 0 { if build != nil && len(build.Settings.Targets) != 0 {
current, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version) current, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
if err != nil { if err != nil {
return result, fmt.Errorf("recheck tagged source after build: %w", err) return result, fmt.Errorf("recheck tagged source after build: %w", err)
} }
if current.Status != "" { if current.Status != "" {
return result, fmt.Errorf("tagged checkout changed during build:\n%s", current.Status) return result, fmt.Errorf("tagged checkout changed during build:\n%s", current.Status)
} }
if current.Head != source.TagCommit || current.TagCommit != source.TagCommit { if current.Head != commit || current.TagCommit != commit {
return result, errors.New("tagged source changed during build") return result, errors.New("tagged source changed during build")
} }
} }
releaseResult, err := (gitea.Client{}).EnsureRelease(ctx, gitea.Request{ release, pageEvidence, err := coordinateRelease(ctx, request.Backend, identity.Tag, commit, string(note))
Destination: request.Destination,
Version: request.Version,
Commit: source.TagCommit,
Note: string(note),
})
if err != nil { if err != nil {
result.State = stateForError(err, false) result.State = stateForError(err, false)
return result, err return result, err
} }
result.ReleaseURL = releaseResult.Release.URL result.ReleaseURL = release.URL
if len(assets) == 0 { if len(assets) == 0 {
result.State = Complete result.State = Complete
return result, nil return result, nil
} }
inspection, err := (gitea.Client{}).InspectAssets(ctx, request.Destination, releaseResult.Release.ID, assets) inspection, err := inspectRemoteAssets(ctx, request.Backend, release.Handle, assets)
if err != nil { if err != nil {
result.State = NotAttempted result.State = NotAttempted
if releaseResult.WriteAttempted { if pageEvidence.Attempted {
result.State = Partial result.State = Partial
} }
result.Uncertain = assetIdentities(assets) result.Uncertain = assetIdentities(assets)
return result, err return result, err
} }
uploadResult, uploadErr := (gitea.Client{}).UploadMissing(ctx, request.Destination, releaseResult.Release.ID, inspection) uploadResult, uploadErr := uploadMissingAssets(ctx, request.Backend, release.Handle, inspection)
result.Matching = uploadResult.Matching result.Matching = uploadResult.Matching
result.Uploaded = uploadResult.Uploaded result.Uploaded = uploadResult.Uploaded
result.Pending = uploadResult.Pending result.Pending = uploadResult.Pending
result.Conflicting = uploadResult.Conflicting result.Conflicting = uploadResult.Conflicting
result.Uncertain = uploadResult.Uncertain result.Uncertain = uploadResult.Uncertain
result.State = State(uploadResult.State) result.State = State(uploadResult.State)
if result.State == NotAttempted && releaseResult.WriteAttempted { if result.State == NotAttempted && pageEvidence.Attempted {
result.State = Partial result.State = Partial
} }
return result, uploadErr return result, uploadErr
} }
func validateBuild(repositoryDir, commit, version string, build *internalbuild.Result, assets []gitea.ExpectedAsset) error { func validateBuild(identity releaseidentity.Identity, commit string, build *internalbuild.Result, assets []artifact.ExpectedAsset) error {
if build == nil { if build == nil {
if len(assets) != 0 { if len(assets) != 0 {
return errors.New("assets require a build identity") return errors.New("assets require a build identity")
} }
return nil return nil
} }
if len(build.Targets) == 0 { if err := validateBuildIdentity(identity, commit, build); err != nil {
return err
}
if len(build.Settings.Targets) == 0 {
if len(assets) != 0 { if len(assets) != 0 {
return errors.New("page-only delivery cannot include binary assets") return errors.New("page-only delivery cannot include binary assets")
} }
return nil return nil
} }
if !build.SourceVerified { if len(assets) != len(build.Settings.Targets)+1 || assets[len(assets)-1].Filename != artifact.ManifestFilename {
return errors.New("build source was not verified as clean and unchanged during compilation") return errors.New("build result does not contain the selected artifacts and complete checksum manifest")
} }
return nil
}
func validateBuildIdentity(identity releaseidentity.Identity, commit string, build *internalbuild.Result) error {
buildRepository, err := filepath.Abs(build.RepositoryDir) buildRepository, err := filepath.Abs(build.RepositoryDir)
if err != nil { if err != nil {
return fmt.Errorf("resolve build repository: %w", err) return fmt.Errorf("resolve build repository: %w", err)
} }
if buildRepository != repositoryDir || build.CandidateCommit != commit || build.Version != version { buildModule, err := filepath.Abs(build.ModuleDir)
return errors.New("build result does not identify the selected tagged source") if err != nil {
return fmt.Errorf("resolve build module: %w", err)
} }
if strings.TrimSpace(build.MainPackage) == "" || strings.TrimSpace(build.BinaryName) == "" || len(assets) != len(build.Targets)+1 || assets[len(assets)-1].Filename != gitea.ManifestFilename { if buildRepository != identity.RepositoryDir || buildModule != identity.ModuleDir || build.ModulePath != identity.ModulePath || build.Tag != identity.Tag || build.CandidateCommit != commit || build.Version != identity.Version {
return errors.New("build result does not identify the selected tagged module")
}
if len(build.Settings.Targets) == 0 {
return nil
}
if !build.SourceVerified {
return errors.New("build source was not verified as clean and unchanged during compilation")
}
if strings.TrimSpace(build.Settings.MainPackage) == "" || strings.TrimSpace(build.Settings.BinaryName) == "" {
return errors.New("build result does not contain the selected artifacts and complete checksum manifest") return errors.New("build result does not contain the selected artifacts and complete checksum manifest")
} }
return nil return nil
} }
func stateForError(err error, pageCreated bool) State { func stateForError(err error, pageCreated bool) State {
var failure *gitea.Failure var failure *forge.Failure
if errors.As(err, &failure) { if errors.As(err, &failure) {
switch failure.Kind { switch failure.Kind {
case gitea.FailureConflict: case forge.FailureConflict:
return Conflict return Conflict
case gitea.FailureUnknown: case forge.FailureUnknown:
return Unknown return Unknown
} }
} }
@@ -212,10 +277,10 @@ func stateForError(err error, pageCreated bool) State {
return NotAttempted return NotAttempted
} }
func assetIdentities(assets []gitea.ExpectedAsset) []gitea.AssetIdentity { func assetIdentities(assets []artifact.ExpectedAsset) []AssetIdentity {
result := make([]gitea.AssetIdentity, 0, len(assets)) result := make([]AssetIdentity, 0, len(assets))
for _, asset := range assets { for _, asset := range assets {
result = append(result, gitea.AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256}) result = append(result, AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256})
} }
return result return result
} }

91
internal/delivery/page.go Normal file
View File

@@ -0,0 +1,91 @@
package delivery
import (
"context"
"errors"
"fmt"
"strings"
"go.maximumdirect.net/releasekit/internal/forge"
)
func coordinateRelease(ctx context.Context, backend forge.Backend, tag, commit, note string) (forge.Release, forge.WriteEvidence, error) {
observedCommit, err := backend.TagCommit(ctx, tag)
if err != nil {
return forge.Release{}, forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, err
}
if observedCommit != commit {
return forge.Release{}, forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, &forge.Failure{
Kind: forge.FailureConflict,
Err: fmt.Errorf("hosted tag %q targets %q, want %q", tag, observedCommit, commit),
}
}
existing, err := backend.FindRelease(ctx, tag)
if err == nil {
if !matchesExistingRelease(existing, tag, note) {
return forge.Release{}, forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, &forge.Failure{
Kind: forge.FailureConflict,
Err: errors.New("existing release does not match the committed note and stable tag"),
}
}
return existing, forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, nil
}
if !isForgeFailure(err, forge.FailureNotFound) {
return forge.Release{}, forge.WriteEvidence{Disposition: forge.WriteNotAttempted}, err
}
request := forge.CreateReleaseRequest{
Tag: tag, Commit: commit, Title: releaseNoteTitle(note), Body: note,
}
created, evidence, createErr := backend.CreateRelease(ctx, request)
if createErr == nil && matchesCreatedRelease(created, request) {
return created, evidence, nil
}
if createErr == nil {
createErr = &forge.Failure{Kind: forge.FailureMalformed, Err: errors.New("created release does not match the requested stable release")}
}
if evidence.Disposition != forge.WriteConflict && evidence.Disposition != forge.WriteUncertain && !isForgeFailure(createErr, forge.FailureMalformed) {
return forge.Release{}, evidence, createErr
}
return reconcileReleaseCreate(ctx, backend, tag, note, evidence, createErr)
}
func reconcileReleaseCreate(ctx context.Context, backend forge.Backend, tag, note string, evidence forge.WriteEvidence, createErr error) (forge.Release, forge.WriteEvidence, error) {
existing, lookupErr := backend.FindRelease(ctx, tag)
if lookupErr == nil {
if matchesExistingRelease(existing, tag, note) {
return existing, evidence, nil
}
return forge.Release{}, evidence, &forge.Failure{Kind: forge.FailureConflict, Err: errors.Join(createErr, errors.New("reconciled release does not match the committed note and stable tag"))}
}
if isForgeFailure(lookupErr, forge.FailureNotFound) {
if evidence.Disposition == forge.WriteConflict {
return forge.Release{}, evidence, &forge.Failure{Kind: forge.FailureConflict, Err: createErr}
}
return forge.Release{}, evidence, &forge.Failure{Kind: forge.FailureUnknown, Err: createErr}
}
return forge.Release{}, evidence, &forge.Failure{Kind: forge.FailureUnknown, Err: errors.Join(createErr, lookupErr)}
}
func matchesExistingRelease(release forge.Release, tag, note string) bool {
return release.Tag == tag && release.Body == note && !release.Draft && !release.Prerelease
}
func matchesCreatedRelease(release forge.Release, request forge.CreateReleaseRequest) bool {
return release.Tag == request.Tag && release.Body == request.Body && release.Title == request.Title && !release.Draft && !release.Prerelease
}
func releaseNoteTitle(note string) string {
first := strings.SplitN(note, "\n", 2)[0]
if !strings.HasPrefix(first, "# ") {
return ""
}
return strings.TrimSpace(strings.TrimPrefix(first, "# "))
}
func isForgeFailure(err error, kind forge.FailureKind) bool {
var failure *forge.Failure
return errors.As(err, &failure) && failure.Kind == kind
}

View File

@@ -0,0 +1,204 @@
package delivery
import (
"context"
"errors"
"io"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/forge"
)
func TestCoordinateReleaseAcceptsExistingPageAndRetainsItsTitle(t *testing.T) {
backend := &pageBackend{
commit: "commit",
findResults: []pageFindResult{{release: forge.Release{
Tag: "v1.2.3", Title: "Maintained title", Body: "# Release\n\nNotes", Handle: "release",
}}},
}
release, evidence, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release\n\nNotes")
if err != nil || release.Title != "Maintained title" || evidence.Attempted {
t.Fatalf("coordinateRelease() = %#v, evidence %#v, error %v", release, evidence, err)
}
if backend.createCalls != 0 || backend.findCalls != 1 {
t.Fatalf("calls = create %d, find %d", backend.createCalls, backend.findCalls)
}
}
func TestCoordinateReleaseRejectsWrongHostedTagAndExistingPage(t *testing.T) {
t.Run("wrong hosted tag", func(t *testing.T) {
backend := &pageBackend{commit: "other"}
_, evidence, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release")
if !isForgeFailure(err, forge.FailureConflict) || evidence.Attempted || backend.findCalls != 0 || backend.createCalls != 0 {
t.Fatalf("coordinateRelease() evidence %#v, error %v, calls find=%d create=%d", evidence, err, backend.findCalls, backend.createCalls)
}
})
t.Run("missing hosted tag", func(t *testing.T) {
backend := &pageBackend{tagErr: &forge.Failure{Kind: forge.FailureNotFound, Err: errors.New("tag missing")}}
_, _, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release")
if !isForgeFailure(err, forge.FailureNotFound) || backend.findCalls != 0 || backend.createCalls != 0 {
t.Fatalf("coordinateRelease() error = %v, calls find=%d create=%d", err, backend.findCalls, backend.createCalls)
}
})
for _, release := range []forge.Release{
{Tag: "v9.9.9", Body: "# Release", Title: "Release"},
{Tag: "v1.2.3", Body: "different", Title: "Release"},
{Tag: "v1.2.3", Body: "# Release", Title: "Release", Draft: true},
{Tag: "v1.2.3", Body: "# Release", Title: "Release", Prerelease: true},
} {
backend := &pageBackend{commit: "commit", findResults: []pageFindResult{{release: release}}}
_, _, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release")
if !isForgeFailure(err, forge.FailureConflict) || backend.createCalls != 0 {
t.Fatalf("coordinateRelease(%#v) error = %v, create calls = %d", release, err, backend.createCalls)
}
}
}
func TestCoordinateReleaseCreatesWithFullNoteAndVerifiesRequestedTitle(t *testing.T) {
backend := &pageBackend{
commit: "commit",
findResults: []pageFindResult{{err: &forge.Failure{Kind: forge.FailureNotFound}}},
createResult: pageCreateResult{
release: forge.Release{Tag: "v1.2.3", Title: "Release", Body: "# Release\n\nFull note", Handle: "release"},
evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted},
},
}
release, evidence, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release\n\nFull note")
if err != nil || release.Handle != "release" || evidence.Disposition != forge.WriteAccepted || !evidence.Attempted {
t.Fatalf("coordinateRelease() = %#v, evidence %#v, error %v", release, evidence, err)
}
if got := backend.createRequest; got.Tag != "v1.2.3" || got.Commit != "commit" || got.Title != "Release" || got.Body != "# Release\n\nFull note" || got.Draft || got.Prerelease {
t.Fatalf("CreateRelease request = %#v", got)
}
}
func TestCoordinateReleaseReconcilesCreateOutcomes(t *testing.T) {
createErr := &forge.Failure{Kind: forge.FailureTransport, Err: errors.New("connection lost")}
lookupErr := errors.New("lookup unavailable")
matching := forge.Release{Tag: "v1.2.3", Title: "Original", Body: "# Release\n\nNotes", Handle: "release"}
wrong := forge.Release{Tag: "v1.2.3", Body: "different", Handle: "other"}
notFound := &forge.Failure{Kind: forge.FailureNotFound}
for _, test := range []struct {
name string
create pageCreateResult
followup pageFindResult
wantKind forge.FailureKind
wantRecovered bool
wantCause error
}{
{
name: "matching page after conflict",
create: pageCreateResult{err: createErr, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteConflict}},
followup: pageFindResult{release: matching}, wantRecovered: true,
},
{
name: "different page after uncertain write",
create: pageCreateResult{err: createErr, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteUncertain}},
followup: pageFindResult{release: wrong}, wantKind: forge.FailureConflict,
},
{
name: "missing after conflict",
create: pageCreateResult{err: createErr, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteConflict}},
followup: pageFindResult{err: notFound}, wantKind: forge.FailureConflict,
},
{
name: "missing after uncertain write",
create: pageCreateResult{err: createErr, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteUncertain}},
followup: pageFindResult{err: notFound}, wantKind: forge.FailureUnknown, wantCause: createErr,
},
{
name: "unavailable follow-up",
create: pageCreateResult{err: createErr, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteUncertain}},
followup: pageFindResult{err: lookupErr}, wantKind: forge.FailureUnknown, wantCause: lookupErr,
},
{
name: "inconsistent accepted response reconciled",
create: pageCreateResult{release: wrong, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
followup: pageFindResult{release: matching}, wantRecovered: true,
},
{
name: "inconsistent accepted response missing",
create: pageCreateResult{release: wrong, evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
followup: pageFindResult{err: notFound}, wantKind: forge.FailureUnknown,
},
} {
t.Run(test.name, func(t *testing.T) {
backend := &pageBackend{
commit: "commit",
findResults: []pageFindResult{{err: notFound}, test.followup},
createResult: test.create,
}
release, evidence, err := coordinateRelease(context.Background(), backend, "v1.2.3", "commit", "# Release\n\nNotes")
if test.wantRecovered {
if err != nil || release.Handle != "release" || !evidence.Attempted || backend.findCalls != 2 {
t.Fatalf("recovered result = %#v, evidence %#v, error %v, find calls %d", release, evidence, err, backend.findCalls)
}
return
}
if !isForgeFailure(err, test.wantKind) || !evidence.Attempted {
t.Fatalf("result evidence %#v, error %v; want kind %s", evidence, err, test.wantKind)
}
if test.wantCause != nil && !errors.Is(err, test.wantCause) {
t.Fatalf("error %v does not retain cause %v", err, test.wantCause)
}
})
}
}
type pageFindResult struct {
release forge.Release
err error
}
type pageCreateResult struct {
release forge.Release
evidence forge.WriteEvidence
err error
}
type pageBackend struct {
commit string
tagErr error
findResults []pageFindResult
findCalls int
createResult pageCreateResult
createCalls int
createRequest forge.CreateReleaseRequest
}
func (backend *pageBackend) Preflight(context.Context) error { return nil }
func (backend *pageBackend) TagCommit(context.Context, string) (string, error) {
return backend.commit, backend.tagErr
}
func (backend *pageBackend) FindRelease(context.Context, string) (forge.Release, error) {
index := backend.findCalls
backend.findCalls++
if index >= len(backend.findResults) {
return forge.Release{}, &forge.Failure{Kind: forge.FailureNotFound}
}
result := backend.findResults[index]
return result.release, result.err
}
func (backend *pageBackend) CreateRelease(_ context.Context, request forge.CreateReleaseRequest) (forge.Release, forge.WriteEvidence, error) {
backend.createCalls++
backend.createRequest = request
return backend.createResult.release, backend.createResult.evidence, backend.createResult.err
}
func (*pageBackend) ListAssets(context.Context, any) ([]forge.Asset, error) { return nil, nil }
func (*pageBackend) OpenAsset(context.Context, any) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader("")), nil
}
func (*pageBackend) UploadAsset(context.Context, any, string, io.Reader) (forge.WriteEvidence, error) {
return forge.WriteEvidence{}, nil
}

View File

@@ -0,0 +1,84 @@
package delivery
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"testing"
"go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
)
const performanceArtifactSize = 16 << 20
func BenchmarkPerformanceAssetPreflight(b *testing.B) {
result, totalBytes := performanceBuildResult(b)
declarations, err := declaredBuildAssets(result)
if err != nil {
b.Fatal(err)
}
b.Run("Declarations", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(totalBytes)
b.ResetTimer()
b.ReportMetric(float64(totalBytes), "bytes/op")
for i := 0; i < b.N; i++ {
assets, err := declaredBuildAssets(result)
if err != nil || len(assets) != len(declarations) {
b.Fatalf("declaredBuildAssets() returned %d assets, err %v", len(assets), err)
}
}
})
b.Run("DeclarationsAndLocalVerification", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(totalBytes)
b.ResetTimer()
b.ReportMetric(float64(totalBytes), "bytes/op")
for i := 0; i < b.N; i++ {
assets, err := declaredBuildAssets(result)
if err != nil {
b.Fatal(err)
}
if err := artifact.VerifyLocalAssets(assets); err != nil {
b.Fatal(err)
}
}
})
}
func performanceBuildResult(b *testing.B) (internalbuild.Result, int64) {
b.Helper()
outputDir := b.TempDir()
data := make([]byte, performanceArtifactSize)
for i := range data {
data[i] = byte((i*31 + i/251 + 17) % 251)
}
digest := sha256.Sum256(data)
result := internalbuild.Result{
Version: "v1.2.3",
Settings: artifact.NormalizeSettings("./cmd/releasekit", "releasekit", []artifact.Target{
{OS: "linux", Arch: "amd64"},
{OS: "windows", Arch: "amd64"},
}),
}
for _, target := range result.Settings.Targets {
name := fmt.Sprintf("releasekit-v1.2.3-%s-%s", target.OS, target.Arch)
if target.OS == "windows" {
name += ".exe"
}
path := filepath.Join(outputDir, name)
if err := os.WriteFile(path, data, 0o600); err != nil {
b.Fatal(err)
}
result.Artifacts = append(result.Artifacts, internalbuild.Artifact{
Path: path, Filename: name, Target: target,
SHA256: hex.EncodeToString(digest[:]),
})
}
return result, 2 * performanceArtifactSize
}

View File

@@ -0,0 +1,279 @@
package delivery
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"sort"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/forge"
)
type AssetState string
const (
AssetMatching AssetState = "matching"
AssetMissing AssetState = "missing"
AssetConflicting AssetState = "conflicting"
AssetUnverifiable AssetState = "unverifiable"
)
type AssetIdentity struct {
Filename string
SHA256 string
}
type AssetInspection struct {
Expected artifact.ExpectedAsset
State AssetState
Existing []forge.Asset
Err error
}
type Inspection struct {
Assets []AssetInspection
Unrelated []forge.Asset
}
type UploadResult struct {
State State
Matching []AssetIdentity
Uploaded []AssetIdentity
Pending []AssetIdentity
Conflicting []AssetIdentity
Uncertain []AssetIdentity
}
func inspectRemoteAssets(ctx context.Context, backend forge.Backend, releaseHandle any, expected []artifact.ExpectedAsset) (Inspection, error) {
if err := artifact.ValidateExpectedAssets(expected); err != nil {
return Inspection{}, &forge.Failure{Kind: forge.FailureInvalid, Err: err}
}
listed, err := backend.ListAssets(ctx, releaseHandle)
if err != nil {
inspection := Inspection{Assets: make([]AssetInspection, 0, len(expected))}
for _, item := range expected {
inspection.Assets = append(inspection.Assets, AssetInspection{Expected: item, State: AssetUnverifiable, Err: err})
}
return inspection, err
}
byName := make(map[string][]forge.Asset, len(listed))
for _, item := range listed {
byName[item.Filename] = append(byName[item.Filename], item)
}
inspection := Inspection{Assets: make([]AssetInspection, 0, len(expected))}
declared := make(map[string]struct{}, len(expected))
for _, item := range expected {
declared[item.Filename] = struct{}{}
matches := byName[item.Filename]
observation := AssetInspection{Expected: item, Existing: matches}
switch len(matches) {
case 0:
observation.State = AssetMissing
case 1:
digest, sizeMatches, err := remoteAssetDigest(ctx, backend, matches[0].Handle, item.Size)
if err != nil {
observation.State = AssetUnverifiable
observation.Err = err
} else if sizeMatches && digest == item.SHA256 {
observation.State = AssetMatching
} else {
observation.State = AssetConflicting
}
default:
observation.State = AssetConflicting
}
inspection.Assets = append(inspection.Assets, observation)
}
for _, item := range listed {
if _, ok := declared[item.Filename]; !ok {
inspection.Unrelated = append(inspection.Unrelated, item)
}
}
return inspection, nil
}
func remoteAssetDigest(ctx context.Context, backend forge.Backend, handle any, expectedSize int64) (string, bool, error) {
if err := ctx.Err(); err != nil {
return "", false, err
}
stream, err := backend.OpenAsset(ctx, handle)
if err != nil {
return "", false, err
}
hasher := sha256.New()
read, readErr := io.Copy(hasher, io.LimitReader(stream, expectedSize))
excess := false
if readErr == nil && read == expectedSize {
var probe [1]byte
for attempts := 0; ; attempts++ {
var n int
n, readErr = stream.Read(probe[:])
excess = n != 0
if readErr != nil || excess {
if readErr == io.EOF {
readErr = nil
}
break
}
if attempts == 99 {
readErr = io.ErrNoProgress
break
}
}
}
closeErr := stream.Close()
if err := errors.Join(readErr, closeErr, ctx.Err()); err != nil {
return "", false, &forge.Failure{Kind: forge.FailureUnverifiable, Err: err}
}
return hex.EncodeToString(hasher.Sum(nil)), read == expectedSize && !excess, nil
}
func uploadMissingAssets(ctx context.Context, backend forge.Backend, releaseHandle any, inspection Inspection) (result UploadResult, err error) {
expected := make([]artifact.ExpectedAsset, len(inspection.Assets))
for index, observation := range inspection.Assets {
expected[index] = observation.Expected
}
if err := artifact.ValidateExpectedAssets(expected); err != nil {
return UploadResult{State: Partial}, &forge.Failure{Kind: forge.FailureInvalid, Err: err}
}
result = UploadResult{State: Partial}
preflightConflict := false
preflightUnverifiable := false
var inspectionErrors []error
var missing []artifact.ExpectedAsset
pending := make(map[string]struct{}, len(expected))
// Keep the initial observation order and compact pending identities once,
// including on early returns after partial or unresolved uploads.
defer func() {
remaining := result.Pending[:0]
for _, item := range result.Pending {
if _, ok := pending[item.Filename]; ok {
remaining = append(remaining, item)
}
}
result.Pending = remaining
}()
for _, observation := range inspection.Assets {
item := identity(observation.Expected)
switch observation.State {
case AssetMatching:
result.Matching = append(result.Matching, item)
case AssetMissing:
result.Pending = append(result.Pending, item)
pending[observation.Expected.Filename] = struct{}{}
missing = append(missing, observation.Expected)
case AssetConflicting:
preflightConflict = true
result.Conflicting = append(result.Conflicting, item)
case AssetUnverifiable:
preflightUnverifiable = true
result.Uncertain = append(result.Uncertain, item)
if observation.Err != nil {
inspectionErrors = append(inspectionErrors, fmt.Errorf("verify existing attachment %q: %w", item.Filename, observation.Err))
}
default:
return result, &forge.Failure{Kind: forge.FailureInvalid, Err: fmt.Errorf("asset %q has no inspection result", observation.Expected.Filename)}
}
}
if preflightConflict {
result.State = Conflict
return result, &forge.Failure{Kind: forge.FailureConflict, Err: errors.Join(errors.New("one or more existing attachments conflict"), errors.Join(inspectionErrors...))}
}
if preflightUnverifiable {
result.State = NotAttempted
return result, &forge.Failure{Kind: forge.FailureUnverifiable, Err: errors.Join(errors.New("one or more existing attachments could not be verified"), errors.Join(inspectionErrors...))}
}
if len(pending) == 0 {
result.State = Complete
return result, nil
}
orderMissing(missing)
for _, item := range missing {
content, err := assetContent(item)
if err != nil {
return result, &forge.Failure{Kind: forge.FailureInvalid, Err: fmt.Errorf("open local release asset %q: %w", item.Filename, err)}
}
evidence, uploadErr := backend.UploadAsset(ctx, releaseHandle, item.Filename, content)
closeErr := content.Close()
if uploadErr == nil {
result.Uploaded = append(result.Uploaded, identity(item))
delete(pending, item.Filename)
continue
}
operationErr := errors.Join(uploadErr, closeErr)
if evidence.Disposition != forge.WriteConflict && evidence.Disposition != forge.WriteUncertain {
return result, operationErr
}
delete(pending, item.Filename)
if err := reconcileAssetUpload(ctx, backend, releaseHandle, item, evidence, operationErr, &result); err != nil {
return result, err
}
}
if len(pending) == 0 {
result.State = Complete
}
return result, nil
}
func reconcileAssetUpload(ctx context.Context, backend forge.Backend, releaseHandle any, item artifact.ExpectedAsset, evidence forge.WriteEvidence, uploadErr error, result *UploadResult) error {
inspection, inspectErr := inspectRemoteAssets(ctx, backend, releaseHandle, []artifact.ExpectedAsset{item})
if inspectErr != nil || len(inspection.Assets) != 1 {
result.State = Unknown
result.Uncertain = append(result.Uncertain, identity(item))
return &forge.Failure{Kind: forge.FailureUnknown, Err: errors.Join(uploadErr, inspectErr)}
}
observation := inspection.Assets[0]
switch observation.State {
case AssetMatching:
result.Matching = append(result.Matching, identity(item))
return nil
case AssetConflicting:
result.State = Conflict
result.Conflicting = append(result.Conflicting, identity(item))
return &forge.Failure{Kind: forge.FailureConflict, Err: uploadErr}
case AssetMissing:
if evidence.Disposition == forge.WriteConflict {
result.State = Conflict
result.Conflicting = append(result.Conflicting, identity(item))
return &forge.Failure{Kind: forge.FailureConflict, Err: uploadErr}
}
result.State = Unknown
result.Uncertain = append(result.Uncertain, identity(item))
return &forge.Failure{Kind: forge.FailureUnknown, Err: uploadErr}
default:
result.State = Unknown
result.Uncertain = append(result.Uncertain, identity(item))
return &forge.Failure{Kind: forge.FailureUnknown, Err: errors.Join(uploadErr, observation.Err)}
}
}
func orderMissing(missing []artifact.ExpectedAsset) {
sort.Slice(missing, func(i, j int) bool {
if missing[i].Filename == artifact.ManifestFilename {
return false
}
if missing[j].Filename == artifact.ManifestFilename {
return true
}
return missing[i].Filename < missing[j].Filename
})
}
func assetContent(asset artifact.ExpectedAsset) (io.ReadCloser, error) {
if len(asset.Content) > 0 {
return io.NopCloser(bytes.NewReader(asset.Content)), nil
}
return os.Open(asset.Path)
}
func identity(asset artifact.ExpectedAsset) AssetIdentity {
return AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256}
}

View File

@@ -0,0 +1,543 @@
package delivery
import (
"bytes"
"context"
"errors"
"io"
"os"
"reflect"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/forge"
)
func TestInspectRemoteAssetsComparesContentAndPreservesUnrelatedAssets(t *testing.T) {
backend := &assetBackend{
lists: []assetListResult{{assets: []forge.Asset{
{Filename: "same.bin", Size: 4, Handle: "same"},
{Filename: "different.bin", Size: 4, Handle: "different"},
{Filename: "duplicate.bin", Size: 4, Handle: "first"},
{Filename: "duplicate.bin", Size: 4, Handle: "second"},
{Filename: "unrelated.txt", Size: 3, Handle: "unrelated"},
}}},
content: map[string][]byte{
"same": []byte("same"),
"different": []byte("diff"),
},
}
expected := []artifact.ExpectedAsset{
expectedAsset("same.bin", []byte("same")),
expectedAsset("different.bin", []byte("else")),
expectedAsset("duplicate.bin", []byte("dupe")),
expectedAsset("missing.bin", []byte("gone")),
}
inspection, err := inspectRemoteAssets(context.Background(), backend, "release", expected)
if err != nil {
t.Fatal(err)
}
wantStates := []AssetState{AssetMatching, AssetConflicting, AssetConflicting, AssetMissing}
for i, observation := range inspection.Assets {
if observation.State != wantStates[i] {
t.Errorf("asset %q state = %s, want %s", observation.Expected.Filename, observation.State, wantStates[i])
}
}
if len(inspection.Unrelated) != 1 || inspection.Unrelated[0].Filename != "unrelated.txt" {
t.Fatalf("unrelated assets = %#v", inspection.Unrelated)
}
if len(backend.opened) != 2 || !backend.opened[0].closed || !backend.opened[1].closed {
t.Fatalf("opened asset streams = %#v", backend.opened)
}
}
type controlledAssetStream struct {
*bytes.Reader
readErr error
errorAfter int
closeErr error
cancel context.CancelFunc
read int
closed bool
}
func (stream *controlledAssetStream) Read(p []byte) (int, error) {
n, err := stream.Reader.Read(p)
stream.read += n
if stream.cancel != nil {
stream.cancel()
stream.cancel = nil
}
if stream.readErr != nil && n > 0 && stream.read > stream.errorAfter {
err, stream.readErr = stream.readErr, nil
}
return n, err
}
func (stream *controlledAssetStream) Close() error {
stream.closed = true
return stream.closeErr
}
type controlledAssetBackend struct {
pageBackend
stream *controlledAssetStream
}
func (backend *controlledAssetBackend) ListAssets(context.Context, any) ([]forge.Asset, error) {
return []forge.Asset{{Filename: "asset.bin", Size: 999, Handle: "asset"}}, nil
}
func (backend *controlledAssetBackend) OpenAsset(context.Context, any) (io.ReadCloser, error) {
return backend.stream, nil
}
func TestInspectRemoteAssetBoundsContentAndPreservesErrors(t *testing.T) {
readErr := errors.New("read failed")
closeErr := errors.New("close failed")
for _, test := range []struct {
name, expected, actual string
readErr, closeErr error
cancel bool
errorAfter int
state AssetState
}{
{"empty", "", "", nil, nil, false, 0, AssetMatching},
{"shorter", "abcd", "abc", nil, nil, false, 0, AssetConflicting},
{"matching", "abcd", "abcd", nil, nil, false, 0, AssetMatching},
{"different", "abcd", "wxyz", nil, nil, false, 0, AssetConflicting},
{"oversized", "abcd", "abcdefghijk", nil, nil, false, 0, AssetConflicting},
{"empty oversized", "", "abc", nil, nil, false, 0, AssetConflicting},
{"data and error", "abcd", "abcd", readErr, nil, false, 0, AssetUnverifiable},
{"probe data and error", "abcd", "abcde", readErr, nil, false, 4, AssetUnverifiable},
{"close failure", "abcd", "abcdefgh", nil, closeErr, false, 0, AssetUnverifiable},
{"cancellation", "abcd", "abcd", nil, nil, true, 0, AssetUnverifiable},
} {
t.Run(test.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
stream := &controlledAssetStream{Reader: bytes.NewReader([]byte(test.actual)), readErr: test.readErr, errorAfter: test.errorAfter, closeErr: test.closeErr}
if test.cancel {
stream.cancel = cancel
}
backend := &controlledAssetBackend{stream: stream}
inspection, err := inspectRemoteAssets(ctx, backend, "release", []artifact.ExpectedAsset{expectedAsset("asset.bin", []byte(test.expected))})
if err != nil || len(inspection.Assets) != 1 || inspection.Assets[0].State != test.state || !stream.closed || stream.read > len(test.expected)+1 {
t.Fatalf("inspection = %#v, error = %v, bytes = %d, closed = %t", inspection, err, stream.read, stream.closed)
}
cause := inspection.Assets[0].Err
if test.readErr != nil && !errors.Is(cause, test.readErr) || test.closeErr != nil && !errors.Is(cause, test.closeErr) || test.cancel && !errors.Is(cause, context.Canceled) {
t.Fatalf("inspection lost cause: %v", cause)
}
})
}
}
func TestInspectRemoteAssetsListingFailureDoesNotBecomeUnknownWrite(t *testing.T) {
assets := []artifact.ExpectedAsset{expectedAsset("a.bin", []byte("a")), expectedAsset("b.bin", []byte("b"))}
listErr := &forge.Failure{Kind: forge.FailureTransport, Err: errors.New("service unavailable")}
backend := &assetBackend{lists: []assetListResult{{err: listErr}}}
inspection, err := inspectRemoteAssets(context.Background(), backend, "release", assets)
if !errors.Is(err, listErr) || len(inspection.Assets) != len(assets) {
t.Fatalf("inspection = %#v, error %v", inspection, err)
}
for _, observation := range inspection.Assets {
if observation.State != AssetUnverifiable || !errors.Is(observation.Err, listErr) {
t.Fatalf("listing failure observation = %#v", observation)
}
}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspection)
if !isForgeFailure(err, forge.FailureUnverifiable) || result.State != NotAttempted || len(result.Uncertain) != len(assets) || len(backend.uploadNames) != 0 {
t.Fatalf("uploadMissingAssets() = %#v, error %v, uploads %v", result, err, backend.uploadNames)
}
}
func TestInspectRemoteAssetsKeepsMatchingManifestWhenBinariesAreMissing(t *testing.T) {
binary := expectedAsset("app-linux-amd64", []byte("binary"))
manifest, err := artifact.BuildManifest([]artifact.ExpectedAsset{binary})
if err != nil {
t.Fatal(err)
}
backend := &assetBackend{
lists: []assetListResult{{assets: []forge.Asset{{Filename: manifest.Filename, Size: int64(len(manifest.Content)), Handle: "manifest"}}}},
content: map[string][]byte{"manifest": manifest.Content},
}
inspection, err := inspectRemoteAssets(context.Background(), backend, "release", []artifact.ExpectedAsset{binary, manifest})
if err != nil {
t.Fatal(err)
}
if inspection.Assets[0].State != AssetMissing || inspection.Assets[1].State != AssetMatching {
t.Fatalf("manifest inspection = %#v", inspection.Assets)
}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspection)
if err != nil || result.State != Complete || !reflect.DeepEqual(result.Uploaded, []AssetIdentity{identity(binary)}) {
t.Fatalf("uploadMissingAssets() = %#v, error %v", result, err)
}
if !reflect.DeepEqual(backend.uploadNames, []string{binary.Filename}) {
t.Fatalf("uploaded names = %v", backend.uploadNames)
}
}
func TestInspectRemoteAssetsRejectsSubsetOrDifferentManifestContent(t *testing.T) {
binaryA := expectedAsset("a", []byte("a"))
binaryB := expectedAsset("b", []byte("b"))
manifest, err := artifact.BuildManifest([]artifact.ExpectedAsset{binaryA, binaryB})
if err != nil {
t.Fatal(err)
}
for _, test := range []struct {
name string
content []byte
}{
{name: "subset", content: []byte("a a\n")},
{name: "different", content: []byte("different manifest\n")},
} {
t.Run(test.name, func(t *testing.T) {
backend := &assetBackend{
lists: []assetListResult{{assets: []forge.Asset{{Filename: artifact.ManifestFilename, Handle: "manifest"}}}},
content: map[string][]byte{"manifest": test.content},
}
inspection, err := inspectRemoteAssets(context.Background(), backend, "release", []artifact.ExpectedAsset{binaryA, binaryB, manifest})
if err != nil {
t.Fatal(err)
}
if inspection.Assets[2].State != AssetConflicting {
t.Fatalf("manifest state = %s, want conflicting", inspection.Assets[2].State)
}
})
}
}
func TestUploadMissingAssetsPreflightsAndOrdersWrites(t *testing.T) {
assets := []artifact.ExpectedAsset{
expectedAsset("z.bin", []byte("z")),
expectedAsset(artifact.ManifestFilename, []byte("manifest")),
expectedAsset("a.bin", []byte("a")),
}
inspection := inspectionFor(assets, map[string]AssetState{
"z.bin": AssetMissing,
artifact.ManifestFilename: AssetMissing,
"a.bin": AssetMissing,
})
backend := &assetBackend{uploads: []assetUploadResult{
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
}}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspection)
if err != nil || result.State != Complete {
t.Fatalf("uploadMissingAssets() = %#v, error %v", result, err)
}
want := []string{"a.bin", "z.bin", artifact.ManifestFilename}
if !reflect.DeepEqual(backend.uploadNames, want) {
t.Fatalf("upload order = %v, want %v", backend.uploadNames, want)
}
}
func TestUploadMissingAssetsStopsBeforeWritesForConflictOrUnverifiableContent(t *testing.T) {
for _, test := range []struct {
name string
state AssetState
want State
}{
{name: "conflict", state: AssetConflicting, want: Conflict},
{name: "unverifiable", state: AssetUnverifiable, want: NotAttempted},
} {
t.Run(test.name, func(t *testing.T) {
assets := []artifact.ExpectedAsset{expectedAsset("existing", []byte("old")), expectedAsset("missing", []byte("new"))}
inspection := inspectionFor(assets, map[string]AssetState{"existing": test.state, "missing": AssetMissing})
result, err := uploadMissingAssets(context.Background(), &assetBackend{}, "release", inspection)
if err == nil || result.State != test.want || len(result.Pending) != 1 || len(result.Conflicting)+len(result.Uncertain) != 1 {
t.Fatalf("uploadMissingAssets() = %#v, error %v", result, err)
}
})
}
}
func TestUploadMissingAssetsPreservesInspectionCausesAndConflictPrecedence(t *testing.T) {
readErr := errors.New("asset download failed")
for _, conflict := range []bool{false, true} {
name := "unverifiable"
if conflict {
name = "conflict"
}
t.Run(name, func(t *testing.T) {
backend := &assetBackend{}
inspection := Inspection{Assets: []AssetInspection{
{Expected: expectedAsset("canceled.bin", []byte("a")), State: AssetUnverifiable, Err: context.Canceled},
{Expected: expectedAsset("unreadable.bin", []byte("b")), State: AssetUnverifiable, Err: readErr},
}}
wantState, wantKind := NotAttempted, forge.FailureUnverifiable
if conflict {
inspection.Assets = append(inspection.Assets, AssetInspection{Expected: expectedAsset("conflicting.bin", []byte("c")), State: AssetConflicting})
wantState, wantKind = Conflict, forge.FailureConflict
}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspection)
if !isForgeFailure(err, wantKind) || result.State != wantState || len(result.Uncertain) != 2 || len(backend.uploadNames) != 0 {
t.Fatalf("result = %#v, error %v", result, err)
}
if !errors.Is(err, context.Canceled) || !errors.Is(err, readErr) || !strings.Contains(err.Error(), "canceled.bin") || !strings.Contains(err.Error(), "unreadable.bin") {
t.Fatalf("aggregate lost cause or asset context: %v", err)
}
})
}
}
func TestUploadMissingAssetsReconcilesOnceAndKeepsLaterAssetsPending(t *testing.T) {
assets := []artifact.ExpectedAsset{
expectedAsset("a.bin", []byte("a")),
expectedAsset("b.bin", []byte("b")),
expectedAsset("c.bin", []byte("c")),
}
for _, test := range []struct {
name string
disposition forge.WriteDisposition
followupAssets []forge.Asset
followupData map[string][]byte
openErrors map[string]error
followupErr error
wantState State
wantCategory string
wantContinue bool
}{
{
name: "matching bytes resolve uncertain upload", disposition: forge.WriteUncertain,
followupAssets: []forge.Asset{{Filename: "a.bin", Handle: "a"}}, followupData: map[string][]byte{"a": []byte("a")},
wantState: Complete, wantCategory: "matching", wantContinue: true,
},
{
name: "different bytes conflict", disposition: forge.WriteUncertain,
followupAssets: []forge.Asset{{Filename: "a.bin", Handle: "a"}}, followupData: map[string][]byte{"a": []byte("x")},
wantState: Conflict, wantCategory: "conflicting",
},
{
name: "oversized bytes conflict", disposition: forge.WriteUncertain,
followupAssets: []forge.Asset{{Filename: "a.bin", Handle: "a"}}, followupData: map[string][]byte{"a": []byte("oversized")},
wantState: Conflict, wantCategory: "conflicting",
},
{
name: "missing after conflict remains conflict", disposition: forge.WriteConflict,
wantState: Conflict, wantCategory: "conflicting",
},
{
name: "missing after uncertain upload is unknown", disposition: forge.WriteUncertain,
wantState: Unknown, wantCategory: "uncertain",
},
{
name: "unreadable follow-up is unknown", disposition: forge.WriteUncertain,
followupAssets: []forge.Asset{{Filename: "a.bin", Handle: "a"}}, openErrors: map[string]error{"a": errors.New("download failed")},
wantState: Unknown, wantCategory: "uncertain",
},
} {
t.Run(test.name, func(t *testing.T) {
first := assetListResult{assets: []forge.Asset{}}
followup := assetListResult{assets: test.followupAssets, err: test.followupErr}
backend := &assetBackend{
lists: []assetListResult{first, followup},
content: test.followupData,
openErrors: test.openErrors,
uploads: []assetUploadResult{{
evidence: forge.WriteEvidence{Attempted: true, Disposition: test.disposition},
err: &forge.Failure{Kind: failureKindForDisposition(test.disposition), Err: errors.New("upload outcome unresolved")},
}},
}
inspection, err := inspectRemoteAssets(context.Background(), backend, "release", assets)
if err != nil {
t.Fatal(err)
}
result, uploadErr := uploadMissingAssets(context.Background(), backend, "release", inspection)
if result.State != test.wantState || backend.listCalls != 2 {
t.Fatalf("result = %#v, error %v, list calls %d, uploads %v", result, uploadErr, backend.listCalls, backend.uploadNames)
}
if test.wantContinue {
if uploadErr != nil || !reflect.DeepEqual(backend.uploadNames, []string{"a.bin", "b.bin", "c.bin"}) || len(result.Pending) != 0 {
t.Fatalf("continued result = %#v, error %v, uploads %v", result, uploadErr, backend.uploadNames)
}
} else {
if uploadErr == nil || !reflect.DeepEqual(backend.uploadNames, []string{"a.bin"}) {
t.Fatalf("stopped result = %#v, error %v, uploads %v", result, uploadErr, backend.uploadNames)
}
if !reflect.DeepEqual(result.Pending, []AssetIdentity{identity(assets[1]), identity(assets[2])}) {
t.Fatalf("pending = %#v", result.Pending)
}
}
var category []AssetIdentity
switch test.wantCategory {
case "matching":
category = result.Matching
case "conflicting":
category = result.Conflicting
case "uncertain":
category = result.Uncertain
}
if len(category) != 1 || category[0].Filename != "a.bin" {
t.Fatalf("%s assets = %#v", test.wantCategory, category)
}
})
}
}
func TestUploadMissingAssetsPreservesAcknowledgedProgressOnDefinitiveFailure(t *testing.T) {
assets := []artifact.ExpectedAsset{expectedAsset("a.bin", []byte("a")), expectedAsset("b.bin", []byte("b")), expectedAsset("c.bin", []byte("c"))}
backend := &assetBackend{uploads: []assetUploadResult{
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteRejected}, err: &forge.Failure{Kind: forge.FailureRejected, Err: errors.New("denied")}},
}}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspectionFor(assets, map[string]AssetState{
"a.bin": AssetMissing, "b.bin": AssetMissing, "c.bin": AssetMissing,
}))
if err == nil || result.State != Partial || !reflect.DeepEqual(result.Uploaded, []AssetIdentity{identity(assets[0])}) || !reflect.DeepEqual(result.Pending, []AssetIdentity{identity(assets[1]), identity(assets[2])}) {
t.Fatalf("uploadMissingAssets() = %#v, error %v", result, err)
}
}
func TestUploadMissingAssetsRetainsPendingObservationOrderOnEarlyReturn(t *testing.T) {
assets := []artifact.ExpectedAsset{
expectedAsset("z.bin", []byte("z")),
expectedAsset("a.bin", []byte("a")),
expectedAsset("c.bin", []byte("c")),
expectedAsset("b.bin", []byte("b")),
}
for _, disposition := range []forge.WriteDisposition{forge.WriteRejected, forge.WriteUncertain} {
t.Run(string(disposition), func(t *testing.T) {
backend := &assetBackend{uploads: []assetUploadResult{
{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}},
{evidence: forge.WriteEvidence{Attempted: true, Disposition: disposition}, err: errors.New("upload stopped")},
}}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspectionFor(assets, map[string]AssetState{
"z.bin": AssetMissing, "a.bin": AssetMissing, "c.bin": AssetMissing, "b.bin": AssetMissing,
}))
wantPending := []AssetIdentity{identity(assets[0]), identity(assets[2]), identity(assets[3])}
wantState := Partial
if disposition == forge.WriteUncertain {
wantPending = wantPending[:2]
wantState = Unknown
if !reflect.DeepEqual(result.Uncertain, []AssetIdentity{identity(assets[3])}) {
t.Fatalf("uncertain = %#v", result.Uncertain)
}
}
if err == nil || result.State != wantState || !reflect.DeepEqual(result.Pending, wantPending) || !reflect.DeepEqual(result.Uploaded, []AssetIdentity{identity(assets[1])}) {
t.Fatalf("result = %#v, error %v; want pending %#v", result, err, wantPending)
}
})
}
}
func TestUploadMissingAssetsBorrowsReaderAndClosesItAfterCall(t *testing.T) {
filePath := t.TempDir() + "/asset.bin"
if err := os.WriteFile(filePath, []byte("asset"), 0o600); err != nil {
t.Fatal(err)
}
asset := artifact.ExpectedAsset{Filename: "asset.bin", SHA256: assetDigest([]byte("asset")), Size: 5, Path: filePath}
backend := &assetBackend{uploads: []assetUploadResult{{evidence: forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}}}}
result, err := uploadMissingAssets(context.Background(), backend, "release", inspectionFor([]artifact.ExpectedAsset{asset}, map[string]AssetState{"asset.bin": AssetMissing}))
if err != nil || result.State != Complete || !backend.readerWasOpen {
t.Fatalf("uploadMissingAssets() = %#v, error %v, reader open during call %v", result, err, backend.readerWasOpen)
}
if backend.borrowed == nil {
t.Fatal("backend did not receive the file reader")
}
if _, err := backend.borrowed.Stat(); !errors.Is(err, os.ErrClosed) {
t.Fatalf("borrowed file stat error = %v, want closed file", err)
}
}
type assetListResult struct {
assets []forge.Asset
err error
}
type assetUploadResult struct {
evidence forge.WriteEvidence
err error
}
type assetBackend struct {
pageBackend
lists []assetListResult
listCalls int
content map[string][]byte
openErrors map[string]error
opened []*trackedAssetStream
uploads []assetUploadResult
uploadNames []string
uploadContent [][]byte
borrowed *os.File
readerWasOpen bool
}
func (backend *assetBackend) ListAssets(context.Context, any) ([]forge.Asset, error) {
index := backend.listCalls
backend.listCalls++
if index >= len(backend.lists) {
return nil, errors.New("unexpected asset listing")
}
result := backend.lists[index]
return result.assets, result.err
}
func (backend *assetBackend) OpenAsset(_ context.Context, handle any) (io.ReadCloser, error) {
key, ok := handle.(string)
if !ok {
return nil, errors.New("unexpected asset handle")
}
if err := backend.openErrors[key]; err != nil {
return nil, err
}
stream := &trackedAssetStream{Reader: bytes.NewReader(backend.content[key])}
backend.opened = append(backend.opened, stream)
return stream, nil
}
func (backend *assetBackend) UploadAsset(_ context.Context, _ any, filename string, content io.Reader) (forge.WriteEvidence, error) {
backend.uploadNames = append(backend.uploadNames, filename)
if file, ok := content.(*os.File); ok {
backend.borrowed = file
}
data, err := io.ReadAll(content)
backend.uploadContent = append(backend.uploadContent, data)
if backend.borrowed != nil {
_, statErr := backend.borrowed.Stat()
backend.readerWasOpen = statErr == nil
}
index := len(backend.uploadNames) - 1
if err != nil {
return forge.WriteEvidence{Attempted: true, Disposition: forge.WriteUncertain}, err
}
if index >= len(backend.uploads) {
return forge.WriteEvidence{Attempted: true, Disposition: forge.WriteAccepted}, nil
}
result := backend.uploads[index]
return result.evidence, result.err
}
type trackedAssetStream struct {
*bytes.Reader
closed bool
}
func (stream *trackedAssetStream) Close() error {
stream.closed = true
return nil
}
func expectedAsset(filename string, content []byte) artifact.ExpectedAsset {
return artifact.ExpectedAsset{Filename: filename, SHA256: assetDigest(content), Size: int64(len(content)), Content: content}
}
func inspectionFor(assets []artifact.ExpectedAsset, states map[string]AssetState) Inspection {
inspection := Inspection{Assets: make([]AssetInspection, 0, len(assets))}
for _, item := range assets {
inspection.Assets = append(inspection.Assets, AssetInspection{Expected: item, State: states[item.Filename]})
}
return inspection
}
func failureKindForDisposition(disposition forge.WriteDisposition) forge.FailureKind {
if disposition == forge.WriteConflict {
return forge.FailureConflict
}
return forge.FailureTransport
}

153
internal/forge/forge.go Normal file
View File

@@ -0,0 +1,153 @@
// Package forge defines the backend-neutral operations used by hosted delivery.
package forge
import (
"context"
"io"
)
// Backend provides the hosted operations needed by the shared delivery
// workflow. Implementations own destination-specific rules and protocol
// details; the shared workflow uses only the logical values and evidence in
// this package.
type Backend interface {
// Preflight verifies credentials and access to the configured destination
// using read-only operations. It does not depend on a source tag or release.
Preflight(ctx context.Context) error
// TagCommit returns the commit observed for the complete tag.
TagCommit(ctx context.Context, tag string) (string, error)
// FindRelease returns the release for the complete tag. A missing release
// is reported with FailureNotFound.
FindRelease(ctx context.Context, tag string) (Release, error)
// CreateRelease creates the requested release and returns the protocol
// evidence even when an error occurs.
CreateRelease(ctx context.Context, request CreateReleaseRequest) (Release, WriteEvidence, error)
// ListAssets returns the assets attached to the release identified by handle.
ListAssets(ctx context.Context, releaseHandle any) ([]Asset, error)
// OpenAsset opens the remote asset identified by handle. The caller owns and
// must close the returned stream, including when reading it fails.
OpenAsset(ctx context.Context, assetHandle any) (io.ReadCloser, error)
// UploadAsset uploads content to the release identified by handle. The
// backend borrows content for the duration of this call and must finish any
// request or multipart work before returning; it must not close content.
UploadAsset(ctx context.Context, releaseHandle any, filename string, content io.Reader) (WriteEvidence, error)
}
// Release contains the logical release properties used by shared delivery.
// Handle is opaque to shared code and is interpreted only by the backend that
// produced it.
type Release struct {
URL string
Tag string
Title string
Body string
Draft bool
Prerelease bool
Handle any
}
// CreateReleaseRequest contains the release properties requested by shared
// delivery.
type CreateReleaseRequest struct {
Tag string
Commit string
Title string
Body string
Draft bool
Prerelease bool
}
// Asset contains the remote properties needed to compare an attachment with a
// declared local asset. Handle is opaque to shared code and is interpreted only
// by the backend that produced it.
type Asset struct {
Filename string
Size int64
Handle any
}
// PreflightFailureKind classifies a failure to verify destination settings,
// credentials, or repository access.
type PreflightFailureKind string
const (
PreflightInvalidDestination PreflightFailureKind = "invalid_destination"
PreflightMissingCredential PreflightFailureKind = "missing_credential"
PreflightInvalidCredential PreflightFailureKind = "invalid_credential"
PreflightInsufficientPermissions PreflightFailureKind = "insufficient_permissions"
PreflightInaccessibleDestination PreflightFailureKind = "inaccessible_destination"
PreflightUnavailable PreflightFailureKind = "unavailable"
)
// PreflightFailure reports a classified credential or destination access
// failure. Err retains the underlying cause for diagnostics and cancellation
// identity.
type PreflightFailure struct {
Kind PreflightFailureKind
Err error
}
func (f *PreflightFailure) Error() string {
if f.Err != nil {
return string(f.Kind) + ": " + f.Err.Error()
}
return string(f.Kind)
}
// Unwrap returns the cause of the preflight failure, if any.
func (f *PreflightFailure) Unwrap() error { return f.Err }
// FailureKind classifies a backend-neutral delivery operation failure.
type FailureKind string
const (
FailureInvalid FailureKind = "invalid_request"
FailureNotFound FailureKind = "not_found"
FailureUnauthorized FailureKind = "unauthorized"
FailureConflict FailureKind = "conflict"
FailureMalformed FailureKind = "malformed_response"
FailureUnverifiable FailureKind = "unverifiable"
FailureTransport FailureKind = "transport"
FailureRejected FailureKind = "rejected"
FailureUnknown FailureKind = "unknown"
)
// Failure reports a backend-neutral operation failure. Backend-specific
// status and operation details belong in Err. Err is retained for errors.Is
// and errors.As inspection.
type Failure struct {
Kind FailureKind
Err error
}
func (f *Failure) Error() string {
if f.Err != nil {
return string(f.Kind) + ": " + f.Err.Error()
}
return string(f.Kind)
}
// Unwrap returns the cause of the operation failure, if any.
func (f *Failure) Unwrap() error { return f.Err }
// WriteDisposition describes the backend's evidence about a write operation.
type WriteDisposition string
const (
WriteNotAttempted WriteDisposition = "not_attempted"
WriteAccepted WriteDisposition = "accepted"
WriteRejected WriteDisposition = "rejected"
WriteConflict WriteDisposition = "conflict"
WriteUncertain WriteDisposition = "uncertain"
)
// WriteEvidence records whether a write was handed to the transport and what
// its acknowledgment establishes. Accepted means the backend received and
// decoded the required protocol acknowledgment; shared content checks still
// apply. Uncertain means the outcome could not be established. Attempted marks
// handoff to the transport and does not claim the server received the request.
// Evidence remains meaningful when the operation also returns an error.
type WriteEvidence struct {
Attempted bool
Disposition WriteDisposition
}

226
internal/git/blob_reader.go Normal file
View File

@@ -0,0 +1,226 @@
package git
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"os/exec"
"strconv"
"strings"
"sync"
"go.maximumdirect.net/releasekit/internal/process"
)
var errBlobObjectMissing = errors.New("Git object is missing")
// BlobReader reads requested blobs through one lazy git cat-file --batch
// process. Reads are serialized; callers must close the reader when finished.
type BlobReader struct {
repositoryDir string
parent context.Context
mu sync.Mutex
child *process.PipedProcess
stdout *bufio.Reader
stderr bytes.Buffer
closed bool
aborted bool
terminal error
closeErr error
}
// NewBlobReader creates a lazy reader for one repository. It starts no child
// process until the first valid blob is requested.
func NewBlobReader(ctx context.Context, repositoryDir string) *BlobReader {
return &BlobReader{repositoryDir: repositoryDir, parent: ctx}
}
// Read returns one blob body from the candidate repository. The returned bytes
// are newly allocated and owned by the caller.
func (reader *BlobReader) Read(ctx context.Context, objectID string) ([]byte, error) {
if !validObjectID(objectID) {
return nil, fmt.Errorf("invalid blob object ID %q", objectID)
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
}
reader.mu.Lock()
defer reader.mu.Unlock()
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
}
if reader.terminal != nil {
return nil, reader.terminal
}
if reader.closed {
return nil, fmt.Errorf("read blob %s: Git blob reader is closed", objectID)
}
if err := reader.startLocked(); err != nil {
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
}
child := reader.child
callbackDone := make(chan struct{})
stopCancellation := context.AfterFunc(ctx, func() {
defer close(callbackDone)
child.Cancel()
_ = child.Stdin().Close()
_ = child.Stdout().Close()
})
body, err := reader.exchange(objectID)
if !stopCancellation() {
<-callbackDone
}
if contextErr := ctx.Err(); contextErr != nil {
err = contextErr
} else if contextErr := reader.parent.Err(); contextErr != nil {
err = contextErr
}
if errors.Is(err, errBlobObjectMissing) {
return nil, err
}
if err != nil {
return nil, reader.abortLocked(objectID, err)
}
return body, nil
}
// Close closes a healthy session cleanly or reaps an aborted session. It is
// safe to call more than once.
func (reader *BlobReader) Close() error {
reader.mu.Lock()
defer reader.mu.Unlock()
if reader.closed {
return reader.closeErr
}
reader.closed = true
if reader.aborted {
reader.closeErr = reader.terminal
return reader.closeErr
}
if reader.child == nil {
return nil
}
if err := reader.child.Stdin().Close(); err != nil {
reader.closeErr = reader.abortLocked("", fmt.Errorf("close Git cat-file input: %w", err))
return reader.closeErr
}
if _, err := io.Copy(io.Discard, reader.child.Stdout()); err != nil {
reader.closeErr = reader.abortLocked("", fmt.Errorf("finish Git cat-file output: %w", err))
return reader.closeErr
}
if err := reader.child.Wait(); err != nil {
reader.closeErr = reader.processError("close Git cat-file batch", err)
}
return reader.closeErr
}
func (reader *BlobReader) startLocked() error {
if reader.child != nil {
return nil
}
if err := reader.parent.Err(); err != nil {
return err
}
child, err := process.StartPiped(reader.parent, process.Invocation{
Args: []string{"git", "cat-file", "--batch"},
Dir: reader.repositoryDir,
Env: map[string]string{
"GIT_NO_LAZY_FETCH": "1",
"GIT_ALLOW_PROTOCOL": "",
"GIT_NO_REPLACE_OBJECTS": "1",
},
Stderr: &reader.stderr,
})
if err != nil {
return err
}
reader.child = child
reader.stdout = bufio.NewReader(child.Stdout())
return nil
}
func (reader *BlobReader) exchange(objectID string) ([]byte, error) {
if _, err := io.WriteString(reader.child.Stdin(), objectID+"\n"); err != nil {
return nil, fmt.Errorf("write object request: %w", err)
}
header, err := reader.stdout.ReadString('\n')
if err != nil {
return nil, fmt.Errorf("read object header: %w", err)
}
fields := strings.Fields(strings.TrimSuffix(header, "\n"))
if len(fields) == 2 && strings.EqualFold(fields[0], objectID) && fields[1] == "missing" {
return nil, fmt.Errorf("read blob %s: %w", objectID, errBlobObjectMissing)
}
if len(fields) != 3 {
return nil, fmt.Errorf("invalid Git blob header %q", strings.TrimSuffix(header, "\n"))
}
if !strings.EqualFold(fields[0], objectID) {
return nil, fmt.Errorf("Git blob response object ID %q does not match request %q", fields[0], objectID)
}
if fields[1] != "blob" {
return nil, fmt.Errorf("Git object %s has type %q, want blob", objectID, fields[1])
}
size, err := strconv.ParseInt(fields[2], 10, strconv.IntSize)
if err != nil || size < 0 {
if err == nil {
err = errors.New("negative object size")
}
return nil, fmt.Errorf("invalid Git blob size %q: %w", fields[2], err)
}
body := make([]byte, int(size))
if _, err := io.ReadFull(reader.stdout, body); err != nil {
return nil, fmt.Errorf("read %d-byte Git blob body: %w", size, err)
}
framing, err := reader.stdout.ReadByte()
if err != nil {
return nil, fmt.Errorf("read Git blob framing: %w", err)
}
if framing != '\n' {
return nil, fmt.Errorf("invalid Git blob framing byte %q", framing)
}
return body, nil
}
func (reader *BlobReader) abortLocked(objectID string, cause error) error {
if reader.aborted {
return reader.terminal
}
reader.aborted = true
var waitErr error
if reader.child != nil {
reader.child.Cancel()
_ = reader.child.Stdin().Close()
_ = reader.child.Stdout().Close()
waitErr = reader.child.Wait()
}
if contextErr := reader.parent.Err(); contextErr != nil {
cause = contextErr
}
reader.terminal = reader.processError("read blob "+objectID, errors.Join(cause, relevantProcessError(waitErr, cause)))
return reader.terminal
}
func (reader *BlobReader) processError(operation string, cause error) error {
message := strings.TrimSpace(reader.stderr.String())
if message != "" {
return fmt.Errorf("%s: %s: %w", operation, message, cause)
}
return fmt.Errorf("%s: %w", operation, cause)
}
func relevantProcessError(waitErr, cause error) error {
if waitErr == nil || errors.Is(cause, context.Canceled) || errors.Is(cause, context.DeadlineExceeded) {
return nil
}
var exitErr *exec.ExitError
if errors.As(waitErr, &exitErr) && exitErr.ExitCode() == -1 {
return nil
}
return waitErr
}

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