114 Commits
v0.2.0 ... main

Author SHA1 Message Date
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
165 changed files with 14002 additions and 3208 deletions

View File

@@ -18,8 +18,3 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
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
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
and installation commands.
The Go module is `go.maximumdirect.net/releasekit`. The
[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:
@@ -42,6 +56,8 @@ failure recovery.
## 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
policy reading.
- [CLI contract](docs/cli.md): the `version`, `check`, `publish`, `build`,
@@ -65,6 +81,8 @@ failure recovery.
components and their responsibilities.
- [Architecture policy](docs/policy/architecture.md): responsibility and dependency
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.
- [Policy provenance](docs/policy/meta.md): adopted policy sources and update
guidance.

View File

@@ -2,9 +2,14 @@ package releasekit
import (
"context"
"fmt"
"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.
@@ -22,11 +27,14 @@ type BuildSpec struct {
// BuildRequest contains the source and output settings for Build.
type BuildRequest struct {
RepositoryDir string // source repository whose current HEAD is recorded.
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
Spec BuildSpec // application package, artifact name, and targets.
OutputDir string // output location; empty selects <repository>/dist.
Output io.Writer // optional build progress destination.
RepositoryDir string // directory within the source Git checkout whose HEAD is recorded.
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
ModuleDir string
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.
@@ -40,6 +48,9 @@ type BuildArtifact struct {
// BuildResult describes the source and artifacts reached by Build.
type BuildResult struct {
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.
// SourceVerified reports clean source and the same HEAD observed before and
// 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.
}
// Build compiles the selected targets with Version injected through buildinfo.
// It uses the available compatible local Go toolchain, applies ReleaseKit's
// readonly offline build settings, preserves effective cache and tool settings,
// and verifies the version command on the Go host before succeeding. An empty
// target set records source identity without running the Go toolchain. Errors
// return partial build facts in the result.
// Build resolves the selected module's working-tree identity, then compiles the
// selected targets with Version injected through buildinfo. It uses the
// available compatible local Go toolchain, applies ReleaseKit's readonly
// offline build settings, preserves effective cache and tool settings, and
// verifies the version command on the Go host before succeeding. Relative
// 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) {
result, err := internalbuild.Build(ctx, internalbuild.Request{
RepositoryDir: request.RepositoryDir,
Version: request.Version,
Spec: *internalBuildSpec(&request.Spec),
OutputDir: request.OutputDir,
Output: request.Output,
spec := *internalBuildSpec(&request.Spec)
result := internalbuild.Result{Version: request.Version}
failure := func(err error) (BuildResult, error) {
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
return publicBuildResult(result), err
}
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{
RepositoryDir: result.RepositoryDir,
ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath,
Tag: result.Tag,
CandidateCommit: result.CandidateCommit,
SourceVerified: result.SourceVerified,
Version: result.Version,
MainPackage: result.MainPackage,
BinaryName: result.BinaryName,
MainPackage: result.Settings.MainPackage,
BinaryName: result.Settings.BinaryName,
OutputDir: result.OutputDir,
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)),
}
for _, target := range result.Targets {
for _, target := range result.Settings.Targets {
public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch})
}
for _, artifact := range result.Artifacts {
@@ -90,7 +128,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
SHA256: artifact.SHA256,
})
}
return public, err
return public
}
func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
@@ -105,8 +143,10 @@ func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
}
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}
for _, target := range result.Targets {
input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, MainPackage: settings.MainPackage, BinaryName: settings.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler}
for _, target := range settings.Targets {
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
}
for _, artifact := range result.Artifacts {

View File

@@ -15,9 +15,32 @@ import (
"testing"
"time"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
releasekit "go.maximumdirect.net/releasekit"
)
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) {
repository := newBuildConsumer(t, `package main
@@ -25,7 +48,7 @@ import (
"fmt"
"os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() {
@@ -104,7 +127,7 @@ func TestBuildUsesGoHostDespiteAmbientTargetEnvironment(t *testing.T) {
import (
"fmt"
"os"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() {
@@ -115,7 +138,7 @@ func main() {
t.Setenv("GOARCH", "arm64")
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
Version: "v2.3.4",
Version: "v1.2.3",
Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app",
BinaryName: "fixture",
@@ -126,7 +149,7 @@ func main() {
if err != nil {
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)
}
}
@@ -136,7 +159,7 @@ func TestBuildIgnoresAmbientAndPersistentArchitectureTuning(t *testing.T) {
import (
"fmt"
"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()) } }
`)
@@ -166,7 +189,7 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixt
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
RepositoryDir: repository,
Version: "v2.3.4",
Version: "v1.2.3",
Spec: releasekit.BuildSpec{
MainPackage: "./cmd/app",
BinaryName: "fixture",
@@ -242,9 +265,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) {
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())}
`
repository := newBuildConsumer(t, source)
@@ -432,6 +594,21 @@ func TestBuildCancellationReturnsCompletedArtifacts(t *testing.T) {
func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.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")
gitRun(t, repository.work, "add", "guide.md")
gitRun(t, repository.work, "commit", "-m", "add Markdown guide")
@@ -439,7 +616,7 @@ func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
import (
"fmt"
"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()) } }
`)
@@ -465,6 +642,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") {
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 != "" {
t.Fatalf("candidate build dirtied worktree: %s", got)
}
@@ -516,7 +713,7 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
if err != nil {
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, "cmd/app/main.go", mainSource)
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
@@ -528,13 +725,25 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
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) {
t.Helper()
root, err := filepath.Abs(".")
if err != nil {
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, ".gitignore", "dist/\n")
writeFile(t, repository, "cmd/app/main.go", mainSource)
@@ -568,7 +777,7 @@ func buildGit(t *testing.T, directory string, args ...string) string {
func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) {
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())} }
`
for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} {
@@ -606,7 +815,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, "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 {
t.Fatalf("dirty source delivered: %#v %v", delivered, err)
}
@@ -629,7 +838,7 @@ func TestCandidateBuildDoesNotRequireWritableRepositoryParent(t *testing.T) {
t.Skip("requires ordinary Unix permission checks")
}
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())}
`)
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")

View File

@@ -2,7 +2,7 @@
// built with ReleaseKit.
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,
// it returns the executable's main module version, or "dev" when that metadata

View File

@@ -7,7 +7,7 @@ import (
"path/filepath"
"testing"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
func TestVersionInConsumerExecutable(t *testing.T) {
@@ -19,11 +19,11 @@ func TestVersionInConsumerExecutable(t *testing.T) {
dir := t.TempDir()
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))
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil {
t.Fatal(err)
@@ -32,7 +32,7 @@ replace gitea.maximumdirect.net/eric/ReleaseKit => %s
import (
"fmt"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
"go.maximumdirect.net/releasekit/buildinfo"
)
func main() { fmt.Print(buildinfo.Version()) }

View File

@@ -4,10 +4,10 @@ import (
"context"
"io"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
"go.maximumdirect.net/releasekit/internal/candidate"
"go.maximumdirect.net/releasekit/internal/publish"
"go.maximumdirect.net/releasekit/internal/validation"
)
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH.
@@ -18,21 +18,30 @@ var ErrInvalidVersion = candidate.ErrInvalidVersion
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
// 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 {
RepositoryDir string
ModuleDir string
ModulePath string
Tag string
Commit string
Version string
Version string // selected stable semantic version.
}
// ReleaseRequest contains the inputs used to validate and optionally build one
// local candidate. Remote is retained for publication operations; Check makes
// no remote availability claim.
type ReleaseRequest struct {
// RepositoryDir names a directory within the source Git checkout. Operations
// resolve its root before applying repository-relative selections.
RepositoryDir string
Product string
Version string
Remote string
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
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
// this string exactly before validation or tag creation. Check ignores this
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
@@ -46,9 +55,24 @@ type ReleaseRequest struct {
}
// 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 {
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
// does not modify repository contents and is disabled when false.
GoFormat bool
@@ -76,7 +100,7 @@ type FileSizeValidationSpec struct {
// LimitBytes is the maximum decimal byte count. Nil selects 1,000,000;
// zero is a zero-byte limit, and negative values are invalid.
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.
Exclusions []string
}
@@ -88,7 +112,8 @@ type ModuleDistributionValidationSpec struct {
// nested paths and symlink entries. It does not select Go's test workspace.
WorkspaceFiles bool
// 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
}
@@ -107,21 +132,26 @@ type GoValidationSpec struct {
}
// Check validates one local, committed release candidate. It requires a clean
// worktree and index on main, a committed note matching Product and Version,
// and an unused local tag. It always runs the offline Go test suite with the
// available compatible local Go toolchain and Go host target, then calls
// worktree and index on main, a selected module declaration and module-local
// committed note matching Product and Version, and an unused local tag. An
// 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
// 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
// each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package
// 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
// Go checks and before AdditionalChecks. Its zero value disables formatting.
// Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace
// files after formatting. Its zero value disables that distribution check and
// does not change Go's workspace environment.
// 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.
// Validation.FileSize checks each selected committed blob after module
// 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) {
checked, err := candidate.Check(ctx, candidateRequest(request))
if err != nil {
return Candidate{}, convertValidationError(err)
return publicCandidate(checked), convertValidationError(err)
}
return publicCandidate(checked), nil
}
func publicCandidate(checked candidate.Candidate) Candidate {
return Candidate{
RepositoryDir: checked.RepositoryDir,
ModuleDir: checked.ModuleDir,
ModulePath: checked.ModulePath,
Tag: checked.Tag,
Commit: checked.Commit,
Version: checked.Version,
}, nil
}
}
func candidateRequest(request ReleaseRequest) candidate.Request {
fileSize := internalFileSizeSettings(request.Validation.FileSize)
result := candidate.Request{
RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir,
Product: request.Product,
Version: request.Version,
Validation: validation.Settings{
Race: request.Validation.Go.Race,
FullVet: request.Validation.Go.FullVet,
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
ForbiddenFiles: copyStringSlice(request.Validation.ForbiddenFiles),
GoFormat: request.Validation.GoFormat,
Markdown: internalMarkdownSettings(request.Validation.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
@@ -176,6 +216,13 @@ func candidateRequest(request ReleaseRequest) candidate.Request {
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 {
if spec == nil {
return nil
@@ -203,10 +250,6 @@ func candidateChecks(checks func(context.Context, Candidate) error) func(context
return nil
}
return func(ctx context.Context, captured candidate.Candidate) error {
return checks(ctx, Candidate{
RepositoryDir: captured.RepositoryDir,
Commit: captured.Commit,
Version: captured.Version,
})
return checks(ctx, publicCandidate(captured))
}
}

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"
"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
@@ -31,14 +32,17 @@ const (
// Invocation contains parsed command settings owned by the CLI adapter.
type Invocation struct {
Command Command
Repository string
ConfigPath string
OutputDir string
AssetsDir string
Remote string
Commit string
Version string
Command Command
Repository string
ConfigPath string
OutputDir string
AssetsDir string
Remote string
Commit string
Version string
ExpectedModule string
ExpectedTag string
Prepared bool
}
// 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")
}
var remote *string
expectedModule := ""
if action == PublishAction || action == CIDeliveryAction {
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
}
expectedCommit := ""
prepared := false
if action == CIDeliveryAction {
remote = flags.String("remote", "origin", "Git remote")
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 {
return Invocation{}, err
@@ -84,11 +94,25 @@ func Parse(args []string) (Invocation, error) {
if action == CIDeliveryAction && !validGitObjectID(expectedCommit) {
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 := ""
if remote != nil {
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:
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.
type Settings struct {
Product string `json:"product"`
ModuleDir string `json:"module_dir,omitempty"`
Remote string `json:"remote,omitempty"`
ExpectedPushURL string `json:"expected_push_url,omitempty"`
Checks []CheckCommand `json:"checks,omitempty"`
@@ -126,7 +151,11 @@ type Settings struct {
// ValidationSettings selects shared candidate checks in a release profile.
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.
// Omitted or false disables the check.
GoFormat bool `json:"go_format,omitempty"`
@@ -167,12 +196,14 @@ type GoValidationSettings struct {
CompileTargets []string `json:"compile_targets,omitempty"`
}
// DeliverySettings selects the hosted Gitea release destination.
// DeliverySettings selects the hosted forge release destination.
type DeliverySettings struct {
Forge string `json:"forge,omitempty"`
BaseURL string `json:"base_url"`
Owner string `json:"owner"`
Repository string `json:"repository"`
TokenEnv string `json:"token_env,omitempty"`
TokenFile string `json:"token_file,omitempty"`
}
// BuildSettings selects the Go application package, artifact name, and targets.
@@ -269,9 +300,9 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
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.
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 {
environment := make(map[string]string, len(check.Env)+len(ownedEnv))
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{
Args: check.Args,
Dir: repoDir,
Dir: dir,
Env: environment,
Stdout: stdout,
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" {
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"})
if err != nil {
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" {
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 {
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)
}
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") {
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 {
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) {
repoDir := t.TempDir()
profilePath := filepath.Join(repoDir, "releasekit.json")

View File

@@ -2,7 +2,6 @@ package cli
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -11,11 +10,13 @@ import (
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
)
const BuildReceiptName = ".releasekit-build.json"
const BuildReceiptSchemaVersion = 1
type ReceiptTarget struct {
OS string `json:"os"`
@@ -31,7 +32,11 @@ type ReceiptArtifact struct {
// BuildReceipt is private local coordination data for generated binaries.
type BuildReceipt struct {
SchemaVersion int `json:"schema_version"`
RepositoryDir string `json:"repository_dir"`
ModuleDir string `json:"module_dir"`
ModulePath string `json:"module_path"`
Tag string `json:"tag"`
CandidateCommit string `json:"candidate_commit"`
SourceVerified bool `json:"source_verified"`
Version string `json:"version"`
@@ -49,7 +54,7 @@ func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
return "", fmt.Errorf("resolve build receipt directory: %w", err)
}
receipt.OutputDir = resolvedDir
if err := validateBuildReceipt(receipt, true); err != nil {
if err := validateBuildReceipt(receipt); err != nil {
return "", err
}
contents, err := json.MarshalIndent(receipt, "", " ")
@@ -111,41 +116,62 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
}
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
}
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 receipt, nil
}
func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool {
resolvedRepo, err := filepath.Abs(repositoryDir)
if err != nil || filepath.Clean(receipt.RepositoryDir) != filepath.Clean(resolvedRepo) {
if !sameDirectory(receipt.RepositoryDir, repositoryDir) {
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
}
want := normalizeReceiptTargets(settings.Targets)
if len(want) != len(receipt.Targets) {
want := artifact.NormalizeSettings(settings.MainPackage, settings.BinaryName, parseReceiptTargets(settings.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
}
for i, target := range want {
if target != receipt.Targets[i] {
for i, target := range want.Targets {
if target != got.Targets[i] {
return false
}
}
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) {
return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
}
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository and output directories must be absolute")
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository, module, and output directories must be absolute")
}
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
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) {
return errors.New("build receipt has invalid candidate commit")
@@ -191,39 +217,38 @@ func validateBuildReceipt(receipt BuildReceipt, verifyFiles bool) error {
if !validSHA256(artifact.SHA256) {
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
}
func verifyReceiptArtifact(artifact ReceiptArtifact) error {
info, err := os.Lstat(artifact.Path)
func validateRecordedIdentity(receipt BuildReceipt) error {
repositoryDir := filepath.Clean(receipt.RepositoryDir)
moduleDir := filepath.Clean(receipt.ModuleDir)
relative, err := filepath.Rel(repositoryDir, moduleDir)
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() {
return fmt.Errorf("build artifact %q is not a regular file", artifact.Path)
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
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 {
return fmt.Errorf("open build artifact %q: %w", artifact.Path, err)
return err
}
defer file.Close()
hash := sha256.New()
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)
if identity.Tag != receipt.Tag {
return fmt.Errorf("full tag %q does not match module selection and version; want %q", receipt.Tag, identity.Tag)
}
return nil
}
func normalizeReceiptTargets(targets []string) []ReceiptTarget {
func parseReceiptTargets(targets []string) []artifact.Target {
parsed := make([]artifact.Target, 0, len(targets))
for _, value := range targets {
goos, goarch, ok := strings.Cut(value, "/")
@@ -232,12 +257,15 @@ func normalizeReceiptTargets(targets []string) []ReceiptTarget {
}
parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch})
}
normalized := artifact.NormalizeTargets(parsed)
result := make([]ReceiptTarget, 0, len(normalized))
for _, target := range normalized {
result = append(result, ReceiptTarget{OS: target.OS, Arch: target.Arch})
return parsed
}
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 {

View File

@@ -3,62 +3,103 @@ package cli
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func TestBuildReceiptRoundTripBindsFilesAndBuildInputs(t *testing.T) {
outputDir := t.TempDir()
repositoryDir := t.TempDir()
filename := "example-v1.2.3-linux-amd64"
artifactPath := filepath.Join(outputDir, filename)
contents := []byte("built application")
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(contents)
receipt := BuildReceipt{
RepositoryDir: repositoryDir,
CandidateCommit: strings.Repeat("a", 40),
Version: "v1.2.3",
MainPackage: "./cmd/example",
BinaryName: "example",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
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)
}
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 || !strings.Contains(err.Error(), "hash changed") {
t.Fatalf("LoadBuildReceipt() error = %v, want changed-file hash error", err)
func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
for _, test := range []struct {
name string
moduleDir string
modulePath string
tag string
}{
{name: "root", moduleDir: ".", modulePath: "example.com/receipt", tag: "v1.2.3"},
{name: "nested", moduleDir: "integrations/ckconfig", modulePath: "example.com/ckconfig", tag: "integrations/ckconfig/v1.2.3"},
} {
t.Run(test.name, func(t *testing.T) {
outputDir := t.TempDir()
repositoryDir := t.TempDir()
moduleDir := repositoryDir
if test.moduleDir != "." {
moduleDir = filepath.Join(repositoryDir, filepath.FromSlash(test.moduleDir))
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
t.Fatal(err)
}
}
filename := "example-v1.2.3-linux-amd64"
artifactPath := filepath.Join(outputDir, filename)
contents := []byte("built application")
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(contents)
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion,
RepositoryDir: repositoryDir,
ModuleDir: moduleDir,
ModulePath: test.modulePath,
Tag: test.tag,
CandidateCommit: strings.Repeat("a", 40),
Version: "v1.2.3",
MainPackage: "./cmd/example",
BinaryName: "example",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
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 +109,9 @@ func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
body 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"},
} {
t.Run(test.name, func(t *testing.T) {
@@ -82,3 +125,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"
"syscall"
"gitea.maximumdirect.net/eric/ReleaseKit"
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit"
"go.maximumdirect.net/releasekit/buildinfo"
"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() {
@@ -29,6 +32,13 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage)
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 {
case cli.VersionCommand:
@@ -42,11 +52,15 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
}
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 %s\n", invocation.Version)
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 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))
fmt.Fprintf(stderr, "publication state=%s phase=%s module=%s module-dir=%s version=%s tag=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.TagObject, result.Endpoint, candidateFailureText(err))
if errors.Is(err, releasekit.ErrInvalidVersion) {
return 2
}
@@ -55,18 +69,18 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
}
return 1
}
fmt.Fprintf(stdout, "published %s at %s (tag object %s)\n", result.Version, result.CandidateCommit, result.TagObject)
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: %s\n", candidateFailureText(err))
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 %s at %s is valid\n", candidate.Version, candidate.Commit)
fmt.Fprintf(stdout, "local candidate module %s version %s tag %s at %s is valid\n", candidate.ModulePath, candidate.Version, candidate.Tag, candidate.Commit)
return 0
case cli.BuildAction:
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
@@ -80,6 +94,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
}
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
Version: invocation.Version,
Spec: *configuredBuildSpec(settings.Build),
OutputDir: invocation.OutputDir,
@@ -92,7 +107,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
}
}
if err != nil {
fmt.Fprintf(stderr, "build failed at %s: %v\n", result.CandidateCommit, err)
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)
}
@@ -102,7 +117,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
return 1
}
if len(result.Targets) == 0 {
fmt.Fprintf(stdout, "no build targets selected for %s at %s\n", result.Version, result.CandidateCommit)
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)
@@ -120,7 +135,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
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)
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)
}
@@ -137,6 +152,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
request := releasekit.ReleaseRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
Product: settings.Product,
Version: invocation.Version,
Remote: settings.Remote,
@@ -147,9 +163,13 @@ func candidateRequest(invocation cli.Invocation, settings cli.Settings, output i
if len(settings.Checks) != 0 {
checks := settings.Checks
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
return cli.RunChecks(ctx, candidate.RepositoryDir, checks, map[string]string{
"RELEASEKIT_VERSION": candidate.Version,
"RELEASEKIT_CANDIDATE": candidate.Commit,
return cli.RunChecks(ctx, candidate.ModuleDir, checks, map[string]string{
"RELEASEKIT_VERSION": candidate.Version,
"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)
}
}
@@ -161,7 +181,9 @@ func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec
return releasekit.ValidationSpec{}
}
result := releasekit.ValidationSpec{
GoFormat: settings.GoFormat,
SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles),
ForbiddenFiles: copyStringsPreservingEmpty(settings.ForbiddenFiles),
GoFormat: settings.GoFormat,
ModuleDistribution: releasekit.ModuleDistributionValidationSpec{
WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles,
LocalReplacements: settings.ModuleDistribution.LocalReplacements,
@@ -199,6 +221,42 @@ func candidateFailureText(err error) string {
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 {
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil {
@@ -211,9 +269,10 @@ func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr
func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
RepositoryDir: invocation.Repository,
Version: invocation.Version,
Tag: invocation.ExpectedTag,
Remote: invocation.Remote,
ExpectedCommit: invocation.Commit,
VerifyOnly: invocation.Prepared,
})
if err != nil {
fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err)
@@ -228,12 +287,32 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
fmt.Fprintf(stderr, "load profile: %v\n", err)
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 {
return status
}
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)
return 1
}
@@ -244,32 +323,61 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
// deliverWithSettings adapts prepared CLI state to the public delivery facade.
// 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 {
destination, status := deliveryDestination(settings, stderr)
destination, status := deliveryDestination(invocation.Repository, settings, stderr)
if status != 0 {
return status
}
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
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")
return releasekit.GiteaDestination{}, 2
return releasekit.DeliveryDestination{}, 2
}
tokenEnv := delivery.TokenEnv
if strings.TrimSpace(tokenEnv) == "" {
tokenEnv = "RELEASEKIT_GITEA_TOKEN"
}
token, ok := os.LookupEnv(tokenEnv)
if !ok || strings.TrimSpace(token) == "" {
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
return releasekit.GiteaDestination{}, 2
if (!ok || strings.TrimSpace(token) == "") && delivery.TokenFile != "" {
name := delivery.TokenFile
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
if invocation.AssetsDir != "" && !hasTargets {
fmt.Fprintln(stderr, "--assets requires build targets in the profile")
@@ -282,10 +390,17 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
}
if hasTargets {
if invocation.AssetsDir != "" {
assetsDir := invocation.AssetsDir
if !filepath.IsAbs(assetsDir) {
assetsDir = filepath.Join(invocation.Repository, assetsDir)
commit, err := git.CaptureHead(ctx, invocation.Repository)
if err != nil {
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))
if err != nil {
fmt.Fprintf(stderr, "load verified build receipt: %v\n", err)
@@ -301,26 +416,32 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir,
Product: settings.Product,
Version: invocation.Version,
ExpectedTag: invocation.ExpectedTag,
Destination: destination,
Build: buildSpec,
Prebuilt: prebuilt,
Output: stderr,
})
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)
fmt.Fprintf(stderr, "delivery state=%s module=%s module-dir=%s version=%s tag=%s commit=%s url=%s: %v\n", result.State, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.ReleaseURL, err)
writeDeliveryAssets(stderr, result)
writeDeliveryRecovery(stderr, result)
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
}
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 != "" {
fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL)
}
@@ -328,6 +449,23 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
return 0
}
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) {
for _, group := range []struct {
label string
@@ -342,13 +480,13 @@ func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
switch result.State {
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:
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:
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:
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:
return
}
@@ -359,7 +497,8 @@ func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
func buildResultFromReceipt(receipt cli.BuildReceipt) *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,
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
}
@@ -393,7 +532,11 @@ func configuredBuildSpec(settings *cli.BuildSettings) *releasekit.BuildSpec {
func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: result.RepositoryDir,
ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath,
Tag: result.Tag,
CandidateCommit: result.CandidateCommit,
SourceVerified: result.SourceVerified,
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",
"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{
"base_url": "https://gitea.maximumdirect.net",
"owner": "eric",
"repository": "ReleaseKit",
"forge": "gitea",
"base_url": "https://forge.maximumdirect.net",
"owner": "base-layer",
"repository": "releasekit",
"token_env": "RELEASEKIT_GITEA_TOKEN",
},
}

View File

@@ -8,7 +8,7 @@ import (
"strings"
"testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
@@ -24,7 +24,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
if profile.Build != nil && len(profile.Build.Targets) != 0 {
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)
}
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
@@ -37,9 +37,9 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
const version = "v1.2.3"
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" +
"[LICENSE](https://gitea.maximumdirect.net/eric/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"
"[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/COPYRIGHT) |\n" +
"[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v1.2.3/LICENSE) |\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")
if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil {
t.Fatal(err)
@@ -50,14 +50,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
cliGitRun(t, repository, "add", "docs/releases/"+version+".md")
cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery")
state := &deliveryServerState{product: "ReleaseKit"}
state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}}
server := newDeliveryServer(t, state)
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
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")
remote := filepath.Join(t.TempDir(), "origin.git")
@@ -78,7 +78,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
}
env := map[string]string{
"CI_WORKSPACE": repository,
"CI_COMMIT_SHA": state.commit,
"CI_COMMIT_SHA": cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version),
"CI_COMMIT_TAG": version,
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
"GOTOOLCHAIN": "local",
@@ -87,14 +87,14 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
}
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 {
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")
}
state.remoteCommit = ""
state.update(func(state *deliveryServerData) { state.remoteCommit = "" })
for attempt := 0; attempt < 2; attempt++ {
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)
}
}
if state.releaseCreates != 1 || state.assetUploads != 0 || state.assetListReads != 0 {
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.releaseCreates, state.assetUploads, state.assetListReads)
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.snapshot().releaseCreates, state.snapshot().assetUploads, state.snapshot().assetListReads)
}
if state.noteBody != note {
t.Fatalf("hosted note body = %q, want complete note %q", state.noteBody, note)
if state.snapshot().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 {
t.Fatalf("source tag moved after delivery: %s, want %s", 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.snapshot().commit)
}
if status := cliGitOutput(t, repository, "status", "--porcelain"); 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"
"testing"
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
)
func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
@@ -39,10 +39,10 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{
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)
state.commit = commit
state.update(func(state *deliveryServerData) { state.commit = commit })
goDir, goLog := installGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog)
@@ -51,8 +51,8 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
if !strings.Contains(output, "state complete") {
t.Fatalf("delivery output=%q", output)
}
if state.releaseCreates != 1 || state.assetUploads != 0 {
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("source-only calls = creates:%d uploads:%d", state.snapshot().releaseCreates, state.snapshot().assetUploads)
}
assertModuleBootstrap(t, repository, goLog, moduleBefore)
})
@@ -70,10 +70,10 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
BinaryName: "helper",
Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)},
},
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example"},
})
commit := pushTaggedCLIRepository(t, repository)
state.commit = commit
state.update(func(state *deliveryServerData) { state.commit = commit })
goDir, goLog := installGoBootstrapShim(t)
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)
}
}
if state.releaseCreates != 1 || state.assetUploads != 2 {
t.Fatalf("binary calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
if state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 2 {
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 {
t.Fatalf("binary asset was not delivered: %#v", state.assets)
if _, ok := state.snapshot().assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
t.Fatalf("binary asset was not delivered: %#v", state.snapshot().assets)
}
if _, ok := state.assets["SHA256SUMS"]; !ok {
t.Fatalf("checksum manifest was not delivered: %#v", state.assets)
if _, ok := state.snapshot().assets["SHA256SUMS"]; !ok {
t.Fatalf("checksum manifest was not delivered: %#v", state.snapshot().assets)
}
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
})
@@ -104,10 +104,14 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
repository := newCLIRepository(t)
selectReleaseKitModule(t, repository, root, false)
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)
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 {
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)
})
@@ -126,30 +130,66 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
})
t.Run("selected executable receives event arguments and its status", func(t *testing.T) {
repository := newCLIRepository(t)
selectReleaseKitModule(t, repository, root, false)
commit := pushTaggedCLIRepository(t, repository)
goDir, goLog := installControlledGoBootstrapShim(t)
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
env := templateEnvironment(repository, strings.ToUpper(commit), goDir, goLog)
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)
for _, event := range []struct {
name, tag string
tagObject bool
}{
{"lightweight commit", "v1.2.3", false},
{"annotated commit", "v1.2.4", false},
{"annotated tag object", "v1.2.4", true},
} {
t.Run(event.name, func(t *testing.T) {
repository := newCLIRepository(t)
selectReleaseKitModule(t, repository, root, false)
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) {
// 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)
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml"))
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) {
goDir, goLog := installGoBootstrapShim(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")
cliGitRun(t, repository, "add", "go.mod")
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"))
commit := oldCommit
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")
env["RELEASEKIT_SUM_LOG"] = sumLog
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) {
goDir, goLog := installGoBootstrapShim(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"
writeRepositoryFile(t, repository, "go.mod", goMod)
cliGitRun(t, repository, "add", "go.mod")
@@ -207,7 +247,7 @@ func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
commit := pushTaggedCLIRepository(t, repository)
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
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")
env["RELEASEKIT_SUM_LOG"] = sumLog
output := runWoodpeckerBlock(t, command, repository, env)
@@ -245,21 +285,15 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
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, "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{
"GOPROXY": proxy.URL, "GOSUMDB": "off", "GONOPROXY": "none", "GOPRIVATE": "",
"GOWORK": "off", "GOTOOLCHAIN": "local", "GOENV": "off", "GOFLAGS": "-modcacherw",
"GOMODCACHE": t.TempDir(),
}
preparationEnv := map[string]string{}
useSyntheticModuleProxy(t, preparationEnv, proxy.URL)
runWoodpeckerBlock(t, "go mod download "+dependency, repository, preparationEnv)
cliGitRun(t, repository, "add", "cmd/releasekit/main.go", "go.mod", "go.sum")
cliGitRun(t, repository, "commit", "-m", "add the self-bootstrapped command")
commit := pushTaggedCLIRepository(t, repository)
goDir, goLog := installGoBootstrapShim(t)
env := templateEnvironment(repository, commit, goDir, goLog)
for key, value := range preparationEnv {
env[key] = value
}
env["GOMODCACHE"] = t.TempDir()
useSyntheticModuleProxy(t, env, proxy.URL)
proxyRequests.Store(0)
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
@@ -277,7 +311,7 @@ func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
if proxyRequests.Load() == 0 {
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)
}
log := readWoodpeckerFixtureFile(t, goLog)
@@ -426,6 +460,19 @@ esac
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 {
realGo, _ := exec.LookPath("go")
return map[string]string{
@@ -433,7 +480,7 @@ func templateEnvironment(repository, commit, shimDir, goLog string) map[string]s
"CI_COMMIT_SHA": commit,
"CI_COMMIT_TAG": "v1.2.3",
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
"RELEASEKIT_MODULE": "gitea.maximumdirect.net/eric/ReleaseKit",
"RELEASEKIT_MODULE": "go.maximumdirect.net/releasekit",
"RELEASEKIT_REAL_GO": realGo,
"RELEASEKIT_GO_LOG": goLog,
"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) {
t.Helper()
const module = "gitea.maximumdirect.net/eric/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))
const module = "go.maximumdirect.net/releasekit"
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.26.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
writeRepositoryFile(t, repository, "go.mod", goMod)
cliGitRun(t, repository, "add", "go.mod")
if includeSum {
@@ -479,7 +526,7 @@ func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, i
func writeReleaseKitModuleProxy(t *testing.T) string {
t.Helper()
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
const module = "go.maximumdirect.net/releasekit"
const toolDependency = "example.com/releasekit-helper"
proxyDir := t.TempDir()
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)
list := "list -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) {
t.Fatalf("Go module selection command is missing required settings: %q", log)
}

View File

@@ -2,11 +2,15 @@ package releasekit
import (
"context"
"errors"
"fmt"
"io"
"strings"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
internaldelivery "gitea.maximumdirect.net/eric/ReleaseKit/internal/delivery"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
internaldelivery "go.maximumdirect.net/releasekit/internal/delivery"
"go.maximumdirect.net/releasekit/internal/forge"
"go.maximumdirect.net/releasekit/internal/gitea"
)
// DeliveryState describes the result of one delivery invocation.
@@ -25,30 +29,81 @@ const (
DeliveryUnknown DeliveryState = "unknown"
)
// GiteaDestination supplies the hosted repository and explicit access token.
type GiteaDestination struct {
// Forge selects the hosted delivery backend. A delivery request must select a
// 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
Owner string
Repository 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.
type DeliveryAsset struct {
Filename 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
// build output instead. They cannot both be set. Either may be nil for
// page-only delivery when both are nil. Build with no targets, or an empty
// Prebuilt result, also performs page-only delivery.
type DeliveryRequest struct {
RepositoryDir string
Product string
Version string
Destination GiteaDestination
RepositoryDir string // directory within the tagged source Git checkout.
// ModuleDir selects a repository-relative module directory; empty selects
// the repository root.
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 *BuildSpec
// Prebuilt supplies an existing build whose files remain caller-owned.
@@ -62,7 +117,11 @@ type DeliveryRequest struct {
// current observations: an asset appears in at most one slice, and early
// failures may leave some declared assets unreported.
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
ReleaseURL string
State DeliveryState
@@ -78,16 +137,22 @@ type DeliveryResult struct {
Uncertain []DeliveryAsset
}
// Deliver verifies the selected local tag and hosted source, then creates or
// finds its release page and adds any missing declared build assets. Build
// requests are compiled into temporary storage that Deliver removes on return.
// Prebuilt artifacts remain caller-owned and are not removed. Both paths
// validate source identity and artifact contents before hosted writes.
// Deliver requires an explicit supported destination forge. It checks the local
// request and source, then performs read-only credential preflight before a
// managed build or full artifact verification. It verifies the selected local
// tag and hosted source, then creates or finds its release page and adds any
// 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) {
result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted}
destination := gitea.Destination{
BaseURL: request.Destination.BaseURL, Owner: request.Destination.Owner,
Repository: request.Destination.Repository, Token: request.Destination.Token,
backend, err := deliveryBackend(request.Destination)
if err != nil {
return result, err
}
var prebuilt *internalbuild.Result
if request.Prebuilt != nil {
@@ -95,13 +160,19 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
}
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir,
Product: request.Product,
Version: request.Version,
Destination: destination,
ExpectedTag: request.ExpectedTag,
Backend: backend,
Build: internalBuildSpec(request.Build),
Prebuilt: prebuilt,
Output: request.Output,
})
result.RepositoryDir = internalResult.RepositoryDir
result.ModuleDir = internalResult.ModuleDir
result.ModulePath = internalResult.ModulePath
result.Tag = internalResult.Tag
result.CandidateCommit = internalResult.CandidateCommit
result.ReleaseURL = internalResult.ReleaseURL
result.State = DeliveryState(internalResult.State)
@@ -110,10 +181,65 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
result.Pending = deliveryAssets(internalResult.Pending)
result.Conflicting = deliveryAssets(internalResult.Conflicting)
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))
for _, asset := range assets {
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

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

View File

@@ -8,15 +8,186 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"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) {
repository := newTaggedDeliveryConsumer(t)
temporaryRoot := t.TempDir()
@@ -40,11 +211,12 @@ func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.
if err != nil {
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)
}
if len(result.Uploaded) != 2 || len(remote.assets) != 2 {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
if len(result.Uploaded) != 2 || len(observed.assets) != 2 {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
}
if !strings.Contains(progress.String(), "checking fixture version output") {
t.Fatalf("build progress = %q", progress.String())
@@ -78,7 +250,8 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
if err != nil {
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)
}
wantAssets := []string{
@@ -86,12 +259,12 @@ func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
"fixture-v1.2.3-linux-arm64",
"SHA256SUMS",
}
if len(result.Uploaded) != len(wantAssets) || len(remote.assets) != len(wantAssets) {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
if len(result.Uploaded) != len(wantAssets) || len(observed.assets) != len(wantAssets) {
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(observed.assets))
}
for _, name := range wantAssets {
if _, ok := remote.assets[name]; !ok {
t.Errorf("hosted assets omit %q: %v", name, mapKeys(remote.assets))
if _, ok := observed.assets[name]; !ok {
t.Errorf("hosted assets omit %q: %v", name, mapKeys(observed.assets))
}
}
if !strings.Contains(progress.String(), "checking fixture version output") {
@@ -134,6 +307,50 @@ func TestDeliverPrebuiltArtifactsRemainCallerOwned(t *testing.T) {
}
}
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) {
for _, test := range []struct {
name string
@@ -146,6 +363,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
} {
t.Run(test.name, func(t *testing.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()
t.Setenv("TMPDIR", temporaryRoot)
server, remote := newFacadeDeliveryServer(t, repository)
@@ -158,14 +383,14 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
Version: "v1.2.3",
Destination: facadeDeliveryDestination(server.URL),
Build: test.build,
Prebuilt: test.prebuilt,
Prebuilt: prebuilt,
Output: &progress,
})
if err != nil || result.State != releasekit.DeliveryComplete {
t.Fatalf("Deliver() = %#v, %v", result, err)
}
if len(remote.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))
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.snapshot().assets))
}
if progress.Len() != 0 {
t.Fatalf("page-only delivery emitted build progress: %q", progress.String())
@@ -177,6 +402,108 @@ func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
}
}
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) {
repository := newTaggedDeliveryConsumer(t)
writeBuildFixture(t, repository, "local-change.txt", "dirty source")
@@ -198,19 +525,20 @@ func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T)
},
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)
}
if progress.Len() != 0 {
t.Fatalf("build started before source eligibility passed: %q", progress.String())
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
}
}
func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) {
repository := newTaggedDeliveryConsumer(t)
tagCommit := buildGit(t, repository, "rev-parse", "HEAD")
writeBuildFixture(t, repository, "later-change.txt", "new commit")
buildGit(t, repository, "add", "--all")
buildGit(t, repository, "commit", "-m", "advance checkout after release tag")
@@ -232,14 +560,14 @@ func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T
},
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)
}
if progress.Len() != 0 {
t.Fatalf("build started before tag/HEAD agreement: %q", progress.String())
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
}
}
@@ -263,14 +591,14 @@ func TestDeliverRejectsInvalidCommittedNoteBeforeBuildOrHostedWrites(t *testing.
},
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)
}
if progress.Len() != 0 {
t.Fatalf("build started before committed-note validation: %q", progress.String())
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
}
}
@@ -304,8 +632,8 @@ func TestDeliverManagedBuildRejectsCheckoutMutationBeforeHostedWrites(t *testing
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)
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().writes != 0 {
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
}
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err)
@@ -330,11 +658,11 @@ func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *te
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)
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().writes != 0 {
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
}
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err)
@@ -366,8 +694,8 @@ func TestDeliverManagedBuildCancellationCleansTemporaryOutput(t *testing.T) {
if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted {
t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err)
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().writes != 0 {
t.Fatalf("hosted writes = %d, want none after preflight", remote.snapshot().writes)
}
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err)
@@ -390,8 +718,8 @@ func TestDeliverRejectsBothBuildSourcesBeforeHostedWrites(t *testing.T) {
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") {
t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err)
}
if remote.requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.requests)
if remote.snapshot().requests != 0 {
t.Fatalf("hosted requests = %d, want none", remote.snapshot().requests)
}
}
@@ -405,7 +733,7 @@ func newTaggedDeliveryConsumerWithNote(t *testing.T, note string) string {
import (
"fmt"
"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()) } }
`)
@@ -416,8 +744,8 @@ func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fix
return repository
}
func facadeDeliveryDestination(baseURL string) releasekit.GiteaDestination {
return releasekit.GiteaDestination{BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
func facadeDeliveryDestination(baseURL string) releasekit.DeliveryDestination {
return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
}
type deliveryCancelWriter struct{ cancel context.CancelFunc }
@@ -428,34 +756,79 @@ func (writer deliveryCancelWriter) Write(content []byte) (int, error) {
}
type facadeDeliveryServer struct {
mu sync.Mutex
data facadeDeliveryData
}
func (state *facadeDeliveryServer) update(change func(*facadeDeliveryData)) {
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
page bool
tag string
version string
noteBody string
pages map[string]bool
requests int
writes int
assets map[string][]byte
url string
}
func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) {
t.Helper()
state := &facadeDeliveryServer{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), assets: make(map[string][]byte)}
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP))
state.url = server.URL
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.NewUnstartedServer(http.HandlerFunc(state.serveHTTP))
state.data.url = "http://" + server.Listener.Addr().String()
server.Start()
return server, state
}
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/") {
state.requests++
data.requests++
if r.Method != http.MethodGet {
data.writes++
}
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 {
case "/api/v1/repos/owner/example/tags/v1.2.3":
_, _ = fmt.Fprintf(w, `{"name":"v1.2.3","commit":{"sha":%q}}`, state.commit)
case "/api/v1/repos/owner/example/releases/tags/v1.2.3":
if !state.page {
switch r.URL.EscapedPath() {
case "/api/v1/repos/owner/example", "/api/v1/repositories/1":
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 1, "name": "example", "full_name": "owner/example",
"owner": map[string]string{"login": "owner"},
})
case "/api/v1/repos/owner/example/tags/" + url.PathEscape(data.tag):
_, _ = 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)
return
}
@@ -468,20 +841,20 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
Body string `json:"body"`
}
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)
return
}
if payload.Tag != "v1.2.3" || payload.Target != state.commit || payload.Name != "Fixture v1.2.3" {
state.t.Errorf("release payload = %#v", payload)
if payload.Tag != data.tag || payload.Target != data.commit || payload.Name != "Fixture "+data.version {
data.t.Errorf("release payload = %#v", payload)
}
state.page = true
data.pages[data.tag] = true
state.writeRelease(w)
case "/api/v1/repos/owner/example/releases/10/assets":
if r.Method == http.MethodGet {
list := make([]map[string]any, 0, len(state.assets))
for name, content := range state.assets {
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": state.url + "/files/" + name})
list := make([]map[string]any, 0, len(data.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": data.url + "/files/" + name})
}
_ = json.NewEncoder(w).Encode(list)
return
@@ -489,22 +862,22 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
name := r.URL.Query().Get("name")
file, _, err := r.FormFile("attachment")
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)
return
}
content, err := io.ReadAll(file)
_ = file.Close()
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)
_ = 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:
if strings.HasPrefix(r.URL.Path, "/files/") {
name := strings.TrimPrefix(r.URL.Path, "/files/")
content, ok := state.assets[name]
content, ok := data.assets[name]
if !ok {
http.NotFound(w, r)
return
@@ -512,17 +885,19 @@ func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Requ
_, _ = w.Write(content)
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)
}
}
func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
// The request handler holds state.mu.
data := &state.data
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"id": 10, "html_url": state.url + "/releases/10", "tag_name": "v1.2.3",
"target_commitish": state.commit, "name": "Fixture v1.2.3",
"body": "# Fixture v1.2.3\n\nDelivery fixture.\n", "draft": false, "prerelease": false,
"id": 10, "html_url": data.url + "/releases/10", "tag_name": data.tag,
"target_commitish": data.commit, "name": "Fixture " + data.version,
"body": data.noteBody, "draft": false, "prerelease": false,
})
}

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. The repository defaults to the current directory, and the profile
defaults to `<repository>/releasekit.json`. A successful command prints the
captured local commit and version. It checks the committed release note and
version. The repository argument defaults to the current directory. ReleaseKit
resolves its containing Git checkout root before selecting the module or profile;
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
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
`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
@@ -31,17 +32,28 @@ selected package compilation and committed Go formatting, followed by
configured additional checks in profile order. It does not inspect remote
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
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
target binaries. Compilation failures use the `package-compile` identity and
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
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
modifying files. When `validation.module_distribution.workspace_files` is true,
`check` reports committed `go.work` and `go.work.sum` blobs, including nested
and symlink entries, as `workspace-files`. This inspection is independent of
`check` reports committed `go.work` and `go.work.sum` blobs in those inputs,
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
separate `build` setting runs after shared validation and configured checks.
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:
```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
@@ -75,8 +87,8 @@ tests. Selected package compilation and committed Go formatting follow. The
selected file checks then run in order: workspace files, local replacements,
file size, and Markdown. Configured checks run afterward in profile order. It
then creates an annotated local tag
and pushes only its exact tag object. It prints the confirmed version,
candidate commit, and tag object
and pushes only its exact full tag object. It prints the confirmed semantic
version, full tag, candidate commit, and tag object
on success. Validation
progress and failed publication state, including the captured publication
endpoint for recovery, are written to standard error. A signal
@@ -95,9 +107,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.
When `validation.module_distribution.local_replacements` is true, the command
parses committed `go.mod` declarations, including nested and vendor modules,
after workspace-file inspection. Filesystem replacements use the
`local-replacements` identity and include the declaration path, source line,
parses committed `go.mod` declarations in the selected module after
workspace-file inspection. Vendored contents remain in scope, while
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
resolved within the candidate, regardless of `GOWORK`.
When `validation.file_size` is a non-null object, the command checks each
@@ -112,6 +126,11 @@ It reports outside-checkout links to standard error unless boundary enforcement
is selected; submodule contents remain out of scope. Markdown failures stop
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
nonempty value must exactly match the effective push URL resolved by Git;
mismatches fail during preflight before Go validation or tag creation. Git URL
@@ -135,8 +154,8 @@ go run ./cmd/releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSIO
targets with the requested version injected, checks the native `version`
invocation, and writes binaries plus the private `.releasekit-build.json`
receipt into `dist` by default. `--output` selects a different directory;
relative paths are resolved from the repository. Selected artifact filenames
are regenerated while unrelated files are preserved. A complete nonempty build
relative paths are resolved from the selected module directory. Selected
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
failure, standard error lists completed outputs and prior receipts in that
output directory are invalidated; no new receipt is written. An
@@ -149,14 +168,17 @@ tree and does not perform candidate validation or remote publication. `check`
and `publish` run the same configured build after their one candidate
validation, using temporary output outside the worktree.
Deliver a tagged source release to Gitea:
Deliver a tagged source release:
```sh
go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION
```
`deliver` requires a `delivery` profile object and its configured token
environment variable, which defaults to `RELEASEKIT_GITEA_TOKEN`. It verifies
`deliver` requires a `delivery` profile object with an explicit
`"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,
then creates or finds the release page and reports delivery state separately
from source publication. Historical lightweight tags and detached checkouts
@@ -169,20 +191,33 @@ the tagged source into temporary storage, removes it when the operation ends,
and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is
supplied, that directory must contain the private `.releasekit-build.json`
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
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
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
`deliver` command does not download application dependencies or change the
checkout.
The command returns 0 for complete delivery, 1 for a known failure, conflict,
or partial delivery, 2 for usage, profile, or missing-credential errors, and 3
when a remote write remains uncertain. The result lists matching, uploaded,
pending, conflicting, and uncertain assets as disjoint current observations;
The command returns 0 for complete delivery, 1 for an unavailable preflight or
a known delivery failure, conflict, or partial delivery, and 2 for usage,
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
prints state-based recovery guidance. Fix local or preflight failures before
retrying; fix the reported cause before retrying partial delivery; resolve an
@@ -197,29 +232,44 @@ known missing assets are added. See the
Prepare a tagged CI checkout and deliver it:
```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`),
requires the tag's peeled commit to match the required full `--commit` object
ID, and checks out that commit detached. It then loads the profile from the
prepared checkout, validates delivery settings and the configured token, and
downloads application dependencies only when the profile selects build targets.
Binary profiles are built and delivered through the same facade path as
`deliver`; source-only profiles skip dependency downloads and binary builds.
`TAG` is the complete Git tag name, including any module path prefix. Its last
path component must be a stable semantic version; other commands continue to
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from
the selected Git remote (default `origin`), requires its peeled commit to match
the required full `--commit` object ID, checks out that commit detached, then
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
checks read-only against the existing checkout and does not fetch or check out.
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
from `--repo`, and absolute paths are used as-is. This command explicitly
prepares and changes the selected checkout. Ordinary `deliver` continues to
operate on already prepared source without fetching, checking out, or
downloading dependencies.
from `--repo`, and absolute paths are used as-is. The default mode prepares and
changes the selected checkout; `--prepared` reuses a verified checkout.
Ordinary `deliver` continues to operate on already prepared source without
fetching, checking out, or downloading dependencies.
In Woodpecker, pass `CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the
repository, expected commit, and version arguments. The CLI does not read
In Woodpecker, pass `CI_WORKSPACE`, the source commit resolved from
`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
preparation failures return status 1; usage, profile, credential, and invalid
version errors return 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.
preparation failures, unavailable preflight, and cancellation during those
steps return status 1. Usage, profile, forge-selection, local credential-loading,
classified preflight configuration/access, and invalid-version errors return
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
before resolving the consumer module. It builds the ReleaseKit version already

View File

@@ -1,20 +1,29 @@
# Configuration
ReleaseKit reads a JSON profile from `<repository>/releasekit.json` by default.
The repository directory defaults to the current directory. A relative profile
path is resolved from that repository directory; an absolute path is used as-is.
ReleaseKit reads a JSON profile from `<repository-root>/releasekit.json` by default.
The repository argument defaults to the current directory; the CLI resolves its
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:
| Field | Required | Behavior |
| --- | --- | --- |
| `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`. |
| `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. |
| `validation` | No | Optional shared checks selected by ReleaseKit. |
| `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
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.
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
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
@@ -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
test command keeps its existing vet behavior. These settings are independent.
`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
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
@@ -69,12 +90,14 @@ Anchors keep Unicode letters and numbers, underscores, and hyphens; spaces
become hyphens, and repeated headings receive numeric suffixes.
When `validation.module_distribution.workspace_files` is true, it reports
committed blob entries whose basename is `go.work` or `go.work.sum`, including
nested paths and symlinks. It checks candidate distribution contents regardless
committed `go.work` and `go.work.sum` files in the selected module inputs,
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,
and it does not alter existing vendor behavior. Omitted or false disables it.
When `validation.module_distribution.local_replacements` is true, it parses all
committed `go.mod` declarations, including vendor and nested modules, and reports
and vendored contents remain in scope. Omitted or false disables it. When
`validation.module_distribution.local_replacements` is true, it parses the
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
replacements include relative and absolute paths; versioned module replacements
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
are invalid.
`validation.file_size.exclusions` contains literal repository-relative file or
directory paths. Directory exclusions include committed descendants, using path
`validation.file_size.exclusions` contains literal paths relative to the
selected module. Directory exclusions include committed descendants, using path
boundaries (`assets` does not exclude `assets-old`). Ordinary relative path
normalization applies; metacharacters are literal and unmatched paths have no
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,
and historical or aggregate repository size is not measured.
The `delivery` object contains `base_url`, `owner`, `repository`, and optional
`token_env`. Its values are required when running `deliver`, but credentials are
not required for `check`, `publish`, or `build`. `token_env` names the
environment variable containing the Gitea token; it defaults to
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and
passes its value explicitly to the library operation.
`validation.forbidden_files` is an optional list of literal repository-relative
file paths that must be absent from the captured commit. It runs after the Go
checks and before other file checks, using the `forbidden-files` identity and
reporting selected committed paths. Omission, `null`, or `[]` disables it.
Paths use slash separators and ordinary relative normalization and must stay
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
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
change the checkout.
`ci-deliver` uses the same profile after preparing the selected tag in the
checkout. It checks out the tag only after its peeled commit matches the
provider-supplied commit ID, then loads the profile and validates delivery
settings and credentials. It runs `go mod download` only when the profile has
selected build targets; source-only delivery does not need application
dependencies. This preparation may access the network and may update
`go.sum`. The command takes CI values as arguments, so profile settings remain
independent of Woodpecker environment variable names. See the
`ci-deliver` takes a full Git `TAG`; its final path component is the stable
semantic version and the complete value is checked against the profile's
derived tag. By default it fetches the selected tag, confirms its peeled commit
matches the provider-supplied commit ID, checks it out detached, and verifies
the tag, HEAD, and clean worktree. With `--prepared`, it performs the same
checks against an existing checkout without fetching or checking out. It then
loads the profile from that source and validates delivery settings and
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.
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"
"fmt"
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
releasekit "go.maximumdirect.net/releasekit"
)
func build(ctx context.Context) error {
@@ -36,19 +36,24 @@ func build(ctx context.Context) error {
}
```
`Build` records the repository's current `HEAD`, injects the selected stable
version into `buildinfo.Version`, and returns the compiler identity, normalized
targets, artifact paths, filenames, and SHA-256 digests. Names follow
`Build` resolves `ModuleDir` and the selected module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected stable
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
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 and the same HEAD before and after compilation; binary delivery requires
that fact. This observation is not a source snapshot or attestation guarantee.
The default output directory is `<repository>/dist`; a relative `OutputDir` is
resolved from the repository. Selected artifact filenames are regenerated. Other files in the output
directory are left in place. A failed later build or native version check returns the binaries already
generated in `BuildResult.Artifacts`.
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
module. The default output directory is `<module>/dist`; a relative `OutputDir`
is resolved from the module, while an absolute path is used as supplied.
Selected artifact filenames are regenerated. Other files in the output
directory are left in place. A failed later build or native version check
returns the binaries already generated in `BuildResult.Artifacts`.
Builds use the available compatible Go toolchain selected locally; ReleaseKit
does not download a different toolchain automatically. It disables workspace
@@ -72,10 +77,14 @@ The [`build` command](../cli.md) reads the same build specification from the
profile and writes a private receipt alongside its artifacts. `check` and
`publish` run selected builds after the standard suite and any additional
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
targets into temporary storage by default. Use `--assets DIR` to deliver a
separate build output; ReleaseKit requires its receipt and verifies the source,
build settings, and artifact hashes before the first Gitea write. See the
separate build output; ReleaseKit requires the current module-bound receipt and
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.

View File

@@ -21,14 +21,27 @@ if err != nil {
fmt.Println(result.Version, result.Commit)
```
The repository must have a clean index and worktree on `main`, and the selected
version must be stable `vMAJOR.MINOR.PATCH`. The committed
`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
that version may already exist.
Set `ReleaseRequest.ModuleDir` to select a nested module using a
repository-relative physical directory; omission or `.` selects the root
module. ReleaseKit reads that module's committed `go.mod` and returns its
physical `ModuleDir`, declared `ModulePath`, semantic `Version`, and complete
`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
available compatible local Go toolchain. Set `Validation.Go.Race` to run that
The repository must have a clean index and worktree on `main`, and the selected
version must be stable `vMAJOR.MINOR.PATCH`. The module-local committed
`<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
`go vet -mod=readonly ./...` after successful tests, with test-time vet disabled
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
values retain the ordinary native test behavior and select no compilation.
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
`go-format` without rewriting files. Its zero value disables the check; it runs
after tests, selected vet, and package compilation, before `AdditionalChecks`.
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
`go.work` and `go.work.sum` blobs, including nested and symlink entries. It
examines the captured candidate even when `GOWORK=off`, ignores uncommitted
files, and does not change Go test workspace selection or vendor behavior. The
zero value disables the check; failures use `workspace-files`.
`go.work` and `go.work.sum` files in the selected module inputs, including
symlink entries. It examines the captured candidate even when
`GOWORK=off`, ignores uncommitted files, and does not change Go test workspace
selection; vendored contents remain in scope. The zero value disables the check;
failures use `workspace-files`.
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
committed `go.mod` declarations throughout the candidate, including nested and
vendor modules. It reports filesystem `replace` directives with their source
path, line, and target as `local-replacements`; versioned replacements are
the selected module's committed `go.mod` declarations. Vendored contents remain
in scope; automatic inputs stop at independently released nested modules. An
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
and inspection errors retain their causes, and the rule applies even when
`GOWORK=off`. Its zero value disables the check.
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
decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects
negative values. `Exclusions` contains literal repository-relative files or
directories; excluded directories include descendants. Symlink blobs are
negative values. `Exclusions` contains literal files or directories relative to
the selected module; excluded directories include descendants. Symlink blobs are
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
`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
consumer-specific assertions—such as tests of maintained examples—in those
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
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,
@@ -86,6 +128,9 @@ settings are preserved, including values from Go's persistent environment
file. The check revalidates the branch, commit, and cleanliness after
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
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
@@ -94,10 +139,11 @@ commands from `releasekit.json`.
## Publishing the source tag
`releasekit.Publish` uses the same request and validation order: the standard
suite runs first, followed by `AdditionalChecks` when supplied. It then performs
authoritative remote checks, annotated-tag creation, and an exact tag push. The
suite runs first, followed by `AdditionalChecks` when supplied. It surrounds
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
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
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

View File

@@ -1,12 +1,21 @@
# Deliver a tagged source release
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
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
detached checkout, when the checked-out `HEAD` identifies the selected tag
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
Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified
@@ -20,7 +29,7 @@ or hosted content.
```go
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
RepositoryDir: repositoryDir,
Version: version,
Tag: "integrations/example/v1.2.3",
ExpectedCommit: ciCommit,
})
if err != nil {
@@ -28,16 +37,25 @@ if err != nil {
}
```
For binary profiles, call `PrepareBuildDependencies(ctx, repositoryDir)` after
checkout preparation and before delivery. It runs `go mod download` with
workspace discovery disabled and the available compatible local Go toolchain.
For binary profiles, call `PrepareBuildDependencies` with a
`DependencyPreparationRequest` selecting the repository and module after
checkout preparation and before delivery. It runs `go mod download` in that
module with workspace discovery disabled and the available compatible local Go
toolchain.
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`; see the
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
and command errors are returned. Page-only profiles do not need dependency
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
Add a Gitea destination to the profile:
@@ -46,6 +64,7 @@ Add a Gitea destination to the profile:
{
"product": "Example",
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "example",
@@ -61,14 +80,45 @@ git checkout --detach 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
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before
The CLI resolves the token for delivery using the configured environment
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
hosted body. A retry accepts an identical page and matching attachments, adds
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,
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
temporary storage and delivers the result. To retain artifacts for a retry or
separate credentials between build and delivery, use two invocations:
@@ -80,10 +130,14 @@ RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3
The build command does not need delivery credentials. The `--assets DIR`
directory must contain the private `.releasekit-build.json` receipt created by
`build`. ReleaseKit checks the receipt's repository, commit, version, resolved
build settings, and file hashes before making a remote request; caller-owned
files remain available for retries. Ordinary `deliver` does not download
application dependencies or change the checkout.
`build`. ReleaseKit checks its schema, repository, commit, version, resolved
module directory and path, full tag, normalized build settings, and artifact
declarations. Old receipts must be regenerated with the updated `build`
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
`not_attempted`, along with matching, uploaded, pending, conflicting, and
@@ -101,29 +155,79 @@ published content needs correction. If rebuilding could change bytes already
on the server, retain the original build output and retry with `--assets DIR`.
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
Pass the Gitea credential explicitly. Set `Build` to a `BuildSpec` to compile
selected targets as part of delivery. The facade verifies the local tag, clean
checkout, and committed release note before compiling. Managed output is stored
outside the checkout and removed when delivery returns. `Output` receives build
progress. With no build, or with an empty target set, delivery is page-only.
Pass the Gitea credential explicitly and select `ForgeGitea`. Set `Build` to a
`BuildSpec` to compile selected targets as part of delivery. The facade verifies
the local tag, clean checkout, and committed release note before compiling.
Managed output is stored outside the checkout and removed when delivery
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`.
ReleaseKit checks that it identifies the selected repository, tagged commit, and
version, that its source was verified clean and unchanged during compilation,
and that the current files still match their recorded digests. 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 an empty prebuilt result, delivery is page-only. Do not set both `Build`
and `Prebuilt` in one request.
ReleaseKit checks its repository, module directory, declared module path, full
tag, semantic version, tagged commit, normalized settings, and artifact evidence
against the selected committed module. Binary results must record verified
source. The current files are checked against their recorded digests before any
hosted request. 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. Do not set both `Build` and `Prebuilt` in one
request.
```go
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
RepositoryDir: "/work/example",
ModuleDir: "integrations/example",
Product: "Example",
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",
Owner: "example",
Repository: "example",
@@ -150,34 +254,58 @@ exit codes, and transport behavior.
Use the maintained [tag-delivery workflow](../../examples/woodpecker/tag-delivery.yml)
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
consumer module. It uses `GOTOOLCHAIN=local`; Go does not download a different
toolchain. The tag's `go.mod` must select ReleaseKit as a module dependency.
image with Git and a Go toolchain compatible with the consumer module and its
selected ReleaseKit version. Choose the patch used for the consumer's release
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
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
profile's build target list selects whether application binaries are built and
delivered.
Before running Go, the template fetches the explicit event tag, compares its
peeled commit with the provider's full commit ID without regard to hex case,
checks out that commit detached, and confirms the source tree is clean. It then
copies the tagged `go.mod` and any `go.sum` to a temporary directory outside
the checkout. `go list -m` confirms that the module selects ReleaseKit; Go uses
Before running Go, the template fetches the explicit event tag and independently
resolves both the tag and `CI_COMMIT_SHA` to source commits. The event ID may
identify an annotated tag object or a commit. The template requires the resolved
commits to match, checks out that commit detached, and confirms the source tree
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
`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.
Tool bootstrap and application artifact preparation are separate. The bootstrap
resolves and builds ReleaseKit from the tagged consumer's module configuration.
Afterward, `ci-deliver` loads the profile and downloads application dependencies
only when build targets are selected; it builds and delivers those targets with
the note page. Source-only profiles skip application dependency downloads and
binary work. Dependency preparation for binaries may use the network and may
update an uncommitted checksum file in the checkout. A retry still uses the
same immutable tag and that tag's module settings, even after the default branch
selects a newer ReleaseKit version.
After the workflow verifies and checks out the event tag, the resulting CLI uses
`ci-deliver --prepared` to repeat the tag, commit, HEAD, and cleanliness checks
without another fetch or checkout. It loads the tagged profile and downloads
application dependencies only when build targets are selected; it builds and
delivers those targets with the note page. Source-only profiles skip application
dependency downloads and binary work. Dependency preparation for binaries may
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
the executable separately and invoke the same `ci-deliver` command. For
@@ -192,11 +320,13 @@ and application artifact compilation retain their separate environments.
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
the template. A separately installed executable can be installed with
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run
with the same arguments:
`go install go.maximumdirect.net/releasekit/cmd/releasekit@PIN`, then run
with the same arguments. With the event object available in the CI checkout,
resolve it to its source commit before invocation:
```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
@@ -205,6 +335,12 @@ consumer module configuration when adopting a newer ReleaseKit version and
verify it with a tag fixture. The command and profile behavior are documented
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
publication result. Read its workflow status as delivery status: a delivery
failure does not undo source publication. A failed, partial, or uncertain run
@@ -214,3 +350,50 @@ move the tag to make a retry pass. See
for runner-provided tag and commit variables and
[workflow syntax](https://woodpecker-ci.org/docs/usage/workflow-syntax) for tag
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
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
RepositoryDir: "/work/project",
ModuleDir: "integrations/example",
Product: "Example",
Version: "v1.2.3",
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},
},
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
return runProjectChecks(ctx, candidate.RepositoryDir)
return runProjectChecks(ctx, candidate.ModuleDir)
},
})
if err != nil {
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
release note, and checks the selected remote before running candidate checks.
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.
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
`go-format` without changing files. The default is disabled. The check follows
tests, selected vet, and package compilation, and a failure stops publication
before product checks or tag creation.
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
are ignored, and Go workspace selection and vendor behavior are unchanged. Its
zero value disables the check. Findings use `workspace-files` and stop
publication before product checks or tag creation.
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
committed `go.mod` declarations across the candidate, including nested and
vendor modules. Filesystem `replace` directives are reported with their source
path, line, and target as `local-replacements`; versioned replacements are
selected module's committed `go.mod` declarations. Vendored contents remain in
scope; automatic inputs stop at independently released nested modules. Explicit
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
parse or inspection errors retain their causes. This check is independent of
`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.
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
negative values. `Exclusions` contains literal repository-relative files or
directories, including committed descendants of excluded directories. Symlink
blob size is its link text; gitlinks are omitted. This check measures only the
negative values. `Exclusions` contains literal files or directories relative to
the selected module, including committed descendants of excluded directories.
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
`file-size`; it stops publication before product checks or tag creation.

View File

@@ -4,7 +4,7 @@ Applications can read their embedded version through the public `buildinfo`
package:
```go
import "gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
import "go.maximumdirect.net/releasekit/buildinfo"
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
workflow and does not change the successful-tag-push completion point. ReleaseKit
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
ReleaseKit's public `Deliver` operation and `deliver` command verify tagged
source, find or create its stable release page, inspect existing assets, and
upload missing assets through the internal Gitea client. Page-only and
binary-producing profiles use the same delivery path. The
ReleaseKit's public `Deliver` operation and `deliver` command select Gitea
explicitly, verify tagged source, find or create the selected module's release
page, inspect existing assets, and upload missing assets. Shared delivery code
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;
this guide describes the Gitea protocol and its failure behavior.
@@ -13,34 +14,68 @@ 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,
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
SHA to equal the captured source commit. It then reads
`/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
conflicting page.
conflicting page. Slash-containing tags are escaped as one URL path segment.
If the page is absent, the client posts to `/api/v1/repos/{owner}/{repo}/releases`
with the selected tag and commit, the release note's H1 as title, the complete
note as body, and draft and prerelease disabled. A create conflict, interrupted
response, or malformed create response (including inconsistent decoded fields)
triggers one lookup. An exact page found
there confirms the existing content; a differing page is a conflict. If that
lookup cannot determine the result after a possibly successful write, the
client returns an unknown outcome. Other HTTP failures retain their structured
failure kind and status code. A recovered create retains its write history;
a later asset-inspection failure reports partial page progress.
If the page is absent, the adapter posts to
`/api/v1/repos/{owner}/{repo}/releases` with the selected full tag and commit,
the release note's H1 as title, the complete note as body, and draft and
prerelease disabled. A create conflict, interrupted response, or malformed
create response (including inconsistent decoded fields) triggers one lookup by
the shared workflow. An exact page found there confirms the existing content;
a differing page is a conflict. If that lookup cannot determine the result
after a possibly successful write, delivery returns an unknown outcome. Other
HTTP failures retain their structured failure kind and status code. A recovered
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
are sorted by filename and use the standard two-space separator. A source-only
release produces no manifest.
Asset inspection lists the release attachments, streams each declared existing
file, and compares its SHA-256 digest. It reports each asset as matching,
missing, conflicting, or unverifiable. Same-name attachments with different
bytes are conflicts even when their reported size matches. An existing
The adapter lists release attachments and opens their download streams. Shared
delivery compares each declared existing file by SHA-256 digest and reports it
as matching, missing, conflicting, or unverifiable. Same-name attachments with
different bytes are conflicts even when their reported size matches. An existing
`SHA256SUMS` must exactly match the complete expected manifest; a subset or
different manifest is a conflict. An unreadable attachment is unverifiable,
not missing. A failed read-only inspection reports `not_attempted`; if this
@@ -51,10 +86,10 @@ Attachment downloads and redirects carry the Gitea authorization token only
when their scheme, host, and port match the configured service. Cross-origin
content is downloaded without that token and verified by its digest.
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
missing `SHA256SUMS`, using multipart field `attachment` and the filename query
parameter `name`. Matching attachments are retained; unrelated and existing
missing `SHA256SUMS`, using the adapter's multipart field `attachment` and
filename query parameter `name`. Matching attachments are retained; unrelated and existing
attachments are never overwritten or deleted. Results use disjoint current
observations: matching, uploaded, pending, conflicting, and uncertain. An asset
moved from known missing work to another category is removed from `pending`;

View File

@@ -1,15 +1,47 @@
# Go command environments
`internal/gotool` resolves effective Go settings once for a validation or build
operation and applies the shared environment to its Go commands. It uses
`internal/gotool` resolves effective Go settings when an operation first needs
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
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, then releases its capture
on success. Failures include the captured diagnostic text and preserve the
underlying process or forwarding error.
`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 one 8 MiB write with the same output in
32 KiB writes, forwarding to `io.Discard`. Smaller writes incur buffer-growth
allocations. 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, and cache settings remain available. Its completed capture
uses the same ownership transfer when formatting a failure.
## Configuration discovery
The owner asks the installed `go` command for `GOHOSTOS` and `GOHOSTARCH`, then
queries effective operational settings with that host selected. Both queries
use `GOTOOLCHAIN=local` and controlled `GOFLAGS`. Discovery sets
The owner asks the installed `go` command for `GOHOSTOS`, `GOHOSTARCH`, and the
`GOENV` settings-file path, then queries effective operational settings with
that host selected. Both queries use `GOTOOLCHAIN=local` and controlled
`GOFLAGS`. Discovery sets
`GOEXPERIMENT=none` and clears architecture feature variables so an invalid or
nonbaseline tuning value cannot prevent settings from being read. The
experiment override is discovery-only.
@@ -20,6 +52,13 @@ and native cgo/C-tool configuration into its settings. This captures values
supplied by either the process environment or the persistent Go environment
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
and included in command-failure diagnostics, so a successful query can emit
warnings while supplying valid configuration.
@@ -41,9 +80,10 @@ baseline values. Effective `GOCACHE`, `GOCACHEPROG`, `GOMODCACHE`, `GOPATH`,
`GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain
available to child commands.
Candidate validation uses native mode for the offline `go test` suite and
selected full `go vet` pass. Package-compilation checks use static mode for each
selected target and direct Go's output to the operating system null device, so
they leave no binary artifact. Artifact builds also use static mode for
selected-target compilation, then build the native version-check executable;
that executable runs as a normal child process.
Candidate validation runs the offline `go test` suite and selected full
`go vet` pass from the selected module directory using native mode.
Package-compilation checks use static mode for each selected target and direct
Go's output to the operating system null device, so they leave no binary
artifact. Artifact builds also compile selected targets in static mode, then
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
The module is `gitea.maximumdirect.net/eric/ReleaseKit`, with Go language
version `1.25.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
The module is `go.maximumdirect.net/releasekit`, with Go language
version `1.26.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
validation; public facades do not expose either dependency. `go list ./...`
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. |
| `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/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/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/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/gitea` | Gitea API transport, hosted release pages, asset inspection, manifests, and uploads. |
| `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/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/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. |
| `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
| `internal/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/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/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/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. |
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
in `internal/candidate`. Its validation bridge calls `internal/validation` for
the default offline Go suite, then runs product-specific checks once. The
candidate package owns post-validation builds and local-state rechecks;
publication owns endpoint guards, tag creation, push, and recovery around that
same candidate validation path. `internal/validation.CandidateTree` reads
the selected module's default offline Go suite, then runs product-specific
checks once. Validation and its post-validation build callback share one local
Go settings owner. Each Go acquisition checks inherited and persistent inputs;
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;
it does not consult neighboring files or traverse submodule checkouts.
See the [shared validation guide](validation.md) for checker, Go command, and
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
The following tests are representative evidence from the current offline suite,
@@ -81,14 +97,18 @@ not a separate release matrix:
| 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` |
| 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` |
| 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` |
| 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` |
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` |
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout` |
| 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` |
| Explicit destination selection, standalone and automatic preflight, and delivery ordering | `releasekit`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliveryForgeSelectionIsExplicit`, `TestPreflightDeliveryChecksAuthenticatedRepositoryWithoutCheckout`, `TestPreflightDeliveryPreservesPublicFailureKindsAndCauses`, `TestAutomaticPreflightFailurePrecedesPrebuiltArtifactHashing`, `TestDeliverUnavailablePreflightStopsBeforeManagedBuild`, `TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation`, `TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne` |
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages`, `TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites` |
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
| 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
check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise

View File

@@ -8,59 +8,100 @@ post-validation build callback and local-state recheck. `internal/publish`
adds its endpoint guards, tag creation, push, and recovery around that same
candidate path.
The executor runs one offline Go suite, optionally with the race detector when
selected. When full vet is selected, it disables test-time vet for that suite
and runs native `go vet -mod=readonly ./...` after the suite succeeds. It then
runs `go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
selected package-compilation target, preserving target order and stopping on
the first failure. This compiles source without producing an artifact or
executing a target binary. Test, vet, and package-compilation failures retain
their `go-test`, `go-vet`, and `package-compile` identities, selected target
where applicable, and underlying causes. Its
The executor runs one offline Go suite from the captured module directory,
optionally with the race detector when selected. When full vet is selected, it
disables test-time vet for that suite and runs native
`go vet -mod=readonly ./...` from the same directory after the suite succeeds.
It then runs `go build -mod=readonly -o <os.DevNull> ./...` there in static mode
for each selected package-compilation target, preserving target order and
stopping on the first failure. This compiles source without producing an
artifact or executing a target binary. Test, vet, and package-compilation
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,
and internal settings. When selected, the Go-format check loads the candidate
tree once, reads regular Go blobs from the captured commit, and compares them
with go/format output. It includes vendor and nested-module files, skips
with go/format output. It uses the selected inputs, including vendor and explicit
shared files, and 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.
`Request.ReadCandidateTree` lets selected file checks request candidate
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
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
commands.
The local-replacement check parses every committed go.mod blob with
`golang.org/x/mod/modfile`, including nested modules and vendor declarations.
The local-replacement check parses selected go.mod blobs with
`golang.org/x/mod/modfile`, including vendor and explicitly shared declarations.
It follows committed symlink declarations through the captured tree and fails
with an inspection cause when their selected contents are unavailable. A
replacement with no parsed version is reported with its go.mod path, line,
directive, and target; versioned replacements are allowed. It runs after the
workspace-file check using the same candidate inventory.
The optional file-size check uses each blob's captured Git size, including
symlink link-text bytes, and skips entries without a blob size such as gitlinks.
It applies normalized literal file/directory exclusions with path-boundary
matching, then returns the first oversized path with `FileSizeMeasurement`.
workspace-file check using the same candidate inventory. Resolved module bodies
are parsed once per blob object ID; only owned filesystem-replacement targets
and line numbers remain cached. Each declaration path receives findings from
that summary in its own path context.
The optional forbidden-file check uses the captured tree's full path lookup
before the other file checks. It normalizes the explicitly selected
repository-relative names and reports matching entries through `forbidden-files`
without loading their blobs. Candidate-tree cleanup covers this failure path.
The optional file-size check applies normalized literal file/directory
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
candidate tree. It parses regular Markdown blobs, resolves local destinations,
and checks supported anchors; outside-checkout and submodule observations are
written to the shared output writer. A nil writer keeps library use quiet.
`CandidateTree` gets metadata and bytes from Git objects, reads blob bytes
lazily, and resolves destinations without consulting the worktree or
neighboring files.
`CandidateTree` enumerates full repository path, type, mode, and object metadata
without requiring blob contents or sizes. Checks acquire sizes and bytes for
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
autolinks, images, titles, and their source use sites, and to build heading
anchors from visible AST text. It supports ATX and Setext headings, decodes
Markdown text through the parser, and assigns collision-free numeric suffixes
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
skips schemed and protocol-relative URIs, strips query components, and decodes
percent escapes once in local paths and fragments. It resolves destinations
through `CandidateTree.ResolveDestination`; decoded fragments are compared in
lowercase against anchors from the resolved regular Markdown document. Missing
through `CandidateTree.ResolveDestination` relative to the current source path;
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
the source use site. Outside-checkout links produce out-of-scope observations by
default and findings when boundary enforcement is selected. Submodule-content
@@ -72,6 +113,7 @@ Committed-tree metadata and blob reads disable lazy fetching 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.
Candidate and delivery release-note reads use the same local object boundary.
Public validation errors convert their diagnostic fields to the internal
failure model for shared formatting. Converted failures retain their original
@@ -133,7 +175,8 @@ directories, missing paths, checkout boundaries, submodule paths, and symlink
cycles; the caller selects which observations fail validation or are reported
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
destinations and symlink targets within the repository directory map back to
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,
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
@@ -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) |
[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
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,
dependency checks, and external-package behavioral tests protect the selected
facade boundaries.

View File

@@ -2,7 +2,7 @@
**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)
@@ -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
[COPYRIGHT](../../COPYRIGHT). It applies to the library and release
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).
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;
preserve notices or add them where the applicable terms require them.
Identify separately licensed documentation or assets in the project grant, with
links to their attribution and license information. An application's default
code license does not override the terms of incorporated documentation.
Identify separately licensed documentation or assets in the attribution
document, with links to their license information. The project grant uses the
upstream template's third-party statement.
## Upstream Attribution House Format

View File

@@ -1,10 +1,10 @@
# 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
@@ -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
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
summaries belong in `docs/releases/`. The procedure must agree with the adopted
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`:
- 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.
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
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
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.
Release tests must not require real credentials, mutable application services,
paid APIs, or live service probes. The procedure may describe dependency
preparation separately from offline validation.
paid APIs, live service probes, or inference calls. The procedure may describe
dependency preparation separately from offline validation.
Avoid duplicate validation across release phases. Successful checks for the
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
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;
3. one publication command with its selected local checks and automated guards;
4. declared deliverables, required build targets, and automation responsibilities;

View File

@@ -5,23 +5,58 @@ the complete checked-in release note. The page is delivered asynchronously by
the prepared [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml);
it is not a source-release completion check and carries no binary assets. The
authoritative repository is `origin` at
`https://gitea.maximumdirect.net/eric/ReleaseKit.git`, and the release branch
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
succeeded. CI and consumer installation are not completion checks.
## Prepare a candidate
Use a local Go 1.25 toolchain and a clean clone. Start on `main`, choose an
unused stable `vMAJOR.MINOR.PATCH` version, and add
For local hosted-page delivery, save a Gitea personal access token in
`.releasekit/gitea-token` with owner-only file permissions. The file contains
only the token. ReleaseKit's profile selects this file 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
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:
```markdown
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/LICENSE) |
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/docs/oss/attribution.md)
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/COPYRIGHT) |
[LICENSE](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/vX.Y.Z/LICENSE) |
[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
@@ -124,7 +159,15 @@ git checkout --detach "vX.Y.Z"
GOTOOLCHAIN=local go mod download
mkdir -p .releasekit/bin
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

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)

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

@@ -0,0 +1,62 @@
# ReleaseKit v0.6.0
## Summary
ReleaseKit adds neutral delivery coordination behind an explicit Gitea backend
selection and introduces authenticated, read-only credential preflight.
## Changes
- `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.
## Upgrade guidance
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.
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)

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"]
},
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "example",

View File

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

View File

@@ -4,7 +4,7 @@ when:
steps:
- name: deliver
image: golang:1.25.0-bookworm
image: golang:1.26.10-bookworm
environment:
RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token
@@ -15,9 +15,13 @@ steps:
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 "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
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)"
@@ -29,5 +33,6 @@ steps:
go build -mod=readonly -o "$${bootstrap_dir}/releasekit" ./cmd/releasekit
"$${bootstrap_dir}/releasekit" ci-deliver \
--repo "$${CI_WORKSPACE}" \
--commit "$${CI_COMMIT_SHA}" \
--prepared \
--commit "$${expected_commit}" \
"$${CI_COMMIT_TAG}"

View File

@@ -1,6 +1,6 @@
matrix:
include:
- GO_IMAGE: golang:1.25.0-bookworm
- GO_IMAGE: golang:1.26.10-bookworm
when:
- event: tag
@@ -19,9 +19,13 @@ steps:
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 "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
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)"
@@ -39,11 +43,12 @@ steps:
export GOWORK=off
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 build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
"$${bootstrap_dir}/releasekit" ci-deliver \
--repo "$${CI_WORKSPACE}" \
--commit "$${CI_COMMIT_SHA}" \
--prepared \
--commit "$${expected_commit}" \
"$${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 (
github.com/yuin/goldmark/v2 v2.1.6

View File

@@ -15,7 +15,7 @@ import (
"strings"
)
const modulePath = "gitea.maximumdirect.net/eric/ReleaseKit"
const modulePath = "go.maximumdirect.net/releasekit"
var facades = []string{modulePath, modulePath + "/buildinfo"}
@@ -226,6 +226,33 @@ func checkImportDirections(packages []listedPackage) error {
}
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 {
return nil
}
@@ -254,7 +281,7 @@ func commandInternalRoot(path string) string {
func forbiddenRuntimeDependency(path string) bool {
for _, part := range strings.Split(strings.ToLower(path), "/") {
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
}
}

View File

@@ -10,6 +10,26 @@ import (
"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) {
tests := []struct {
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 {
t.Helper()
fset := token.NewFileSet()

View File

@@ -3,21 +3,51 @@ package artifact
import (
"fmt"
"path/filepath"
"strings"
)
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 {
OS 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 {
Target Target
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
// occurrence.
func NormalizeTargets(targets []Target) []Target {

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) {
targets := []Target{{OS: "windows", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}}
want := []Declaration{

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

@@ -13,26 +13,23 @@ import (
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/candidate"
"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 Target = artifact.Target
type Spec struct {
MainPackage string
BinaryName string
Targets []Target
}
type Spec = artifact.Settings
type Request struct {
RepositoryDir string
Version string
Spec Spec
OutputDir string
Output io.Writer
Identity releaseidentity.Identity
Spec Spec
OutputDir string
Output io.Writer
ToolOwner *gotool.Owner
}
type Artifact struct {
@@ -44,8 +41,12 @@ type Artifact struct {
type Result struct {
RepositoryDir string
ModuleDir string
ModulePath string
Tag string
CandidateCommit string
SourceVerified bool
Settings artifact.Settings
Version string
MainPackage string
BinaryName string
@@ -55,25 +56,32 @@ type Result struct {
Compiler string
}
func Build(ctx context.Context, request Request) (Result, error) {
func BuildResolved(ctx context.Context, request Request) (Result, error) {
identity := request.Identity
settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets)
result := Result{
Version: request.Version,
MainPackage: request.Spec.MainPackage,
BinaryName: request.Spec.BinaryName,
Targets: artifact.NormalizeTargets(request.Spec.Targets),
RepositoryDir: identity.RepositoryDir,
ModuleDir: identity.ModuleDir,
ModulePath: identity.ModulePath,
Tag: identity.Tag,
Settings: settings,
Version: identity.Version,
MainPackage: settings.MainPackage,
BinaryName: settings.BinaryName,
Targets: settings.Targets,
}
if !versioncontract.ValidStableVersion(request.Version) {
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, request.Version)
if !versioncontract.ValidStableVersion(identity.Version) {
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version)
}
if request.RepositoryDir == "" {
return result, errors.New("build requires a repository directory")
if identity.RepositoryDir == "" || identity.ModuleDir == "" || identity.ModulePath == "" {
return result, errors.New("build requires a resolved module identity")
}
if len(result.Targets) != 0 {
if request.Spec.MainPackage == "" {
if settings.MainPackage == "" {
return result, errors.New("build requires a main package when targets are selected")
}
if !artifact.ValidComponent(request.Spec.BinaryName) {
return result, fmt.Errorf("unsafe binary name %q", request.Spec.BinaryName)
if !artifact.ValidComponent(settings.BinaryName) {
return result, fmt.Errorf("unsafe binary name %q", settings.BinaryName)
}
for _, target := range result.Targets {
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
@@ -84,11 +92,16 @@ func Build(ctx context.Context, request Request) (Result, error) {
if err := ctx.Err(); err != nil {
return result, fmt.Errorf("build canceled: %w", err)
}
repositoryDir, err := filepath.Abs(request.RepositoryDir)
repositoryDir, err := filepath.Abs(identity.RepositoryDir)
if err != nil {
return result, fmt.Errorf("resolve repository directory: %w", err)
}
result.RepositoryDir = repositoryDir
moduleDir, err := filepath.Abs(identity.ModuleDir)
if err != nil {
return result, fmt.Errorf("resolve module directory: %w", err)
}
result.ModuleDir = moduleDir
commit, err := gitCommit(ctx, repositoryDir)
if err != nil {
return result, err
@@ -100,12 +113,12 @@ func Build(ctx context.Context, request Request) (Result, error) {
}
if len(result.Targets) == 0 {
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir)
result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
return result, nil
}
result.OutputDir = resolvedOutputDir(repositoryDir, request.OutputDir)
declarations := artifact.ExpectedBuild(request.Spec.BinaryName, request.Version, result.Targets)
result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
declarations := artifact.ExpectedBuild(settings.BinaryName, identity.Version, settings.Targets)
filenames := make([]string, len(declarations))
for i, declaration := range declarations {
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)
}
goTool, err := gotool.New(ctx, repositoryDir)
owner := request.ToolOwner
if owner == nil {
owner = gotool.NewOwner(moduleDir)
}
goTool, err := owner.Acquire(ctx)
if err != nil {
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 {
return result, fmt.Errorf("identify Go compiler: %w", err)
}
@@ -135,7 +152,7 @@ func Build(ctx context.Context, request Request) (Result, error) {
if request.Output != nil {
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)
}
artifact := Artifact{Path: path, Filename: filename, Target: target}
@@ -153,26 +170,26 @@ func Build(ctx context.Context, request Request) (Result, error) {
}
}
if smokePath == "" {
temporaryDir, err := os.MkdirTemp("", "releasekit-native-smoke-")
temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-native-smoke-")
if err != nil {
return result, fmt.Errorf("create native smoke directory: %w", err)
}
defer os.RemoveAll(temporaryDir)
smokePath = filepath.Join(temporaryDir, request.Spec.BinaryName)
smokePath = filepath.Join(temporaryDir, settings.BinaryName)
if host.OS == "windows" {
smokePath += ".exe"
}
if request.Output != nil {
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)
}
}
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
}
commitAfter, err := gitCommit(ctx, repositoryDir)
@@ -187,19 +204,6 @@ func Build(ctx context.Context, request Request) (Result, error) {
return result, nil
}
func resolvedOutputDir(repositoryDir, outputDir string) string {
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()
@@ -212,9 +216,9 @@ func gitCommit(ctx context.Context, repositoryDir string) (string, error) {
return strings.TrimSpace(string(output)), nil
}
func buildTarget(ctx context.Context, goTool *gotool.Tool, repositoryDir, mainPackage, outputPath, version string, target Target) error {
func buildTarget(ctx context.Context, goTool *gotool.Tool, moduleDir, mainPackage, outputPath, version string, target Target) error {
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)
return err
}

View File

@@ -5,29 +5,47 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
"go.maximumdirect.net/releasekit/internal/candidate"
"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 {
if spec == nil || len(spec.Targets) == 0 {
return nil
}
selected := *spec
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) 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-")
if err != nil {
return fmt.Errorf("create temporary candidate build output: %w", err)
}
defer os.RemoveAll(temporaryDir)
_, err = Build(ctx, Request{
RepositoryDir: captured.RepositoryDir,
Version: captured.Version,
Spec: selected,
OutputDir: temporaryDir,
Output: output,
_, err = BuildResolved(ctx, Request{
Identity: identity,
Spec: selected,
OutputDir: temporaryDir,
Output: output,
ToolOwner: owner,
})
if err != nil {
return fmt.Errorf("build candidate: %w", err)

View File

@@ -8,18 +8,23 @@ import (
"fmt"
"io"
"os/exec"
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/gotool"
"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")
type Candidate struct {
RepositoryDir string
ModuleDir string
ModulePath string
Tag string
Commit string
Version string
Note string
@@ -27,29 +32,33 @@ type Candidate struct {
type Request struct {
RepositoryDir string
ModuleDir string
Product string
Version string
Validation validation.Settings
AdditionalChecks func(context.Context, Candidate) error
AfterValidate func(context.Context, Candidate) error
AfterValidate func(context.Context, Candidate, *gotool.Owner) error
Output io.Writer
ToolOwner *gotool.Owner
}
func Check(ctx context.Context, request Request) (Candidate, error) {
captured, err := Capture(ctx, request)
if err != nil {
return Candidate{}, err
return captured, err
}
request.ToolOwner = gotool.NewOwner(captured.ModuleDir)
if err := Validate(ctx, request, captured); err != nil {
return Candidate{}, err
return captured, err
}
if request.AfterValidate != nil {
if err := request.AfterValidate(ctx, captured); err != nil {
return Candidate{}, fmt.Errorf("after candidate validation: %w", err)
callbackErr := request.AfterValidate(ctx, captured, request.ToolOwner)
if callbackErr != nil {
return captured, fmt.Errorf("after candidate validation: %w", callbackErr)
}
}
if err := Recheck(ctx, captured, ""); err != nil {
return Candidate{}, err
return captured, err
}
return captured, nil
}
@@ -57,59 +66,76 @@ func Check(ctx context.Context, request Request) (Candidate, error) {
// Capture validates request identity and records one clean local candidate,
// including the note bytes from the captured commit. It does not run checks.
func Capture(ctx context.Context, request Request) (Candidate, error) {
captured := Candidate{Version: 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) == "" {
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 {
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)
if err != nil {
return Candidate{}, err
return captured, err
}
captured.Commit = state.commit
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 != "" {
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"
note, err := gitOutput(ctx, repositoryDir, "show", state.commit+":"+path)
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit)
captured.ModuleDir = identity.ModuleDir
captured.ModulePath = identity.ModulePath
captured.Tag = identity.Tag
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 {
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 {
return Candidate{}, fmt.Errorf("inspect local tag %q: %w", request.Version, 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 {
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
// when supplied, for the captured candidate.
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{
RepositoryDir: captured.RepositoryDir,
ModuleDir: captured.ModuleDir,
Commit: captured.Commit,
Output: request.Output,
Settings: request.Validation,
ToolOwner: owner,
}); err != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
}
if request.AdditionalChecks != nil {
if err := request.AdditionalChecks(ctx, captured); err != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
callbackErr := request.AdditionalChecks(ctx, captured)
if callbackErr != nil {
return fmt.Errorf("validate candidate %s: %w", captured.Commit, callbackErr)
}
}
return nil
@@ -133,23 +159,23 @@ func Recheck(ctx context.Context, captured Candidate, expectedTagObject string)
return fmt.Errorf("worktree or index changed:\n%s", current.status)
}
if expectedTagObject == "" {
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Version); err != nil {
return fmt.Errorf("recheck local tag %q: %w", captured.Version, err)
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Tag); err != nil {
return fmt.Errorf("recheck local tag %q: %w", captured.Tag, err)
} 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
}
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 {
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 {
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" {
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
}
@@ -199,10 +225,10 @@ func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byt
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
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,
Stderr: &stderr,
})

View File

@@ -3,14 +3,18 @@ package candidate
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"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"
@@ -71,7 +75,7 @@ func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
if 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)
}
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) {
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")
@@ -98,7 +163,7 @@ func TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T)
productCalls++
return nil
},
AfterValidate: func(context.Context, Candidate) error {
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
buildCalls++
return nil
},
@@ -130,7 +195,7 @@ func TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails(t *te
productCalls++
return nil
},
AfterValidate: func(context.Context, Candidate) error {
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
buildCalls++
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) {
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")
@@ -423,7 +629,7 @@ func TestCheckRechecksHeadAndWorktreeAfterCallback(t *testing.T) {
func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n")
_, err := Check(context.Background(), Request{
captured, err := Check(context.Background(), Request{
RepositoryDir: repository,
Product: "Example Product",
Version: testVersion,
@@ -435,6 +641,9 @@ func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "appeared during validation") {
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 {

View File

@@ -1,29 +1,26 @@
package delivery
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
"go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
)
func declaredBuildAssets(result internalbuild.Result) ([]gitea.ExpectedAsset, error) {
if len(result.Targets) == 0 {
func declaredBuildAssets(result internalbuild.Result) ([]artifact.ExpectedAsset, error) {
settings := result.Settings
if len(settings.Targets) == 0 {
if len(result.Artifacts) != 0 {
return nil, fmt.Errorf("source-only build result contains artifacts")
}
return nil, nil
}
if len(result.Artifacts) != len(result.Targets) {
if len(result.Artifacts) != len(settings.Targets) {
return nil, fmt.Errorf("build result must contain one artifact for each selected target")
}
declarations := artifact.ExpectedBuild(result.BinaryName, result.Version, result.Targets)
declarations := artifact.ExpectedBuild(settings.BinaryName, result.Version, settings.Targets)
wantByTarget := make(map[artifact.Target]string, len(declarations))
for _, declaration := range declarations {
target := declaration.Target
@@ -35,48 +32,32 @@ func declaredBuildAssets(result internalbuild.Result) ([]gitea.ExpectedAsset, er
}
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 _, artifact := range result.Artifacts {
wantName, ok := wantByTarget[artifact.Target]
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)
for _, builtArtifact := range result.Artifacts {
wantName, ok := wantByTarget[builtArtifact.Target]
if !ok || seenTargets[builtArtifact.Target] || builtArtifact.Filename != wantName {
return nil, fmt.Errorf("build artifact %q does not match a selected target and its declared name", builtArtifact.Filename)
}
seenTargets[artifact.Target] = true
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)
seenTargets[builtArtifact.Target] = true
if filepath.Base(builtArtifact.Path) != builtArtifact.Filename {
return nil, fmt.Errorf("build artifact path %q does not end with filename %q", builtArtifact.Path, builtArtifact.Filename)
}
info, err := os.Stat(artifact.Path)
info, err := os.Stat(builtArtifact.Path)
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() {
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)
if err != nil {
return nil, fmt.Errorf("open build artifact %q: %w", artifact.Filename, err)
}
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,
assets = append(assets, artifact.ExpectedAsset{
Filename: builtArtifact.Filename,
SHA256: builtArtifact.SHA256,
Size: info.Size(),
Path: artifact.Path,
Path: builtArtifact.Path,
})
}
manifest, err := gitea.BuildManifest(assets)
manifest, err := artifact.BuildManifest(assets)
if err != nil {
return nil, fmt.Errorf("build checksum manifest: %w", err)
}

View File

@@ -8,8 +8,8 @@ import (
"strings"
"testing"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
"go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
)
func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
@@ -25,8 +25,10 @@ func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
t.Fatal(err)
}
result, err := declaredBuildAssets(internalbuild.Result{
Version: "v1.2.3", BinaryName: "app",
Targets: []internalbuild.Target{{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"}},
Version: "v1.2.3",
Settings: artifact.NormalizeSettings("./cmd/app", "app", []artifact.Target{
{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"},
}),
Artifacts: []internalbuild.Artifact{
{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)},
@@ -35,7 +37,7 @@ func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
if err != nil {
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)
}
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) {
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-arm64")
contents := []byte("built application")
@@ -68,7 +56,7 @@ func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) {
t.Fatal(err)
}
_, 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{{
Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(contents),
}},

View File

@@ -9,12 +9,15 @@ import (
"path/filepath"
"strings"
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
"go.maximumdirect.net/releasekit/internal/artifact"
internalbuild "go.maximumdirect.net/releasekit/internal/build"
"go.maximumdirect.net/releasekit/internal/candidate"
"go.maximumdirect.net/releasekit/internal/forge"
"go.maximumdirect.net/releasekit/internal/git"
"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
@@ -29,23 +32,29 @@ const (
type Request struct {
RepositoryDir string
ModuleDir string
Product string
Version string
Destination gitea.Destination
ExpectedTag string
Backend forge.Backend
Build *internalbuild.Spec
Prebuilt *internalbuild.Result
Output io.Writer
}
type Result struct {
RepositoryDir string
ModuleDir string
ModulePath string
Tag string
CandidateCommit string
ReleaseURL string
State State
Matching []gitea.AssetIdentity
Uploaded []gitea.AssetIdentity
Pending []gitea.AssetIdentity
Conflicting []gitea.AssetIdentity
Uncertain []gitea.AssetIdentity
Matching []AssetIdentity
Uploaded []AssetIdentity
Pending []AssetIdentity
Conflicting []AssetIdentity
Uncertain []AssetIdentity
}
func Deliver(ctx context.Context, request Request) (Result, error) {
@@ -59,28 +68,60 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
if request.Build != nil && request.Prebuilt != nil {
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 {
return result, fmt.Errorf("resolve repository directory: %w", err)
}
source, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version)
if err != nil {
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)
result.RepositoryDir = repositoryDir
commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil {
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 {
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
@@ -90,119 +131,135 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
return result, fmt.Errorf("create temporary delivery build directory: %w", err)
}
defer os.RemoveAll(temporaryDir)
built, err := internalbuild.Build(ctx, internalbuild.Request{
RepositoryDir: repositoryDir,
Version: request.Version,
Spec: *request.Build,
OutputDir: filepath.Join(temporaryDir, "assets"),
Output: request.Output,
built, err := internalbuild.BuildResolved(ctx, internalbuild.Request{
Identity: identity,
Spec: *request.Build,
OutputDir: filepath.Join(temporaryDir, "assets"),
Output: request.Output,
ToolOwner: gotool.NewOwner(identity.ModuleDir),
})
if err != nil {
return result, fmt.Errorf("build delivery assets: %w", err)
}
build = &built
}
var assets []gitea.ExpectedAsset
var assets []artifact.ExpectedAsset
if build != nil {
assets, err = declaredBuildAssets(*build)
if err != nil {
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
}
if len(assets) > 0 {
if err := gitea.VerifyLocalAssets(assets); err != nil {
return result, fmt.Errorf("verify build assets: %w", err)
if err := artifact.VerifyLocalAssets(assets); err != nil {
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 {
current, err := git.InspectTaggedSource(ctx, repositoryDir, request.Version)
if build != nil && len(build.Settings.Targets) != 0 {
current, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
if err != nil {
return result, fmt.Errorf("recheck tagged source after build: %w", err)
}
if 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")
}
}
releaseResult, err := (gitea.Client{}).EnsureRelease(ctx, gitea.Request{
Destination: request.Destination,
Version: request.Version,
Commit: source.TagCommit,
Note: string(note),
})
release, pageEvidence, err := coordinateRelease(ctx, request.Backend, identity.Tag, commit, string(note))
if err != nil {
result.State = stateForError(err, false)
return result, err
}
result.ReleaseURL = releaseResult.Release.URL
result.ReleaseURL = release.URL
if len(assets) == 0 {
result.State = Complete
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 {
result.State = NotAttempted
if releaseResult.WriteAttempted {
if pageEvidence.Attempted {
result.State = Partial
}
result.Uncertain = assetIdentities(assets)
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.Uploaded = uploadResult.Uploaded
result.Pending = uploadResult.Pending
result.Conflicting = uploadResult.Conflicting
result.Uncertain = uploadResult.Uncertain
result.State = State(uploadResult.State)
if result.State == NotAttempted && releaseResult.WriteAttempted {
if result.State == NotAttempted && pageEvidence.Attempted {
result.State = Partial
}
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 len(assets) != 0 {
return errors.New("assets require a build identity")
}
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 {
return errors.New("page-only delivery cannot include binary assets")
}
return nil
}
if !build.SourceVerified {
return errors.New("build source was not verified as clean and unchanged during compilation")
if len(assets) != len(build.Settings.Targets)+1 || assets[len(assets)-1].Filename != artifact.ManifestFilename {
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)
if err != nil {
return fmt.Errorf("resolve build repository: %w", err)
}
if buildRepository != repositoryDir || build.CandidateCommit != commit || build.Version != version {
return errors.New("build result does not identify the selected tagged source")
buildModule, err := filepath.Abs(build.ModuleDir)
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 nil
}
func stateForError(err error, pageCreated bool) State {
var failure *gitea.Failure
var failure *forge.Failure
if errors.As(err, &failure) {
switch failure.Kind {
case gitea.FailureConflict:
case forge.FailureConflict:
return Conflict
case gitea.FailureUnknown:
case forge.FailureUnknown:
return Unknown
}
}
@@ -212,10 +269,10 @@ func stateForError(err error, pageCreated bool) State {
return NotAttempted
}
func assetIdentities(assets []gitea.ExpectedAsset) []gitea.AssetIdentity {
result := make([]gitea.AssetIdentity, 0, len(assets))
func assetIdentities(assets []artifact.ExpectedAsset) []AssetIdentity {
result := make([]AssetIdentity, 0, len(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
}

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,257 @@
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, err := remoteAssetDigest(ctx, backend, matches[0].Handle)
if err != nil {
observation.State = AssetUnverifiable
observation.Err = err
} else if 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) (string, error) {
stream, err := backend.OpenAsset(ctx, handle)
if err != nil {
return "", err
}
hasher := sha256.New()
_, readErr := io.Copy(hasher, stream)
closeErr := stream.Close()
if err := errors.Join(readErr, closeErr); err != nil {
return "", &forge.Failure{Kind: forge.FailureUnverifiable, Err: err}
}
return hex.EncodeToString(hasher.Sum(nil)), 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,456 @@
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)
}
}
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: "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
}

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

@@ -0,0 +1,222 @@
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 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": "",
},
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
}

View File

@@ -0,0 +1,195 @@
package git
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
func TestBlobReaderReadsLooseAndPackedObjects(t *testing.T) {
for _, packed := range []bool{false, true} {
name := "loose"
if packed {
name = "packed"
}
t.Run(name, func(t *testing.T) {
fixture := newRemoteFixture(t)
binary := []byte{0, '\n', 0xff, 'b', '\n', 0}
writeRepoFile(t, fixture.work, "empty.dat", "")
writeRepoFile(t, fixture.work, "binary.dat", string(binary))
gitRun(t, fixture.work, "add", ".")
gitRun(t, fixture.work, "commit", "-m", "add binary fixtures")
want := map[string][]byte{
gitText(t, fixture.work, "rev-parse", "HEAD:source.txt"): []byte("candidate"),
gitText(t, fixture.work, "rev-parse", "HEAD:empty.dat"): {},
gitText(t, fixture.work, "rev-parse", "HEAD:binary.dat"): binary,
}
if packed {
gitRun(t, fixture.work, "gc", "--aggressive", "--prune=now")
}
reader := NewBlobReader(t.Context(), fixture.work)
defer reader.Close()
for repeat := 0; repeat < 2; repeat++ {
for objectID, expected := range want {
got, err := reader.Read(t.Context(), objectID)
if err != nil {
t.Fatalf("Read(%s) error = %v", objectID, err)
}
if !bytes.Equal(got, expected) {
t.Errorf("Read(%s) = %v, want %v", objectID, got, expected)
}
}
}
})
}
}
func TestBlobReaderMissingObjectKeepsBatchSessionUsable(t *testing.T) {
fixture := newRemoteFixture(t)
objectID := gitText(t, fixture.work, "rev-parse", "HEAD:source.txt")
reader := NewBlobReader(t.Context(), fixture.work)
defer reader.Close()
missing := strings.Repeat("0", 40)
if _, err := reader.Read(t.Context(), missing); err == nil || !strings.Contains(err.Error(), "missing") {
t.Fatalf("Read(missing) error = %v, want contextual missing-object error", err)
}
contents, err := reader.Read(t.Context(), objectID)
if err != nil || string(contents) != "candidate" {
t.Fatalf("Read(existing) = %q, %v after missing request", contents, err)
}
}
func TestBlobReaderPreservesHexCaseAndArbitraryBodyBytes(t *testing.T) {
installFakeGit(t, `while IFS= read -r object; do
upper=$(printf '%s' "$object" | tr 'a-f' 'A-F')
printf '%s blob 4\n' "$upper"
printf 'a\000b\n\n'
done`)
objectID := strings.Repeat("abcdef0123", 4)
reader := NewBlobReader(t.Context(), t.TempDir())
contents, err := reader.Read(t.Context(), objectID)
if err != nil {
t.Fatal(err)
}
if want := []byte{'a', 0, 'b', '\n'}; !bytes.Equal(contents, want) {
t.Fatalf("Read() = %v, want %v", contents, want)
}
if err := reader.Close(); err != nil {
t.Fatal(err)
}
}
func TestBlobReaderRejectsInvalidHeadersAndFraming(t *testing.T) {
for _, testCase := range []struct {
name string
response string
want string
}{
{name: "wrong object", response: `printf '%040d blob 0\n\n' 0`, want: "does not match request"},
{name: "wrong type", response: `printf '%s tree 0\n\n' "$object"`, want: `has type "tree"`},
{name: "invalid size", response: `printf '%s blob -1\n' "$object"`, want: "invalid Git blob size"},
{name: "invalid framing", response: `printf '%s blob 0\nx' "$object"`, want: "invalid Git blob framing"},
} {
t.Run(testCase.name, func(t *testing.T) {
installFakeGit(t, "IFS= read -r object\n"+testCase.response)
reader := NewBlobReader(t.Context(), t.TempDir())
_, err := reader.Read(t.Context(), strings.Repeat("d", 40))
if err == nil || !strings.Contains(err.Error(), testCase.want) {
t.Fatalf("Read() error = %v, want %q", err, testCase.want)
}
if closeErr := reader.Close(); !strings.Contains(closeErr.Error(), testCase.want) {
t.Fatalf("Close() error = %v, want original protocol error", closeErr)
}
})
}
}
func TestBlobReaderTruncatedBodyAbortsAndKeepsOriginalCause(t *testing.T) {
installFakeGit(t, `IFS= read -r object
printf '%s blob 8\n' "$object"
printf 'short'
exit 0`)
reader := NewBlobReader(t.Context(), t.TempDir())
_, err := reader.Read(t.Context(), strings.Repeat("a", 40))
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("Read() error = %v, want truncated-body cause", err)
}
if closeErr := reader.Close(); !errors.Is(closeErr, io.ErrUnexpectedEOF) {
t.Fatalf("Close() error = %v, want original read cause", closeErr)
}
}
func TestBlobReaderCancellationDuringBodyReadReapsChild(t *testing.T) {
ready := filepath.Join(t.TempDir(), "ready")
installFakeGit(t, `IFS= read -r object
printf '%s blob 1048576\npartial' "$object"
: > "$RELEASEKIT_GIT_READER_READY"
exec sleep 60`)
t.Setenv("RELEASEKIT_GIT_READER_READY", ready)
ctx, cancel := context.WithCancel(t.Context())
reader := NewBlobReader(ctx, t.TempDir())
result := make(chan error, 1)
go func() {
_, err := reader.Read(ctx, strings.Repeat("b", 40))
result <- err
}()
waitForFile(t, ready)
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("Read() error = %v, want context cancellation", err)
}
case <-time.After(5 * time.Second):
t.Fatal("Read() did not return after cancellation")
}
if err := reader.Close(); !errors.Is(err, context.Canceled) {
t.Fatalf("Close() error = %v, want original cancellation cause", err)
}
}
func TestBlobReaderPreservesGitFailureAndStderr(t *testing.T) {
installFakeGit(t, `printf 'fixture Git failure\n' >&2
exit 23`)
reader := NewBlobReader(t.Context(), t.TempDir())
_, err := reader.Read(t.Context(), strings.Repeat("c", 40))
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 23 {
t.Fatalf("Read() error = %v, want Git exit code 23", err)
}
if !strings.Contains(err.Error(), "fixture Git failure") {
t.Fatalf("Read() error = %v, want captured Git stderr", err)
}
}
func installFakeGit(t *testing.T, script string) {
t.Helper()
directory := t.TempDir()
path := filepath.Join(directory, "git")
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+script+"\n"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
}
func waitForFile(t *testing.T, path string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(path); err == nil {
return
} else if !errors.Is(err, os.ErrNotExist) {
t.Fatal(fmt.Errorf("inspect readiness signal: %w", err))
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("child did not create readiness signal")
}

155
internal/git/path.go Normal file
View File

@@ -0,0 +1,155 @@
package git
import (
"context"
"fmt"
"path"
"path/filepath"
"strings"
)
// PathResolver traverses committed paths, sharing reference rules between
// release identity and validation. Lookups include both files and directories.
type PathResolver struct {
RepositoryDir string
Lookup func(context.Context, string) (TreeEntry, bool, error)
ReadLink func(context.Context, TreeEntry) (string, error)
}
// DestinationKind classifies a committed local destination.
type DestinationKind string
const (
DestinationEntry DestinationKind = "entry"
DestinationDirectory DestinationKind = "directory"
DestinationMissing DestinationKind = "missing"
DestinationOutsideCheckout DestinationKind = "outside-checkout"
DestinationSubmodule DestinationKind = "submodule"
DestinationSymlinkCycle DestinationKind = "symlink-cycle"
)
// Destination records the resolved identity and its classification.
type Destination struct {
Kind DestinationKind
Path string
}
// ResolveDestination resolves local destinations using the captured Git tree.
// Relative destinations start at the source directory; absolute destinations
// within the repository directory map back to committed paths.
func (resolver PathResolver) ResolveDestination(ctx context.Context, sourcePath, destination string) (Destination, error) {
if err := ctx.Err(); err != nil {
return Destination{}, err
}
directory := path.Dir(sourcePath)
if path.IsAbs(destination) {
relative, inside, err := resolver.relativeAbsoluteDestination(destination)
if err != nil {
return Destination{}, err
}
if !inside {
return Destination{Kind: DestinationOutsideCheckout, Path: destination}, nil
}
directory, destination = ".", relative
}
return resolver.resolveDestination(ctx, directory, strings.Split(destination, "/"), make(map[string]bool))
}
func (resolver PathResolver) resolveDestination(ctx context.Context, directory string, components []string, active map[string]bool) (Destination, error) {
for index, component := range components {
if err := ctx.Err(); err != nil {
return Destination{}, err
}
remaining := components[index+1:]
switch component {
case "", ".":
continue
case "..":
if directory == "." {
return Destination{Kind: DestinationOutsideCheckout, Path: unresolvedPath("..", remaining)}, nil
}
directory = path.Dir(directory)
continue
}
partial := path.Join(directory, component)
entry, exists, err := resolver.Lookup(ctx, partial)
if err != nil {
return Destination{}, err
}
if !exists {
return Destination{Kind: DestinationMissing, Path: unresolvedPath(partial, remaining)}, nil
}
if entry.Type == "tree" {
directory = partial
continue
}
if entry.Mode == "160000" {
return Destination{Kind: DestinationSubmodule, Path: unresolvedPath(partial, remaining)}, nil
}
if entry.Mode == "120000" {
if active[partial] {
return Destination{Kind: DestinationSymlinkCycle, Path: partial}, nil
}
linkText, err := resolver.ReadLink(ctx, entry)
if err != nil {
return Destination{}, fmt.Errorf("read committed symlink %q: %w", partial, err)
}
target := linkText
targetDirectory := directory
if path.IsAbs(target) {
relative, inside, err := resolver.relativeAbsoluteDestination(target)
if err != nil {
return Destination{}, err
}
if !inside {
return Destination{Kind: DestinationOutsideCheckout, Path: unresolvedPath(target, remaining)}, nil
}
targetDirectory, target = ".", relative
}
active[partial] = true
destination, err := resolver.resolveDestination(ctx, targetDirectory, strings.Split(target, "/"), active)
delete(active, partial)
if err != nil || len(remaining) == 0 {
return destination, err
}
switch destination.Kind {
case DestinationDirectory:
return resolver.resolveDestination(ctx, destination.Path, remaining, active)
case DestinationEntry:
destination.Kind = DestinationMissing
case DestinationSymlinkCycle:
return destination, nil
}
destination.Path = unresolvedPath(destination.Path, remaining)
return destination, nil
}
if len(remaining) != 0 {
return Destination{Kind: DestinationMissing, Path: unresolvedPath(partial, remaining)}, nil
}
return Destination{Kind: DestinationEntry, Path: partial}, nil
}
return Destination{Kind: DestinationDirectory, Path: directory}, nil
}
func (resolver PathResolver) relativeAbsoluteDestination(destination string) (string, bool, error) {
root, err := filepath.Abs(resolver.RepositoryDir)
if err != nil {
return "", false, fmt.Errorf("resolve candidate repository directory: %w", err)
}
root = filepath.ToSlash(root)
if destination == root {
return ".", true, nil
}
// Preserve the suffix for component traversal, including symlinks before '..'.
relative, inside := strings.CutPrefix(destination, strings.TrimSuffix(root, "/")+"/")
return relative, inside, nil
}
// unresolvedPath preserves components that could not be traversed. Cleaning
// them would hide missing entries, non-directories, or checkout boundaries.
func unresolvedPath(base string, remaining []string) string {
if len(remaining) == 0 {
return base
}
return base + "/" + strings.Join(remaining, "/")
}

View File

@@ -0,0 +1,59 @@
package git
import (
"context"
"runtime"
"testing"
)
func BenchmarkPerformanceBlobReader(b *testing.B) {
fixture := newRemoteFixture(b)
objectID := gitText(b, fixture.work, "rev-parse", "HEAD:source.txt")
const expectedBytes = int64(len("candidate"))
b.Run("new-session-per-read", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(expectedBytes)
b.ResetTimer()
b.ReportMetric(float64(expectedBytes), "bytes/op")
b.ReportMetric(1, "blobs/op")
for i := 0; i < b.N; i++ {
reader := NewBlobReader(context.Background(), fixture.work)
contents, err := reader.Read(context.Background(), objectID)
if err != nil {
b.Fatal(err)
}
if int64(len(contents)) != expectedBytes {
b.Fatalf("read %d bytes, want %d", len(contents), expectedBytes)
}
if err := reader.Close(); err != nil {
b.Fatal(err)
}
runtime.KeepAlive(contents)
}
})
b.Run("shared-session", func(b *testing.B) {
reader := NewBlobReader(context.Background(), fixture.work)
b.Cleanup(func() {
if err := reader.Close(); err != nil {
b.Error(err)
}
})
b.ReportAllocs()
b.SetBytes(expectedBytes)
b.ResetTimer()
b.ReportMetric(float64(expectedBytes), "bytes/op")
b.ReportMetric(1, "blobs/op")
for i := 0; i < b.N; i++ {
contents, err := reader.Read(context.Background(), objectID)
if err != nil {
b.Fatal(err)
}
if int64(len(contents)) != expectedBytes {
b.Fatalf("read %d bytes, want %d", len(contents), expectedBytes)
}
runtime.KeepAlive(contents)
}
})
}

View File

@@ -8,30 +8,51 @@ import (
// PrepareTaggedCheckout fetches one explicit tag ref, checks its peeled commit
// against expectedCommit, and checks out that commit detached.
func PrepareTaggedCheckout(ctx context.Context, repositoryDir, version, remote, expectedCommit string) error {
if !validVersionRef(version) || !validObjectID(expectedCommit) {
return fmt.Errorf("invalid tagged checkout identity %q at %q", expectedCommit, version)
func PrepareTaggedCheckout(ctx context.Context, repositoryDir, tag, remote, expectedCommit string) error {
if err := checkTagRef(ctx, repositoryDir, tag); err != nil {
return err
}
ref := "refs/tags/" + version
if !validObjectID(expectedCommit) {
return fmt.Errorf("invalid tagged checkout commit %q for tag %q", expectedCommit, tag)
}
ref := "refs/tags/" + tag
if _, err := run(ctx, repositoryDir, nil, "fetch", "--no-tags", remote, ref+":"+ref); err != nil {
return fmt.Errorf("fetch tag %s from remote %s: %w", version, remote, err)
return fmt.Errorf("fetch tag %s from remote %s: %w", tag, remote, err)
}
source, err := InspectTaggedSource(ctx, repositoryDir, version)
source, err := InspectTaggedSource(ctx, repositoryDir, tag)
if err != nil {
return err
}
if !strings.EqualFold(source.TagCommit, expectedCommit) {
return fmt.Errorf("tag %s resolves to commit %s, expected %s", version, source.TagCommit, expectedCommit)
return fmt.Errorf("tag %s resolves to commit %s, expected %s", tag, source.TagCommit, expectedCommit)
}
if _, err := run(ctx, repositoryDir, nil, "checkout", "--detach", source.TagCommit); err != nil {
return fmt.Errorf("check out tag %s at %s: %w", version, source.TagCommit, err)
return fmt.Errorf("check out tag %s at %s: %w", tag, source.TagCommit, err)
}
head, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "HEAD^{commit}")
return VerifyTaggedCheckout(ctx, repositoryDir, tag, expectedCommit)
}
// VerifyTaggedCheckout confirms that the existing local tag, HEAD, and clean
// worktree all identify the expected commit. It does not fetch or check out.
func VerifyTaggedCheckout(ctx context.Context, repositoryDir, tag, expectedCommit string) error {
if err := checkTagRef(ctx, repositoryDir, tag); err != nil {
return err
}
if !validObjectID(expectedCommit) {
return fmt.Errorf("invalid tagged checkout commit %q for tag %q", expectedCommit, tag)
}
source, err := InspectTaggedSource(ctx, repositoryDir, tag)
if err != nil {
return fmt.Errorf("verify prepared checkout HEAD: %w", err)
return err
}
if !strings.EqualFold(strings.TrimSpace(head), expectedCommit) {
return fmt.Errorf("prepared checkout HEAD is %s, expected %s", strings.TrimSpace(head), expectedCommit)
if source.Status != "" {
return fmt.Errorf("tagged checkout must be clean:\n%s", source.Status)
}
if !strings.EqualFold(source.TagCommit, expectedCommit) {
return fmt.Errorf("tag %s resolves to commit %s, expected %s", tag, source.TagCommit, expectedCommit)
}
if !strings.EqualFold(source.Head, expectedCommit) {
return fmt.Errorf("checkout HEAD is %s, expected %s", source.Head, expectedCommit)
}
return nil
}

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