50 Commits

Author SHA1 Message Date
3b8dd87c4b Prepare v0.11.0 release notes and adoption guidance 2026-12-06 03:48:03 +00:00
fe346c9036 Remove completed release plans and remediation notes 2026-12-06 03:45:20 +00:00
697cd27cde Keep Go readiness separate from publication file checks 2026-12-06 03:39:11 +00:00
d733298bd9 Stream discarded CI log lines without retaining them 2026-12-06 03:35:18 +00:00
4b515404a8 Limit readiness scans to selected package inputs 2026-12-06 03:33:52 +00:00
3f7dd4b2e5 Index observed CI pipeline identities 2026-12-06 03:31:09 +00:00
c930788bf8 Clarify that implementation needs no published example pin 2026-12-06 03:29:36 +00:00
6c94b1fb85 Keep Go package patterns usable during readiness 2026-12-06 03:26:00 +00:00
d5154cf59d Distinguish production tags from complete diagnostic tags 2026-12-06 03:21:39 +00:00
0205f32f28 Describe selected source and version behavior accurately 2026-12-06 03:17:26 +00:00
76252cb5d0 Accept consistent overlaps in CI pipeline pagination 2026-12-06 03:16:17 +00:00
67a560e3fd Recover rejected rehearsals without remote credentials 2026-12-06 03:15:16 +00:00
b4f984fd5b Retain safe CI diagnostics in rehearsal results 2026-12-06 03:13:42 +00:00
b74c054c02 Route diagnostic delivery through the public facade 2026-12-06 03:10:47 +00:00
2b5032d8c9 Clean known rehearsal pages after their tags are removed 2026-12-06 02:59:33 +00:00
75823d6c82 Distinguish rejected rehearsal pushes from uncertain writes 2026-12-06 02:57:35 +00:00
0906cf7094 Validate module readiness without a synthetic version 2026-12-06 02:51:56 +00:00
4088923a45 Keep required local inputs separate from committed source 2026-12-06 02:50:12 +00:00
c626ee4e27 Validate selected release configuration during readiness 2026-12-06 02:49:22 +00:00
633df7a02b Record algorithmic audit findings 2026-12-06 02:39:19 +00:00
fad1567e54 Record additional integration audit findings 2026-12-06 02:01:19 +00:00
67c836388b Record implementation review findings 2026-12-06 01:38:44 +00:00
dd9e177420 Complete rehearsal guidance and integrated verification 2026-12-05 23:48:37 +00:00
3524d8bbb6 Wire rehearsal commands and tagged workflows 2026-12-05 23:35:52 +00:00
8caeeb3d78 Resume and safely clean recorded rehearsals 2026-12-05 23:26:01 +00:00
a348da32da Coordinate diagnostic attempts and CI observation 2026-12-05 23:14:15 +00:00
5ddb7453ec Verify diagnostic deliveries inside CI 2026-12-05 23:00:04 +00:00
4210552cb8 Observe rehearsal resources and support safe cleanup 2026-12-05 22:52:46 +00:00
181e5a030c Capture diagnostic identities and rehearsal records 2026-12-05 22:45:28 +00:00
6f01e9ef0a Add pinned tools for source-only releases 2026-12-05 22:30:21 +00:00
d185df5fd1 Remove the release dependency from the implementation plan 2026-12-05 22:27:25 +00:00
000e9ef9b9 Add read-only release readiness validation 2026-12-05 22:03:34 +00:00
92b820b234 Select delivery credentials by execution context 2026-12-05 21:41:34 +00:00
697ab32715 Preserve release identity in records and receipts 2026-12-05 21:34:51 +00:00
bbee996f84 Carry source identity through builds and delivery 2026-12-05 21:22:38 +00:00
3b925231d5 Validate and publish source-only candidates 2026-12-05 21:05:56 +00:00
0f9923d230 Resolve source and diagnostic release identities 2026-12-05 20:57:10 +00:00
b0fce88a51 Normalize source and publication selection 2026-12-05 20:47:58 +00:00
8f3b59b5f2 Plan the next release implementation 2026-12-05 19:42:51 +00:00
652dcfc7b1 Draft source-release identity and Woodpecker rehearsal ADRs 2026-12-05 19:24:49 +00:00
87e4305889 Consolidate settled roadmap decisions and planning details 2026-12-05 19:19:33 +00:00
751ce6d54a Clarify when Go module version constraints apply 2026-12-05 19:15:39 +00:00
f4a0064342 Plan source-only repository release support 2026-12-05 19:13:45 +00:00
bde8a830df Record application versioning and module identity decisions 2026-12-05 19:06:57 +00:00
ba73721d51 Record readiness validation decisions 2026-12-05 18:59:51 +00:00
eed068bd22 Plan end-to-end Woodpecker delivery rehearsals 2026-12-05 17:12:12 +00:00
7def1fd840 Clarify planned local and CI credential selection 2026-12-05 17:07:44 +00:00
86723750d3 Outline proposals for the next release 2026-12-03 01:46:08 +00:00
82bac1a3ab Prepare the v0.10.0 release notes 2026-11-17 15:31:10 +00:00
0f0bace29e Upgrade to Go 1.27 and refresh dependencies 2026-11-17 15:26:46 +00:00
160 changed files with 11924 additions and 588 deletions

View File

@@ -2,9 +2,8 @@
ReleaseKit is an opinionated Go library and executable for a shared release ReleaseKit is an opinionated Go library and executable for a shared release
process. The Go module, root `releasekit` facade, `buildinfo` runtime package, process. The Go module, root `releasekit` facade, `buildinfo` runtime package,
local candidate check, source-tag publication API, selected-target build API, local candidate check, source-tag publication, selected-target build, tagged
tagged-source delivery API, and the `version`, `check`, `publish`, `build`, delivery, readiness, and rehearsal APIs and commands are implemented. ReleaseKit's source-only
`deliver`, and `ci-deliver` commands are implemented. ReleaseKit's source-only
maintainer procedure and prepared Woodpecker workflow for hosted note-page maintainer procedure and prepared Woodpecker workflow for hosted note-page
delivery are documented. ReleaseKit does not declare binary deliverables. delivery are documented. ReleaseKit does not declare binary deliverables.
@@ -14,9 +13,9 @@ 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 The [v0.6.0 release note](docs/releases/v0.6.0.md) describes the delivery API
and profile migration. and profile migration.
Release operations can select one Go module within a repository. The repository Release operations can select a Go module or a general source directory within a
root remains the default; a selected module's declared import path and physical repository. The repository root remains the default; the selected publication
directory determine its complete Git tag and module-local release note. See the mode determines the complete Git tag and release-note location. See the
[candidate check](docs/consumers/check.md), [candidate check](docs/consumers/check.md),
[publication](docs/consumers/publish.md), and [publication](docs/consumers/publish.md), and
[multi-module example](examples/multi-module/). [multi-module example](examples/multi-module/).
@@ -40,8 +39,7 @@ go run ./cmd/releasekit version
``` ```
The local candidate check validates a committed release note, runs the standard The local candidate check validates a committed release note, runs the standard
offline Go suite with any selected shared validation checks, and then runs offline Go suite when Go is selected, and runs selected shared and product checks:
configured product checks:
```sh ```sh
go run ./cmd/releasekit check v1.2.3 go run ./cmd/releasekit check v1.2.3
@@ -62,8 +60,8 @@ failure recovery.
dependencies, upgrades, and CI adoption. dependencies, upgrades, and CI adoption.
- [Contributor guide](docs/development.md): orientation, validation, and selective - [Contributor guide](docs/development.md): orientation, validation, and selective
policy reading. policy reading.
- [CLI contract](docs/cli.md): the `version`, `check`, `publish`, `build`, - [CLI contract](docs/cli.md): candidate, publication, delivery, readiness,
`deliver`, and `ci-deliver` commands. rehearsal, and recovery commands.
- [Configuration](docs/config.md): profile fields and child-command settings. - [Configuration](docs/config.md): profile fields and child-command settings.
- [Runtime version guidance](docs/consumers/runtime-version.md): how applications - [Runtime version guidance](docs/consumers/runtime-version.md): how applications
read their embedded version through `buildinfo`. read their embedded version through `buildinfo`.
@@ -71,6 +69,9 @@ failure recovery.
injected application version. injected application version.
- [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and - [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and
report hosted page and asset status. report hosted page and asset status.
- [Readiness guidance](docs/consumers/readiness.md) and
[rehearsal guidance](docs/consumers/rehearsal.md): inspect setup and exercise
the tagged delivery workflow with temporary resources.
- [Gitea integration](docs/integrations/gitea.md): hosted release-page - [Gitea integration](docs/integrations/gitea.md): hosted release-page
operations and their failure behavior. operations and their failure behavior.
- [Candidate check guidance](docs/consumers/check.md): local candidate validation - [Candidate check guidance](docs/consumers/check.md): local candidate validation

View File

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

View File

@@ -803,7 +803,7 @@ func newBuildConsumer(t *testing.T, mainSource string) string {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
writeBuildFixture(t, repository, "go.mod", module) writeBuildFixture(t, repository, "go.mod", module)
writeBuildFixture(t, repository, "cmd/app/main.go", mainSource) writeBuildFixture(t, repository, "cmd/app/main.go", mainSource)
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n") writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
@@ -821,7 +821,7 @@ func writeNestedBuildConsumer(t *testing.T, repository, moduleDir, modulePath, m
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module %s\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", modulePath, filepath.ToSlash(root)) module := fmt.Sprintf("module %s\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", modulePath, filepath.ToSlash(root))
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "go.mod")), module) writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "go.mod")), module)
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "cmd/app/main.go")), mainSource) writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "cmd/app/main.go")), mainSource)
return filepath.Join(repository, filepath.FromSlash(moduleDir)) return filepath.Join(repository, filepath.FromSlash(moduleDir))
@@ -833,7 +833,7 @@ func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
writeFile(t, repository, "go.mod", module) writeFile(t, repository, "go.mod", module)
writeFile(t, repository, ".gitignore", "dist/\n") writeFile(t, repository, ".gitignore", "dist/\n")
writeFile(t, repository, "cmd/app/main.go", mainSource) writeFile(t, repository, "cmd/app/main.go", mainSource)

View File

@@ -19,7 +19,7 @@ func TestVersionInConsumerExecutable(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
module := fmt.Sprintf(`module example.com/versionfixture module := fmt.Sprintf(`module example.com/versionfixture
go 1.26.0 go 1.27.0
require go.maximumdirect.net/releasekit v0.0.0 require go.maximumdirect.net/releasekit v0.0.0

View File

@@ -10,7 +10,7 @@ import (
"go.maximumdirect.net/releasekit/internal/validation" "go.maximumdirect.net/releasekit/internal/validation"
) )
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH. // ErrInvalidVersion reports an identifier that does not match its selected format.
var ErrInvalidVersion = candidate.ErrInvalidVersion var ErrInvalidVersion = candidate.ErrInvalidVersion
// ErrUnexpectedPushURL reports that the effective publication push URL does // ErrUnexpectedPushURL reports that the effective publication push URL does
@@ -18,15 +18,22 @@ var ErrInvalidVersion = candidate.ErrInvalidVersion
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
// Candidate identifies one committed local source revision selected for // Candidate identifies one committed local source revision selected for
// validation. ModuleDir is the absolute selected module directory, ModulePath // validation. SourceDir is the absolute selected source directory. ModuleDir
// is its declared Go import path, and Tag is the complete derived Git tag. // and ModulePath identify a selected Go module and are empty for source-only
// releases. Tag is the complete derived Git tag.
type Candidate struct { type Candidate struct {
RepositoryDir string RepositoryDir string
SourceDir string
SourceSubdir string
GoEnabled bool
Publication PublicationMode
VersionFormat VersionFormat
VersionPrefix string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
Tag string Tag string
Commit string Commit string
Version string // selected stable semantic version. Version string // selected production identifier.
} }
// ReleaseRequest contains the inputs used to validate and optionally build one // ReleaseRequest contains the inputs used to validate and optionally build one
@@ -39,9 +46,12 @@ type ReleaseRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects // ModuleDir selects a repository-relative module directory; empty selects
// the repository root. // the repository root.
ModuleDir string ModuleDir string
Product string // Source selects explicit source and publication capabilities. Nil retains
Version string // stable semantic version, independent of the derived Git tag. // the ModuleDir Go-module shorthand.
Remote string Source *SourceSpec
Product string
Version string // production identifier, independent of the derived Git tag.
Remote string
// ExpectedPushURL optionally requires Publish's resolved push URL to match // ExpectedPushURL optionally requires Publish's resolved push URL to match
// this string exactly before validation or tag creation. Check ignores this // this string exactly before validation or tag creation. Check ignores this
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL. // publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
@@ -137,12 +147,10 @@ type GoValidationSpec struct {
} }
// Check validates one local, committed release candidate. It requires a clean // Check validates one local, committed release candidate. It requires a clean
// worktree and index on main, a selected module declaration and module-local // worktree and index on main, a committed source-local note matching Product
// committed note matching Product and Version, and an unused local tag. An // and Version, and an unused local tag. A Go selection also requires a module
// empty ModuleDir selects the repository root. The module declaration // declaration. Nil Source retains the ModuleDir Go-module shorthand. Check
// determines the full Git tag for the semantic Version. It always runs the // runs the offline Go test suite when Go is enabled, then calls
// offline Go test suite with the available compatible local Go toolchain and
// Go host target, then calls
// AdditionalChecks when supplied. Validation.Go.Race runs that one suite with // AdditionalChecks when supplied. Validation.Go.Race runs that one suite with
// the race detector, Validation.Go.FullVet runs go vet after the suite instead // the race detector, Validation.Go.FullVet runs go vet after the suite instead
// of test-time vet, and Validation.Go.CompileTargets compiles all packages for // of test-time vet, and Validation.Go.CompileTargets compiles all packages for
@@ -166,7 +174,7 @@ type GoValidationSpec struct {
// Nil disables the check; an empty object enables it. Outside-checkout // Nil disables the check; an empty object enables it. Outside-checkout
// destinations are reported as out of scope unless the selected specification // destinations are reported as out of scope unless the selected specification
// enforces the checkout boundary. Submodule contents remain out of scope. // enforces the checkout boundary. Submodule contents remain out of scope.
// The zero values of all selections preserve the ordinary suite. If // The zero values of the legacy module selections preserve the ordinary suite. If
// Build selects targets, Check builds them after validation in temporary // Build selects targets, Check builds them after validation in temporary
// storage outside the worktree, then rechecks // storage outside the worktree, then rechecks
// branch, HEAD, worktree, index, and local tag state. Success establishes local // branch, HEAD, worktree, index, and local tag state. Success establishes local
@@ -182,6 +190,12 @@ func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
func publicCandidate(checked candidate.Candidate) Candidate { func publicCandidate(checked candidate.Candidate) Candidate {
return Candidate{ return Candidate{
RepositoryDir: checked.RepositoryDir, RepositoryDir: checked.RepositoryDir,
SourceDir: checked.Identity.SourceDir,
SourceSubdir: checked.Identity.SourceSubdir,
GoEnabled: checked.Identity.GoEnabled,
Publication: PublicationMode(checked.Identity.Publication),
VersionFormat: VersionFormat(checked.Identity.VersionFormat),
VersionPrefix: checked.Identity.VersionPrefix,
ModuleDir: checked.ModuleDir, ModuleDir: checked.ModuleDir,
ModulePath: checked.ModulePath, ModulePath: checked.ModulePath,
Tag: checked.Tag, Tag: checked.Tag,
@@ -191,32 +205,38 @@ func publicCandidate(checked candidate.Candidate) Candidate {
} }
func candidateRequest(request ReleaseRequest) candidate.Request { func candidateRequest(request ReleaseRequest) candidate.Request {
fileSize := internalFileSizeSettings(request.Validation.FileSize)
result := candidate.Request{ result := candidate.Request{
RepositoryDir: request.RepositoryDir, RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir, ModuleDir: request.ModuleDir,
Product: request.Product, Source: internalSourceSpec(request.Source),
Version: request.Version, BuildTargets: request.Build != nil && len(request.Build.Targets) != 0,
Validation: validation.Settings{ Product: request.Product,
Race: request.Validation.Go.Race, Version: request.Version,
FullVet: request.Validation.Go.FullVet, Validation: internalValidationSpec(request.Validation),
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
ForbiddenFiles: copyStringSlice(request.Validation.ForbiddenFiles),
GoFormat: request.Validation.GoFormat,
Markdown: internalMarkdownSettings(request.Validation.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
WorkspaceFiles: request.Validation.ModuleDistribution.WorkspaceFiles,
LocalReplacements: request.Validation.ModuleDistribution.LocalReplacements,
},
FileSize: fileSize,
},
AdditionalChecks: candidateChecks(request.AdditionalChecks), AdditionalChecks: candidateChecks(request.AdditionalChecks),
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output), AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
Output: request.Output, Output: request.Output,
} }
for index, target := range request.Validation.Go.CompileTargets { return result
result.Validation.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch} }
func internalValidationSpec(spec ValidationSpec) validation.Settings {
result := validation.Settings{
Race: spec.Go.Race,
FullVet: spec.Go.FullVet,
CompileTargets: make([]validation.Target, len(spec.Go.CompileTargets)),
SharedFiles: copyStringSlice(spec.SharedFiles),
ForbiddenFiles: copyStringSlice(spec.ForbiddenFiles),
GoFormat: spec.GoFormat,
Markdown: internalMarkdownSettings(spec.Markdown),
ModuleDistribution: validation.ModuleDistributionSettings{
WorkspaceFiles: spec.ModuleDistribution.WorkspaceFiles,
LocalReplacements: spec.ModuleDistribution.LocalReplacements,
},
FileSize: internalFileSizeSettings(spec.FileSize),
}
for index, target := range spec.Go.CompileTargets {
result.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch}
} }
return result return result
} }

View File

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

View File

@@ -49,7 +49,7 @@ func TestCIDeliveryRejectsModuleTagMismatchBeforePreparation(t *testing.T) {
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH")) t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
var stdout, stderr bytes.Buffer 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) 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"`) { if status != 1 || !strings.Contains(stderr.String(), `expected delivery tag "v1.2.3"`) || !strings.Contains(stderr.String(), `selected source tag "child/v1.2.3"`) {
t.Fatalf("status=%d stderr=%q, want module tag mismatch", status, stderr.String()) t.Fatalf("status=%d stderr=%q, want module tag mismatch", status, stderr.String())
} }
if _, err := os.Stat(marker); !os.IsNotExist(err) { if _, err := os.Stat(marker); !os.IsNotExist(err) {

View File

@@ -23,7 +23,7 @@ func TestInvalidDeliveryDestinationStopsBeforePreparation(t *testing.T) {
http.Error(w, "unexpected request", http.StatusInternalServerError) http.Error(w, "unexpected request", http.StatusInternalServerError)
})) }))
defer server.Close() defer server.Close()
destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"} destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}}
switch setting { switch setting {
case "URL": case "URL":
destination.BaseURL = "ssh://forge.example" destination.BaseURL = "ssh://forge.example"

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,21 +2,24 @@ package cli
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
"go.maximumdirect.net/releasekit/internal/artifact" "go.maximumdirect.net/releasekit/internal/artifact"
"go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract" "go.maximumdirect.net/releasekit/internal/versioncontract"
"golang.org/x/mod/module"
) )
const BuildReceiptName = ".releasekit-build.json" const BuildReceiptName = ".releasekit-build.json"
const BuildReceiptSchemaVersion = 1 const BuildReceiptSchemaVersion = 2
type ReceiptTarget struct { type ReceiptTarget struct {
OS string `json:"os"` OS string `json:"os"`
@@ -34,6 +37,14 @@ type ReceiptArtifact struct {
type BuildReceipt struct { type BuildReceipt struct {
SchemaVersion int `json:"schema_version"` SchemaVersion int `json:"schema_version"`
RepositoryDir string `json:"repository_dir"` RepositoryDir string `json:"repository_dir"`
SourceDir string `json:"source_dir"`
SourceSubdir string `json:"source_subdir"`
GoEnabled bool `json:"go_enabled"`
Publication string `json:"publication_mode"`
VersionFormat string `json:"version_format"`
VersionPrefix string `json:"version_prefix"`
IdentityKind string `json:"identity_kind"`
NotePath string `json:"note_path,omitempty"`
ModuleDir string `json:"module_dir"` ModuleDir string `json:"module_dir"`
ModulePath string `json:"module_path"` ModulePath string `json:"module_path"`
Tag string `json:"tag"` Tag string `json:"tag"`
@@ -113,7 +124,6 @@ func LoadBuildReceipt(path string) (BuildReceipt, error) {
defer file.Close() defer file.Close()
var receipt BuildReceipt var receipt BuildReceipt
decoder := json.NewDecoder(file) decoder := json.NewDecoder(file)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&receipt); err != nil { if err := decoder.Decode(&receipt); err != nil {
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err) return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
} }
@@ -169,11 +179,8 @@ func validateBuildReceipt(receipt BuildReceipt) error {
if receipt.SchemaVersion != BuildReceiptSchemaVersion { if receipt.SchemaVersion != BuildReceiptSchemaVersion {
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion) return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
} }
if !versioncontract.ValidStableVersion(receipt.Version) { if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.SourceDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return fmt.Errorf("build receipt has invalid version %q", receipt.Version) return errors.New("build receipt repository, source, module, and output directories must be absolute")
}
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
return errors.New("build receipt repository, module, and output directories must be absolute")
} }
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" { if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
return errors.New("build receipt is missing module path or full tag") return errors.New("build receipt is missing module path or full tag")
@@ -215,16 +222,65 @@ func validateBuildReceipt(receipt BuildReceipt) error {
func validateRecordedIdentity(receipt BuildReceipt) error { func validateRecordedIdentity(receipt BuildReceipt) error {
repositoryDir := filepath.Clean(receipt.RepositoryDir) repositoryDir := filepath.Clean(receipt.RepositoryDir)
moduleDir := filepath.Clean(receipt.ModuleDir) moduleDir := filepath.Clean(receipt.ModuleDir)
relative, err := filepath.Rel(repositoryDir, moduleDir) sourceDir := filepath.Clean(receipt.SourceDir)
relative, err := filepath.Rel(repositoryDir, sourceDir)
if err != nil { if err != nil {
return fmt.Errorf("relate module directory to repository: %w", err) return fmt.Errorf("relate module directory to repository: %w", err)
} }
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
return errors.New("module directory is outside repository") return errors.New("source directory is outside repository")
} }
if relative == "" { if relative == "" {
relative = "." relative = "."
} }
if filepath.ToSlash(relative) != receipt.SourceSubdir || sourceDir != moduleDir || !receipt.GoEnabled {
return errors.New("source and module selections do not match")
}
if err := module.CheckImportPath(receipt.ModulePath); err != nil {
return fmt.Errorf("invalid module path: %w", err)
}
if _, _, ok := module.SplitPathVersion(receipt.ModulePath); !ok {
return errors.New("invalid module path major")
}
if receipt.Publication != "source" && receipt.Publication != "go-module" {
return errors.New("invalid publication mode")
}
if receipt.VersionFormat == "" {
return errors.New("missing version format")
}
_, err = releaseidentity.NormalizeSource("", &releaseidentity.SourceSpec{
Dir: receipt.SourceSubdir, GoEnabled: receipt.GoEnabled, Publication: receipt.Publication,
VersionFormat: receipt.VersionFormat, VersionPrefix: &receipt.VersionPrefix,
})
if err != nil {
return fmt.Errorf("invalid source selection: %w", err)
}
if receipt.Publication == "go-module" && (receipt.VersionFormat != "semver" || receipt.VersionPrefix != "v") {
return errors.New("Go module publication requires prefixed semantic versions")
}
if receipt.IdentityKind == "diagnostic" {
attempt := strings.TrimPrefix(receipt.Version, "releasekit-test-")
if !strings.HasPrefix(receipt.Version, "releasekit-test-") || len(attempt) != 32 || strings.ToLower(attempt) != attempt {
return errors.New("invalid diagnostic version")
}
selector := strings.TrimSuffix(strings.TrimPrefix(receipt.Tag, "releasekit-test/"), "/"+attempt)
if _, err := hex.DecodeString(attempt); err != nil || !strings.HasPrefix(receipt.Tag, "releasekit-test/") || !strings.HasSuffix(receipt.Tag, "/"+attempt) || selector == "" || strings.Contains(selector, "/") {
return errors.New("invalid diagnostic tag")
}
return nil
}
if receipt.IdentityKind != "production" || !versioncontract.ValidIdentifier(receipt.Version, receipt.VersionFormat, receipt.VersionPrefix) {
return errors.New("invalid production identity or version")
}
if receipt.NotePath != path.Join(receipt.SourceSubdir, "docs", "releases", receipt.Version+".md") {
return errors.New("release note path does not match source and version")
}
if receipt.Publication == "source" {
if receipt.Tag != receipt.Version && !strings.HasSuffix(receipt.Tag, "/"+receipt.Version) {
return errors.New("full tag does not match source version")
}
return nil
}
identity, err := releaseidentity.Derive(releaseidentity.Selection{ identity, err := releaseidentity.Derive(releaseidentity.Selection{
RepositoryDir: repositoryDir, RepositoryDir: repositoryDir,
ModuleDir: moduleDir, ModuleDir: moduleDir,

View File

@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@@ -19,6 +20,7 @@ func TestWriteBuildReceiptReportsTemporaryCleanup(t *testing.T) {
name := "app-v1.2.3-linux-amd64" name := "app-v1.2.3-linux-amd64"
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repository, ModuleDir: repository, SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repository, ModuleDir: repository,
SourceDir: repository, SourceSubdir: ".", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
ModulePath: "example.com/receipt", Tag: "v1.2.3", CandidateCommit: strings.Repeat("a", 40), ModulePath: "example.com/receipt", Tag: "v1.2.3", CandidateCommit: strings.Repeat("a", 40),
Version: "v1.2.3", MainPackage: ".", BinaryName: "app", Compiler: "go fixture", Version: "v1.2.3", MainPackage: ".", BinaryName: "app", Compiler: "go fixture",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
@@ -96,6 +98,14 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
RepositoryDir: repositoryDir, RepositoryDir: repositoryDir,
SourceDir: moduleDir,
SourceSubdir: test.moduleDir,
GoEnabled: true,
Publication: "go-module",
VersionFormat: "semver",
VersionPrefix: "v",
IdentityKind: "production",
NotePath: path.Join(test.moduleDir, "docs/releases/v1.2.3.md"),
ModuleDir: moduleDir, ModuleDir: moduleDir,
ModulePath: test.modulePath, ModulePath: test.modulePath,
Tag: test.tag, Tag: test.tag,
@@ -114,6 +124,22 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
fields["future_field"] = true
data, err = json.Marshal(fields)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
loaded, err := LoadBuildReceipt(path) loaded, err := LoadBuildReceipt(path)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -159,15 +185,15 @@ func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
} }
} }
func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) { func TestLoadBuildReceiptRejectsOldSchemasAndMultipleValues(t *testing.T) {
for _, test := range []struct { for _, test := range []struct {
name string name string
body string body string
want string want string
}{ }{
{name: "unknown field", body: `{"schema_version":1,"unexpected":true}`, want: "unknown field"}, {name: "old receipt", body: `{"schema_version":1,"unexpected":true}`, want: "regenerate it with the updated build command"},
{name: "unversioned receipt", body: `{}`, want: "regenerate it with the updated build command"}, {name: "unversioned receipt", body: `{}`, want: "regenerate it with the updated build command"},
{name: "unknown schema", body: `{"schema_version":2}`, want: "regenerate it with the updated build command"}, {name: "unknown schema", body: `{"schema_version":3}`, want: "regenerate it with the updated build command"},
{name: "multiple values", body: `{} {}`, want: "multiple JSON values"}, {name: "multiple values", body: `{} {}`, want: "multiple JSON values"},
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
@@ -191,6 +217,7 @@ func TestWriteBuildReceiptRejectsInconsistentRecordedIdentity(t *testing.T) {
outputDir := t.TempDir() outputDir := t.TempDir()
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
SourceDir: moduleDir, SourceSubdir: "integrations/ckconfig", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "integrations/ckconfig/docs/releases/v1.2.3.md",
RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3", RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper", CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture", OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
@@ -215,6 +242,7 @@ func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
digest := sha256.Sum256(contents) digest := sha256.Sum256(contents)
receipt := BuildReceipt{ receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, SchemaVersion: BuildReceiptSchemaVersion,
SourceDir: repositoryDir, SourceSubdir: ".", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3", RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3",
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper", CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture", OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
@@ -244,3 +272,26 @@ func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err) t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err)
} }
} }
func TestDiagnosticBuildReceiptRoundTrip(t *testing.T) {
repo, output := t.TempDir(), t.TempDir()
attempt := strings.Repeat("a", 32)
version := "releasekit-test-" + attempt
name := "helper-" + version + "-linux-amd64"
receipt := BuildReceipt{
SchemaVersion: BuildReceiptSchemaVersion, RepositoryDir: repo, SourceDir: repo, SourceSubdir: ".",
GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "diagnostic",
ModuleDir: repo, ModulePath: "example.com/receipt", Tag: "releasekit-test/root/" + attempt,
CandidateCommit: strings.Repeat("b", 40), Version: version, MainPackage: ".", BinaryName: "helper", Compiler: "go version fixture",
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
Artifacts: []ReceiptArtifact{{Path: filepath.Join(output, name), Filename: name, Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64)}},
}
path, err := WriteBuildReceipt(output, receipt)
if err != nil {
t.Fatal(err)
}
loaded, err := LoadBuildReceipt(path)
if err != nil || loaded.IdentityKind != "diagnostic" || loaded.Version != version || loaded.Tag != receipt.Tag {
t.Fatalf("diagnostic receipt = %+v, error = %v", loaded, err)
}
}

View File

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

View File

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

View File

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

View File

@@ -19,6 +19,7 @@ import (
"go.maximumdirect.net/releasekit/internal/git" "go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/gotool" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/versioncontract"
) )
func main() { func main() {
@@ -37,6 +38,12 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction { if invocation.Command == cli.ReconcileAction || invocation.Command == cli.PublicationAttemptsAction {
return runRecovery(ctx, invocation, stdout, stderr) return runRecovery(ctx, invocation, stdout, stderr)
} }
if invocation.Command == cli.TestAction || invocation.Command == cli.TestResumeAction || invocation.Command == cli.TestCleanupAction {
return runRehearsal(ctx, invocation, stdout, stderr)
}
if invocation.Command == cli.ValidateAction {
return runValidate(ctx, invocation, stdout)
}
if invocation.Command != cli.VersionCommand { if invocation.Command != cli.VersionCommand {
invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository) invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository)
if err != nil { if err != nil {
@@ -69,8 +76,8 @@ func runCheckOrPublish(ctx context.Context, invocation cli.Invocation, stdout, s
} }
request := candidateRequest(invocation, settings, stderr) request := candidateRequest(invocation, settings, stderr)
if invocation.Command == cli.PublishAction { if invocation.Command == cli.PublishAction {
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil { if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err) fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2 return 2
} }
request.ExpectedPushURL = settings.ExpectedPushURL request.ExpectedPushURL = settings.ExpectedPushURL
@@ -168,6 +175,10 @@ func publicationOffersRecovery(phase releasekit.PublicationPhase) bool {
} }
func publicationRecoveryCommand(recordPath string) (string, error) { func publicationRecoveryCommand(recordPath string) (string, error) {
return executableRecoveryCommand(recordPath, "reconcile")
}
func executableRecoveryCommand(recordPath, command string) (string, error) {
executable, err := os.Executable() executable, err := os.Executable()
if err != nil { if err != nil {
return "", fmt.Errorf("find current executable: %w", err) return "", fmt.Errorf("find current executable: %w", err)
@@ -184,7 +195,7 @@ func publicationRecoveryCommand(recordPath string) (string, error) {
if err != nil { if err != nil {
return "", fmt.Errorf("resolve publication record path: %w", err) return "", fmt.Errorf("resolve publication record path: %w", err)
} }
return shellQuote(executable) + " reconcile --record " + shellQuote(recordPath), nil return shellQuote(executable) + " " + command + " --record " + shellQuote(recordPath), nil
} }
func shellQuote(argument string) string { func shellQuote(argument string) string {
@@ -204,6 +215,7 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.
result, err := releasekit.Build(ctx, releasekit.BuildRequest{ result, err := releasekit.Build(ctx, releasekit.BuildRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Version: invocation.Version, Version: invocation.Version,
Spec: *configuredBuildSpec(settings.Build), Spec: *configuredBuildSpec(settings.Build),
OutputDir: invocation.OutputDir, OutputDir: invocation.OutputDir,
@@ -252,10 +264,22 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io.
return 0 return 0
} }
func sourceSpec(settings cli.Settings) *releasekit.SourceSpec {
source := settings.SourceSpec()
if source == nil {
return nil
}
return &releasekit.SourceSpec{
Dir: source.Dir, GoEnabled: source.GoEnabled, Publication: releasekit.PublicationMode(source.Publication),
VersionFormat: releasekit.VersionFormat(source.VersionFormat), VersionPrefix: source.VersionPrefix, TagPrefix: source.TagPrefix,
}
}
func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest { func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
request := releasekit.ReleaseRequest{ request := releasekit.ReleaseRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
Remote: settings.Remote, Remote: settings.Remote,
@@ -266,10 +290,11 @@ func candidateRequest(invocation cli.Invocation, settings cli.Settings, output i
if len(settings.Checks) != 0 { if len(settings.Checks) != 0 {
checks := settings.Checks checks := settings.Checks
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error { request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
return cli.RunChecks(ctx, candidate.ModuleDir, checks, map[string]string{ return cli.RunChecks(ctx, candidate.SourceDir, checks, map[string]string{
"RELEASEKIT_VERSION": candidate.Version, "RELEASEKIT_VERSION": candidate.Version,
"RELEASEKIT_CANDIDATE": candidate.Commit, "RELEASEKIT_CANDIDATE": candidate.Commit,
"RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir, "RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir,
"RELEASEKIT_SOURCE_DIR": candidate.SourceDir,
"RELEASEKIT_MODULE_DIR": candidate.ModuleDir, "RELEASEKIT_MODULE_DIR": candidate.ModuleDir,
"RELEASEKIT_MODULE_PATH": candidate.ModulePath, "RELEASEKIT_MODULE_PATH": candidate.ModulePath,
"RELEASEKIT_TAG": candidate.Tag, "RELEASEKIT_TAG": candidate.Tag,
@@ -324,28 +349,40 @@ func candidateFailureText(err error) string {
return err.Error() return err.Error()
} }
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error { func checkExpectedSelection(ctx context.Context, repositoryDir, expectedModule, expectedSource string, settings cli.Settings) error {
if expectedModule == "" { if expectedModule == "" && expectedSource == "" {
return nil return nil
} }
commit, err := git.CaptureHead(ctx, repositoryDir) commit, err := git.CaptureHead(ctx, repositoryDir)
if err != nil { if err != nil {
return err return err
} }
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit) selected, err := releaseidentity.ResolveCommittedSource(ctx, repositoryDir, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil { if err != nil {
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err) return fmt.Errorf("normalize profile source: %w", err)
} }
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit) for _, expectation := range []struct{ kind, dir string }{{"module", expectedModule}, {"source", expectedSource}} {
if err != nil { if expectation.dir == "" {
return fmt.Errorf("normalize profile module %q: %w", profileModule, err) continue
} }
if expected.ModuleSubdir != selected.ModuleSubdir { expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectation.dir, commit)
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir) if err != nil {
return fmt.Errorf("normalize expected %s %q: %w", expectation.kind, expectation.dir, err)
}
if expected.ModuleSubdir != selected.ModuleSubdir {
return fmt.Errorf("expected %s %q resolves to %q, but the profile selects %q", expectation.kind, expectation.dir, expected.ModuleSubdir, selected.ModuleSubdir)
}
} }
return nil return nil
} }
func selectionErrorLabel(expectedSource string) string {
if expectedSource != "" {
return "profile source selection"
}
return "profile module selection"
}
func selectedModuleLabel(moduleDir string) string { func selectedModuleLabel(moduleDir string) string {
if moduleDir == "" { if moduleDir == "" {
return "." return "."
@@ -385,25 +422,36 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
return 1 return 1
} }
if releaseidentity.IsDiagnosticTag(invocation.ExpectedTag) {
return runDiagnosticDelivery(ctx, invocation, stdout, stderr)
}
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath) settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
if err != nil { if err != nil {
fmt.Fprintf(stderr, "load profile: %v\n", err) fmt.Fprintf(stderr, "load profile: %v\n", err)
return 2 return 2
} }
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil { if err := checkExpectedSelection(ctx, invocation.Repository, invocation.ExpectedModule, invocation.ExpectedSource, settings); err != nil {
fmt.Fprintf(stderr, "profile module selection: %v\n", err) fmt.Fprintf(stderr, "%s: %v\n", selectionErrorLabel(invocation.ExpectedSource), err)
return 2 return 2
} }
identity, err := releaseidentity.FromCommitted(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit) identity, err := releaseidentity.FromCommittedSource(ctx, invocation.Repository, settings.ModuleDir, invocation.Version, invocation.Commit, settings.SourceSpec())
if err != nil { if err != nil {
fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err) fmt.Fprintf(stderr, "resolve CI release identity: %v\n", err)
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return 2
}
return 1 return 1
} }
if invocation.ExpectedTag != identity.Tag { if invocation.ExpectedTag != identity.Tag {
fmt.Fprintf(stderr, "expected delivery tag %q does not match selected module tag %q\n", invocation.ExpectedTag, identity.Tag) fmt.Fprintf(stderr, "expected delivery tag %q does not match selected source tag %q\n", invocation.ExpectedTag, identity.Tag)
return 1 return 1
} }
destination, status := deliveryDestination(invocation.Repository, settings, stderr) if !identity.GoEnabled && settings.Build != nil && len(settings.Build.Targets) != 0 {
fmt.Fprintln(stderr, "build targets require Go capability")
return 2
}
destination, status := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr)
if status != 0 { if status != 0 {
return status return status
} }
@@ -414,7 +462,7 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
} }
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{ if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: identity.ModuleSubdir,
}); err != nil { }); err != nil {
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err) fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
return 1 return 1
@@ -426,14 +474,14 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder
// deliverWithSettings adapts prepared CLI state to the public delivery facade. // deliverWithSettings adapts prepared CLI state to the public delivery facade.
// CI entry points can reuse it after preparing the checkout and loading its profile. // CI entry points can reuse it after preparing the checkout and loading its profile.
func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int { func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int {
destination, status := deliveryDestination(invocation.Repository, settings, stderr) destination, status := deliveryDestination(invocation.Repository, settings, cli.LocalCredentials, stderr)
if status != 0 { if status != 0 {
return status return status
} }
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr) return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
} }
func deliveryDestination(repositoryDir string, settings cli.Settings, stderr io.Writer) (releasekit.DeliveryDestination, int) { func deliveryDestination(repositoryDir string, settings cli.Settings, context cli.CredentialContext, stderr io.Writer) (releasekit.DeliveryDestination, int) {
delivery := settings.Delivery delivery := settings.Delivery
if delivery == nil { if delivery == nil {
fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile") fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile")
@@ -452,29 +500,9 @@ func deliveryDestination(repositoryDir string, settings cli.Settings, stderr io.
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings") fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
return releasekit.DeliveryDestination{}, 2 return releasekit.DeliveryDestination{}, 2
} }
tokenEnv := delivery.TokenEnv token, _, err := cli.ResolveDeliveryCredential(repositoryDir, delivery.Credentials, context)
if strings.TrimSpace(tokenEnv) == "" { if err != nil {
tokenEnv = "RELEASEKIT_GITEA_TOKEN" fmt.Fprintln(stderr, err)
}
token, ok := os.LookupEnv(tokenEnv)
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
}
}
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{}, 2
} }
return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0 return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
@@ -498,7 +526,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err) fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
return 1 return 1
} }
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit) selection, err := releaseidentity.ResolveCommittedSource(ctx, invocation.Repository, settings.ModuleDir, commit, settings.SourceSpec())
if err != nil { if err != nil {
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err) fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
return 1 return 1
@@ -520,6 +548,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{ result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
RepositoryDir: invocation.Repository, RepositoryDir: invocation.Repository,
ModuleDir: settings.ModuleDir, ModuleDir: settings.ModuleDir,
Source: sourceSpec(settings),
Product: settings.Product, Product: settings.Product,
Version: invocation.Version, Version: invocation.Version,
ExpectedTag: invocation.ExpectedTag, ExpectedTag: invocation.ExpectedTag,
@@ -611,6 +640,9 @@ func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult { func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
result := &releasekit.BuildResult{ result := &releasekit.BuildResult{
RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag, RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag,
SourceDir: receipt.SourceDir, SourceSubdir: receipt.SourceSubdir, GoEnabled: receipt.GoEnabled,
Publication: releasekit.PublicationMode(receipt.Publication), VersionFormat: releasekit.VersionFormat(receipt.VersionFormat),
VersionPrefix: receipt.VersionPrefix, IdentityKind: receipt.IdentityKind, NotePath: receipt.NotePath,
CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified, CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified,
Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName, Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName,
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler, OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
@@ -647,6 +679,14 @@ func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
receipt := cli.BuildReceipt{ receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion, SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: result.RepositoryDir, RepositoryDir: result.RepositoryDir,
SourceDir: result.SourceDir,
SourceSubdir: result.SourceSubdir,
GoEnabled: result.GoEnabled,
Publication: string(result.Publication),
VersionFormat: string(result.VersionFormat),
VersionPrefix: result.VersionPrefix,
IdentityKind: result.IdentityKind,
NotePath: result.NotePath,
ModuleDir: result.ModuleDir, ModuleDir: result.ModuleDir,
ModulePath: result.ModulePath, ModulePath: result.ModulePath,
Tag: result.Tag, Tag: result.Tag,

View File

@@ -1212,13 +1212,13 @@ func TestDeliverRequiresCredentialBeforeRemoteRequests(t *testing.T) {
state := &deliveryServerState{} state := &deliveryServerState{}
server := newDeliveryServer(t, state) server := newDeliveryServer(t, state)
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}) writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{}}}})
state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "") t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "ambient-token")
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr) status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr)
if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "RELEASEKIT_TEST_DELIVERY_TOKEN") { if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "delivery.credentials.local.token_file") {
t.Fatalf("missing credential status=%d requests=%d stdout=%q stderr=%q", status, state.snapshot().apiRequests, stdout.String(), stderr.String()) t.Fatalf("missing credential status=%d requests=%d stdout=%q stderr=%q", status, state.snapshot().apiRequests, stdout.String(), stderr.String())
} }
} }
@@ -1235,7 +1235,7 @@ func TestDeliverRejectsMissingBlankAndUnsupportedForgeBeforeTokenOrBuild(t *test
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{ Delivery: &cli.DeliverySettings{
Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example", Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example",
TokenFile: filepath.Join(repository, "missing-token"), Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}},
}, },
}) })
state.update(func(data *deliveryServerData) { data.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) state.update(func(data *deliveryServerData) { data.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") })
@@ -1273,7 +1273,7 @@ func TestCIDeliverRejectsUnsupportedForgeBeforeTokenOrDependencyPreparation(t *t
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{ Delivery: &cli.DeliverySettings{
Forge: "unsupported", BaseURL: server.URL, Owner: "owner", Repository: "example", Forge: "unsupported", BaseURL: server.URL, Owner: "owner", Repository: "example",
TokenFile: filepath.Join(repository, "missing-token"), Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}},
}, },
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
@@ -1325,7 +1325,7 @@ func TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne(t *testing.T)
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Delivery: &cli.DeliverySettings{ Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
}, },
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
@@ -1367,7 +1367,7 @@ func TestDeliverUnavailablePreflightStopsBeforeManagedBuild(t *testing.T) {
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{ Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
}, },
}) })
cliGitRun(t, repository, "tag", "v1.2.3") cliGitRun(t, repository, "tag", "v1.2.3")
@@ -1419,7 +1419,7 @@ func TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation(t *testin
Product: "Example Product", Product: "Example Product",
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
Delivery: &cli.DeliverySettings{ Delivery: &cli.DeliverySettings{
Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}},
}, },
}) })
expectedCommit := pushTaggedCLIRepository(t, repository) expectedCommit := pushTaggedCLIRepository(t, repository)
@@ -1542,6 +1542,8 @@ func writeDeliveryReceipt(t *testing.T, repository string, settings cli.BuildSet
receipt := cli.BuildReceipt{ receipt := cli.BuildReceipt{
SchemaVersion: cli.BuildReceiptSchemaVersion, SchemaVersion: cli.BuildReceiptSchemaVersion,
RepositoryDir: resolvedRepository, ModuleDir: resolvedRepository, ModulePath: "example.com/cli-candidate", Tag: "v1.2.3", RepositoryDir: resolvedRepository, ModuleDir: resolvedRepository, ModulePath: "example.com/cli-candidate", Tag: "v1.2.3",
SourceDir: resolvedRepository, SourceSubdir: ".", GoEnabled: true, Publication: "go-module",
VersionFormat: "semver", VersionPrefix: "v", IdentityKind: "production", NotePath: "docs/releases/v1.2.3.md",
CandidateCommit: cliGitOutput(t, repository, "rev-parse", "HEAD"), CandidateCommit: cliGitOutput(t, repository, "rev-parse", "HEAD"),
SourceVerified: true, SourceVerified: true,
Version: "v1.2.3", MainPackage: settings.MainPackage, BinaryName: settings.BinaryName, Version: "v1.2.3", MainPackage: settings.MainPackage, BinaryName: settings.BinaryName,
@@ -1740,7 +1742,11 @@ func writeDeliveryRelease(w http.ResponseWriter, baseURL string, data *deliveryS
if product == "" { if product == "" {
product = "Example Product" product = "Example Product"
} }
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " v1.2.3", "body": data.noteBody, "draft": false, "prerelease": false}) version := data.tag
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " " + version, "body": data.noteBody, "draft": false, "prerelease": false})
} }
func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings) { func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings) {
@@ -1749,6 +1755,22 @@ func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings
func writeDeliveryProfileAt(t *testing.T, repository, name string, settings cli.Settings) { func writeDeliveryProfileAt(t *testing.T, repository, name string, settings cli.Settings) {
t.Helper() t.Helper()
if settings.Delivery != nil {
if settings.Delivery.Credentials == nil {
settings.Delivery.Credentials = &cli.DeliveryCredentials{}
}
credentials := settings.Delivery.Credentials
if credentials.Local == nil {
path := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(path, []byte("fixture-token"), 0o600); err != nil {
t.Fatal(err)
}
credentials.Local = &cli.LocalCredential{TokenFile: path}
}
if credentials.CI == nil {
credentials.CI = &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}
}
}
contents, err := json.Marshal(settings) contents, err := json.Marshal(settings)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -1799,7 +1821,7 @@ func newCLIBuildRepository(t *testing.T, mainSource string) string {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
module := fmt.Sprintf("module example.com/cli-candidate\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root)) module := fmt.Sprintf("module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => %s\n", filepath.ToSlash(root))
write := func(name, contents string) { write := func(name, contents string) {
t.Helper() t.Helper()
path := filepath.Join(repository, filepath.FromSlash(name)) path := filepath.Join(repository, filepath.FromSlash(name))

View File

@@ -27,6 +27,9 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"}, {mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
{mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"}, {mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"},
{mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"}, {mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
{mode: "tag", value: "configuration/2026-12-05", want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
{mode: "tag", value: "releasekit-test/ckconfig/" + strings.Repeat("a", 32), want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
{mode: "tag", value: "releasekit-test/config/" + strings.Repeat("b", 32), want: "config\tconfiguration/20*\t-\treleasekit-config.json"},
} { } {
t.Run(test.mode+" "+test.value, func(t *testing.T) { t.Run(test.mode+" "+test.value, func(t *testing.T) {
got := runModuleSelector(t, helper, test.mode, test.value, "") got := runModuleSelector(t, helper, test.mode, test.value, "")
@@ -46,10 +49,22 @@ func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") { if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
t.Fatalf("ambiguous event error = %q", output) t.Fatalf("ambiguous event error = %q", output)
} }
if output := runModuleSelectorError(t, helper, "tag", "releasekit-test/ckconfig/invalid", ""); !strings.Contains(output, "no module map row") {
t.Fatalf("malformed diagnostic error=%q", output)
}
if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil { if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
reservedMap := filepath.Join(t.TempDir(), "production.tsv")
if err := os.WriteFile(reservedMap, []byte("product\treleasekit-test/product/*\t-\treleasekit.json\n"), 0600); err != nil {
t.Fatal(err)
}
for _, tag := range []string{"releasekit-test/product/v1.2.3", "releasekit-test/product/2026-12-01"} {
if got := runModuleSelector(t, helper, "tag", tag, reservedMap); !strings.HasPrefix(got, "product\t") {
t.Fatalf("production tag=%s mapping=%q", tag, got)
}
}
got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath) got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath)
want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json" want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json"
if strings.TrimSpace(got) != want { if strings.TrimSpace(got) != want {

View File

@@ -19,6 +19,8 @@ import (
"testing" "testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
) )
func TestMultiModuleWoodpeckerDelivery(t *testing.T) { func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
@@ -33,7 +35,7 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
command := strings.ReplaceAll(block, "$${", "${") command := strings.ReplaceAll(block, "$${", "${")
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*"} { for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*", "refs/tags/configuration/20*", "refs/tags/releasekit-test/*/*"} {
if !strings.Contains(string(contents), eventTag) { if !strings.Contains(string(contents), eventTag) {
t.Errorf("workflow tag filters omit %q", eventTag) t.Errorf("workflow tag filters omit %q", eventTag)
} }
@@ -41,6 +43,83 @@ func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
toolBinary := buildWorkflowCLI(t, root) toolBinary := buildWorkflowCLI(t, root)
proxy := writeWorkflowToolProxy(t) proxy := writeWorkflowToolProxy(t)
t.Run("diagnostic tag selects the committed module and profile", func(t *testing.T) {
attemptID := strings.Repeat("a", 32)
tag := "releasekit-test/ckconfig/" + attemptID
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeMappedProfile(t, repository, "releasekit-ckconfig.json", cli.Settings{Product: "Example Consumer Integration", ModuleDir: "integrations/ckconfig", Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "ckconfig"}})
cliGitRun(t, repository, "add", "--all")
cliGitRun(t, repository, "commit", "-m", "capture diagnostic selection")
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, "HEAD", "releasekit-ckconfig.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "ckconfig", captured.Commit, attemptID)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attemptID, "ckconfig", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
t.Fatal(err)
}
remote := filepath.Join(filepath.Dir(repository), "origin.git")
cliGitRun(t, repository, "init", "--bare", remote)
cliGitRun(t, repository, "remote", "add", "origin", remote)
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+tag)
delivery.update(func(data *mappedDeliveryData) { data.commit = captured.Commit })
env := multiModuleWorkflowEnvironment(t, repository, captured.Commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
t.Fatalf("result=%+v error=%v output=%s", result, err, output)
}
})
t.Run("source-only row installs the pinned tool", func(t *testing.T) {
const tag = "configuration/2026-12-05"
delivery := newMappedDeliveryFixture(t, tag)
repository := newWorkflowRepository(t, example)
writeRepositoryFile(t, repository, ".releasekit-version", "v0.2.197\n")
writeMappedProfile(t, repository, "releasekit-config.json", cli.Settings{Product: "Example Configuration", Source: &cli.SourceSettings{Dir: "configuration"}, Version: &cli.VersionSettings{Format: "date"}, Delivery: workflowDeliverySettings(delivery.snapshot().URL), Rehearsal: &cli.RehearsalSettings{Selector: "config"}})
commit := tagAndPushWorkflowRepository(t, repository, tag)
delivery.update(func(data *mappedDeliveryData) { data.commit = commit })
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
output := runWoodpeckerBlock(t, command, repository, env)
if !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") || delivery.snapshot().creates != 1 {
t.Fatalf("output=%s delivery=%+v", output, delivery.snapshot())
}
captured, err := cli.CaptureCommittedProfile(t.Context(), repository, commit, "releasekit-config.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repository, captured.Settings.ModuleDir, commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
attemptID := strings.Repeat("b", 32)
identity, err := releaseidentity.DiagnosticFromAttempt(t.Context(), source, "config", commit, attemptID)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attemptID, "config", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repository, manifest); err != nil {
t.Fatal(err)
}
cliGitRun(t, repository, "push", "origin", "refs/tags/"+identity.Tag)
delivery.update(func(data *mappedDeliveryData) { data.tag = identity.Tag; data.page = false; data.creates = 0 })
env["CI_COMMIT_TAG"] = identity.Tag
output = runWoodpeckerBlock(t, command, repository, env)
result, err := rehearsal.ReadResult(strings.NewReader(output), manifest)
if err != nil || result.Verification != "complete" || result.PageID != 10 || delivery.snapshot().creates != 1 {
t.Fatalf("diagnostic result=%+v error=%v output=%s", result, err, output)
}
})
t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) { t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) {
const tag = "integrations/ckconfig/v1.2.3" const tag = "integrations/ckconfig/v1.2.3"
delivery := newMappedDeliveryFixture(t, tag) delivery := newMappedDeliveryFixture(t, tag)
@@ -220,6 +299,7 @@ func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
state.mu.Lock() state.mu.Lock()
defer state.mu.Unlock() defer state.mu.Unlock()
data.requests++ data.requests++
tag := data.tag
if r.Header.Get("Authorization") != "token fixture-token" { if r.Header.Get("Authorization") != "token fixture-token" {
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization")) t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
} }
@@ -388,7 +468,7 @@ func workflowModuleFile(module, version string) string {
} }
func workflowDeliverySettings(baseURL string) *cli.DeliverySettings { func workflowDeliverySettings(baseURL string) *cli.DeliverySettings {
return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"} return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}}
} }
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) { func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {

View File

@@ -22,6 +22,44 @@ import (
"go.maximumdirect.net/releasekit/internal/publish" "go.maximumdirect.net/releasekit/internal/publish"
) )
func TestSourceOnlyPublicationRecoveryAfterLauncherExit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("fixture executes POSIX recovery commands")
}
repo, remote := newSimplePublishRepository(t, false)
cliGitRun(t, repo, "rm", "go.mod")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","source":{},"version":{"format":"date"}}`)
writeRepositoryFile(t, repo, "docs/releases/2026-12-01.md", "# Example Product 2026-12-01\n\nRelease.\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "Configure source only publication")
cliGitRun(t, repo, "push", "origin", "main")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
executable := filepath.Join(t.TempDir(), "releasekit")
build := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", executable, "./cmd/releasekit")
build.Dir = repositoryRoot(t)
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build CLI: %v: %s", err, output)
}
launcher := exec.Command(executable, "publish", "--repo", repo, "2026-12-01")
output, err := launcher.CombinedOutput()
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 {
t.Fatalf("publication: %v: %s", err, output)
}
command := outputLineValue(string(output), "recovery command: ")
if command == "" || !strings.Contains(command, shellQuote(executable)) {
t.Fatalf("missing installed tool handoff: %s", output)
}
recovery := exec.Command("sh", "-c", command)
recovery.Dir = t.TempDir()
recovered, err := recovery.CombinedOutput()
if !errors.As(err, &exitError) || exitError.ExitCode() != 1 || !strings.Contains(string(recovered), "tag=2026-12-01 state=not_published") {
t.Fatalf("source recovery: %v: %s", err, recovered)
}
}
func TestVendoredAPIOnlyPublicationRecovery(t *testing.T) { func TestVendoredAPIOnlyPublicationRecovery(t *testing.T) {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
t.Skip("fixture executes POSIX recovery commands") t.Skip("fixture executes POSIX recovery commands")
@@ -32,7 +70,7 @@ func TestVendoredAPIOnlyPublicationRecovery(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.26.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => "+strconv.Quote(relative)+"\n") writeRepositoryFile(t, repo, "go.mod", "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire go.maximumdirect.net/releasekit v0.0.0\n\nreplace go.maximumdirect.net/releasekit => "+strconv.Quote(relative)+"\n")
writeRepositoryFile(t, repo, "uses_releasekit.go", "package candidate\nimport _ \"go.maximumdirect.net/releasekit\"\n") writeRepositoryFile(t, repo, "uses_releasekit.go", "package candidate\nimport _ \"go.maximumdirect.net/releasekit\"\n")
sums, err := os.ReadFile(filepath.Join(source, "go.sum")) sums, err := os.ReadFile(filepath.Join(source, "go.sum"))
if err != nil { if err != nil {
@@ -163,7 +201,7 @@ func TestColdGoToolRecoverySurvivesLauncherExit(t *testing.T) {
} }
const toolModule = "go.maximumdirect.net/releasekit" const toolModule = "go.maximumdirect.net/releasekit"
const toolVersion = "v0.0.0" const toolVersion = "v0.0.0"
module := "module example.com/cli-candidate\n\ngo 1.26.0\n\nrequire " + toolModule + " " + toolVersion + "\n" module := "module example.com/cli-candidate\n\ngo 1.27.0\n\nrequire " + toolModule + " " + toolVersion + "\n"
var wildcardSource string var wildcardSource string
if registered { if registered {
module += "\nreplace " + toolModule + " => " + strconv.Quote(selectedSource) + "\n" module += "\nreplace " + toolModule + " => " + strconv.Quote(selectedSource) + "\n"

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

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

View File

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

View File

@@ -22,6 +22,14 @@ type recoveryDiagnostic struct {
type safeEvidence struct { type safeEvidence struct {
RepositoryDir string `json:"repository_dir,omitempty"` RepositoryDir string `json:"repository_dir,omitempty"`
SourceDir string `json:"source_dir,omitempty"`
SourceSubdir string `json:"source_subdir,omitempty"`
GoEnabled bool `json:"go_enabled,omitempty"`
Publication string `json:"publication_mode,omitempty"`
VersionFormat string `json:"version_format,omitempty"`
VersionPrefix string `json:"version_prefix,omitempty"`
IdentityKind string `json:"identity_kind,omitempty"`
NotePath string `json:"note_path,omitempty"`
ModuleDir string `json:"module_dir,omitempty"` ModuleDir string `json:"module_dir,omitempty"`
ModulePath string `json:"module_path,omitempty"` ModulePath string `json:"module_path,omitempty"`
Version string `json:"version,omitempty"` Version string `json:"version,omitempty"`
@@ -61,6 +69,14 @@ type attemptsDocument struct {
func safe(e releasekit.PublicationEvidence) safeEvidence { func safe(e releasekit.PublicationEvidence) safeEvidence {
return safeEvidence{ return safeEvidence{
RepositoryDir: git.DisplayDiagnostic(e.RepositoryDir), RepositoryDir: git.DisplayDiagnostic(e.RepositoryDir),
SourceDir: git.DisplayDiagnostic(e.SourceDir),
SourceSubdir: git.DisplayDiagnostic(e.SourceSubdir),
GoEnabled: e.GoEnabled,
Publication: git.DisplayDiagnostic(e.Publication),
VersionFormat: git.DisplayDiagnostic(e.VersionFormat),
VersionPrefix: git.DisplayDiagnostic(e.VersionPrefix),
IdentityKind: git.DisplayDiagnostic(e.IdentityKind),
NotePath: git.DisplayDiagnostic(e.NotePath),
ModuleDir: git.DisplayDiagnostic(e.ModuleDir), ModuleDir: git.DisplayDiagnostic(e.ModuleDir),
ModulePath: git.DisplayDiagnostic(e.ModulePath), ModulePath: git.DisplayDiagnostic(e.ModulePath),
Version: git.DisplayDiagnostic(e.Version), Version: git.DisplayDiagnostic(e.Version),

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,45 +11,48 @@ import (
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
) )
func TestDeliveryTokenFileSelection(t *testing.T) { func TestDeliveryCredentialSelection(t *testing.T) {
repository := t.TempDir()
path := filepath.Join(repository, "token")
if err := os.WriteFile(path, []byte(" file-secret \n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_TOKEN", " ambient-secret ")
credentials := &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_TOKEN"}}
for _, test := range []struct { for _, test := range []struct {
name, env, contents, file, want string context cli.CredentialContext
status int want string
}{ }{{cli.LocalCredentials, "file-secret"}, {cli.CICredentials, "ambient-secret"}} {
{name: "relative file", contents: "fixture-token\n", file: "token", want: "fixture-token"}, token, source, err := cli.ResolveDeliveryCredential(repository, credentials, test.context)
{name: "absolute file", contents: "fixture-token\n", file: "absolute", want: "fixture-token"}, if err != nil || token != test.want || source.Context != test.context {
{name: "environment overrides missing file", env: "env-token", file: "missing", want: "env-token"}, t.Fatalf("context=%s token matches=%t source=%+v error=%v", test.context, token == test.want, source, err)
{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}, credentials.Local.TokenFile = "missing"
{name: "empty file", file: "token", status: 2}, if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil || strings.Contains(err.Error(), "ambient-secret") {
{name: "unreadable as file", file: ".", status: 2}, t.Fatalf("missing local file error = %v", err)
{name: "no credential", status: 2}, }
} { if token, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err != nil || token != "ambient-secret" {
t.Run(test.name, func(t *testing.T) { t.Fatalf("CI credential with missing local file: token matches=%t error=%v", token == "ambient-secret", err)
repository := t.TempDir() }
if err := os.WriteFile(filepath.Join(repository, "token"), []byte(test.contents), 0o600); err != nil { credentials.Local.TokenFile = path
t.Fatal(err) if err := os.WriteFile(path, []byte(" \t\n"), 0600); err != nil {
} t.Fatal(err)
name := test.file }
if name == "absolute" { if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil {
name = filepath.Join(repository, "token") t.Fatal("accepted blank file")
} }
t.Setenv("RELEASEKIT_TEST_TOKEN", test.env) t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "default-secret")
var stderr bytes.Buffer token, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{CI: &cli.CICredential{}}, cli.CICredentials)
destination, status := deliveryDestination(repository, cli.Settings{Delivery: &cli.DeliverySettings{Forge: "gitea", if err != nil || token != "default-secret" {
BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", t.Fatalf("default CI credential matches=%t error=%v", token == "default-secret", err)
TokenEnv: "RELEASEKIT_TEST_TOKEN", TokenFile: name, }
}}, &stderr) if _, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{}, cli.CICredentials); err == nil {
if status != test.status || destination.Token != test.want { t.Fatal("accepted missing CI declaration")
t.Fatalf("status=%d token matches=%t, want status=%d; diagnostics=%s", status, destination.Token == test.want, test.status, &stderr) }
} t.Setenv("RELEASEKIT_TEST_TOKEN", " ")
for _, secret := range []string{"fixture-token", "env-token"} { if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err == nil {
if strings.Contains(stderr.String(), secret) { t.Fatal("accepted blank CI token")
t.Fatal("diagnostics exposed a token")
}
}
})
} }
} }
@@ -58,7 +61,7 @@ func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) {
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Validation: &cli.ValidationSettings{ForbiddenFiles: []string{"token-file"}}, Validation: &cli.ValidationSettings{ForbiddenFiles: []string{"token-file"}},
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", TokenFile: "missing-token-file"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "missing-token-file"}}},
}) })
writeRepositoryFile(t, repository, "token-file", "fixture-secret\n") writeRepositoryFile(t, repository, "token-file", "fixture-secret\n")
cliGitRun(t, repository, "add", "token-file") cliGitRun(t, repository, "add", "token-file")
@@ -73,7 +76,7 @@ func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) {
} }
} }
func TestDeliverAndCIDeliverReadTokenFileFromRepositoryRoot(t *testing.T) { func TestDeliverAndCIDeliverSelectContextCredentials(t *testing.T) {
for _, command := range []string{"deliver", "ci-deliver"} { for _, command := range []string{"deliver", "ci-deliver"} {
t.Run(command, func(t *testing.T) { t.Run(command, func(t *testing.T) {
repository := newCLIRepository(t) repository := newCLIRepository(t)
@@ -82,15 +85,19 @@ func TestDeliverAndCIDeliverReadTokenFileFromRepositoryRoot(t *testing.T) {
defer server.Close() defer server.Close()
writeDeliveryProfile(t, repository, cli.Settings{ writeDeliveryProfile(t, repository, cli.Settings{
Product: "Example Product", Product: "Example Product",
Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenFile: ".releasekit/token"}, Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: ".releasekit/token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}},
}) })
writeRepositoryFile(t, repository, ".gitignore", ".releasekit/\n") writeRepositoryFile(t, repository, ".gitignore", ".releasekit/\n")
cliGitRun(t, repository, "add", ".gitignore") cliGitRun(t, repository, "add", ".gitignore")
cliGitRun(t, repository, "commit", "-m", "ignore local delivery credentials") cliGitRun(t, repository, "commit", "-m", "ignore local delivery credentials")
commit := pushTaggedCLIRepository(t, repository) commit := pushTaggedCLIRepository(t, repository)
state.update(func(data *deliveryServerData) { data.commit = commit }) state.update(func(data *deliveryServerData) { data.commit = commit })
writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n") if command == "deliver" {
t.Setenv("RELEASEKIT_GITEA_TOKEN", "") writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n")
} else if err := os.MkdirAll(filepath.Join(repository, ".releasekit"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
args := []string{command, "--repo", filepath.Join(repository, ".releasekit")} args := []string{command, "--repo", filepath.Join(repository, ".releasekit")}
if command == "ci-deliver" { if command == "ci-deliver" {

View File

@@ -181,6 +181,31 @@ func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
}) })
} }
func TestSingleProductWorkflowClassifiesCompleteDiagnosticTags(t *testing.T) {
for _, file := range []string{"examples/woodpecker/tag-delivery.yml", "examples/woodpecker/releasekit-source-delivery.yml", "examples/source-only/.woodpecker/delivery.yml"} {
t.Run(file, func(t *testing.T) {
body := readWorkflowFile(t, cliRepositoryRoot(t), file)
block, err := extractWoodpeckerCommand(body, "deliver")
if err != nil {
t.Fatal(err)
}
guard, _, ok := strings.Cut(block, "git check-ref-format")
if !ok {
t.Fatal("workflow has no tag preparation boundary")
}
guard = strings.ReplaceAll(guard, "$${", "${")
for _, tag := range []string{"releasekit-test/product/v1.2.3", "releasekit-test/product/2026-12-01", "releasekit-test/root/" + strings.Repeat("a", 32)} {
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": tag, "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err != nil {
t.Fatalf("valid tag=%s output=%s error=%v", tag, output, err)
}
}
if output, err := executeWoodpeckerBlock(guard, t.TempDir(), map[string]string{"CI_COMMIT_TAG": "releasekit-test/foreign/" + strings.Repeat("a", 32), "CI_COMMIT_SHA": strings.Repeat("b", 40)}); err == nil {
t.Fatalf("foreign selector accepted: %s", output)
}
})
}
}
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) { func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
// Synthetic downloads must leave the caller's module cache untouched. // Synthetic downloads must leave the caller's module cache untouched.
callerCache := t.TempDir() callerCache := t.TempDir()
@@ -542,7 +567,7 @@ func executeWoodpeckerBlock(block, repository string, environment map[string]str
func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) { func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) {
t.Helper() t.Helper()
const module = "go.maximumdirect.net/releasekit" const module = "go.maximumdirect.net/releasekit"
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.26.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource)) goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.27.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
writeRepositoryFile(t, repository, "go.mod", goMod) writeRepositoryFile(t, repository, "go.mod", goMod)
cliGitRun(t, repository, "add", "go.mod") cliGitRun(t, repository, "add", "go.mod")
if includeSum { if includeSum {

View File

@@ -101,8 +101,11 @@ type DeliveryRequest struct {
// ModuleDir selects a repository-relative module directory; empty selects // ModuleDir selects a repository-relative module directory; empty selects
// the repository root. // the repository root.
ModuleDir string ModuleDir string
Product string // Source selects explicit source and publication capabilities. Nil retains
Version string // the ModuleDir Go-module shorthand.
Source *SourceSpec
Product string
Version string
// ExpectedTag optionally requires the full CI event tag to match the // ExpectedTag optionally requires the full CI event tag to match the
// selected module's derived tag before building or making hosted requests. // selected module's derived tag before building or making hosted requests.
ExpectedTag string ExpectedTag string
@@ -122,10 +125,16 @@ type DeliveryRequest struct {
// failures may leave some declared assets unreported. // failures may leave some declared assets unreported.
type DeliveryResult struct { type DeliveryResult struct {
RepositoryDir string RepositoryDir string
SourceDir string
SourceSubdir string
GoEnabled bool
Publication PublicationMode
VersionFormat VersionFormat
VersionPrefix string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
Tag string // complete derived Git tag. Tag string // complete derived Git tag.
Version string // selected stable semantic version. Version string // selected production or diagnostic identifier.
CandidateCommit string CandidateCommit string
ReleaseURL string ReleaseURL string
State DeliveryState State DeliveryState
@@ -165,6 +174,7 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{ internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
RepositoryDir: request.RepositoryDir, RepositoryDir: request.RepositoryDir,
ModuleDir: request.ModuleDir, ModuleDir: request.ModuleDir,
Source: internalSourceSpec(request.Source),
Product: request.Product, Product: request.Product,
Version: request.Version, Version: request.Version,
ExpectedTag: request.ExpectedTag, ExpectedTag: request.ExpectedTag,
@@ -173,7 +183,18 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
Prebuilt: prebuilt, Prebuilt: prebuilt,
Output: request.Output, Output: request.Output,
}) })
return publicDeliveryResult(internalResult, request.Version), publicPreflightError(err)
}
func publicDeliveryResult(internalResult internaldelivery.Result, version string) DeliveryResult {
result := DeliveryResult{Version: version}
result.RepositoryDir = internalResult.RepositoryDir result.RepositoryDir = internalResult.RepositoryDir
result.SourceDir = internalResult.Identity.SourceDir
result.SourceSubdir = internalResult.Identity.SourceSubdir
result.GoEnabled = internalResult.Identity.GoEnabled
result.Publication = PublicationMode(internalResult.Identity.Publication)
result.VersionFormat = VersionFormat(internalResult.Identity.VersionFormat)
result.VersionPrefix = internalResult.Identity.VersionPrefix
result.ModuleDir = internalResult.ModuleDir result.ModuleDir = internalResult.ModuleDir
result.ModulePath = internalResult.ModulePath result.ModulePath = internalResult.ModulePath
result.Tag = internalResult.Tag result.Tag = internalResult.Tag
@@ -185,7 +206,7 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro
result.Pending = deliveryAssets(internalResult.Pending) result.Pending = deliveryAssets(internalResult.Pending)
result.Conflicting = deliveryAssets(internalResult.Conflicting) result.Conflicting = deliveryAssets(internalResult.Conflicting)
result.Uncertain = deliveryAssets(internalResult.Uncertain) result.Uncertain = deliveryAssets(internalResult.Uncertain)
return result, publicPreflightError(err) return result
} }
// PreflightDelivery checks destination credentials and repository access using // PreflightDelivery checks destination credentials and repository access using

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
# Command line # Command line
ReleaseKit currently provides eight commands. The exit statuses below belong The exit statuses below belong
to the native executable. `go run` examples are convenient for source execution, to the native executable. `go run` examples are convenient for source execution,
but the Go driver maps a nonzero child exit status to 1. Use the built executable but the Go driver maps a nonzero child exit status to 1. Use the built executable
or `./scripts/release` for publication when distinct statuses are needed. or `./scripts/release` for publication when distinct statuses are needed.
@@ -22,26 +22,28 @@ Check a local candidate:
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
``` ```
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the `VERSION` must match the profile's selected identifier format. Options must precede the
version. The repository argument defaults to the current directory. ReleaseKit version. The repository argument defaults to the current directory. ReleaseKit
resolves its containing Git checkout root before selecting the module or profile; resolves its containing Git checkout root before selecting the module or profile;
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
captured module, version, full tag, and commit. It checks the committed release note and captured module, version, full tag, and commit. It checks the committed release note and
local Git state, runs the standard offline Go test suite (with `-race` when local Git state, runs the standard offline Go test suite when Go is selected (with `-race` when
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...` `validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
pass after successful tests when `validation.go.full_vet` is true. It then runs pass after successful tests when `validation.go.full_vet` is true. It then runs
selected package compilation and committed Go formatting, followed by selected package compilation and committed Go formatting, followed by
configured additional checks in profile order. It does not inspect remote configured additional checks in profile order. It does not inspect remote
availability or publish a tag. availability or publish a tag.
The profile's optional `module_dir` selects a repository-relative physical For legacy profiles, `module_dir` selects a repository-relative physical
module directory; omission selects the root module. Validation and configured module directory; omission selects the root module. Explicit profiles select
product checks use that module selection. Additional check commands run with source and Go capabilities as described in the [configuration reference](config.md).
the selected module as their working directory and receive Additional check commands run with
the selected source as their working directory and receive
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`, `RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
`RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their `RELEASEKIT_SOURCE_DIR`, `RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
environment. These values are added to each child environment without changing environment. These values are added to each child environment without changing
the ReleaseKit process environment. the ReleaseKit process environment. Module values are empty for source-only
selections.
When `validation.go.compile_targets` is selected, `check` compiles all packages When `validation.go.compile_targets` is selected, `check` compiles all packages
for each configured `GOOS/GOARCH` pair after tests and full vet, using static for each configured `GOOS/GOARCH` pair after tests and full vet, using static
@@ -77,20 +79,20 @@ Unsupported argument sequences print usage to standard error.
Publish a source tag: Publish a source tag:
```sh ```sh
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--record-dir DIR] VERSION go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] [--expected-source DIR] [--record-dir DIR] VERSION
``` ```
`publish` reads the same product, remote, validation, and additional-check `publish` reads the same product, remote, validation, and additional-check
settings as `check`. It checks the authoritative remote and validates the settings as `check`. It checks the authoritative remote and validates the
candidate: the single standard offline Go test suite runs first, with `-race` candidate: when Go is selected, the standard offline Go test suite runs first, with `-race`
when `validation.go.race` is true. When `validation.go.full_vet` is true, when `validation.go.race` is true. When `validation.go.full_vet` is true,
test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful
tests. Selected package compilation and committed Go formatting follow. The tests. Selected package compilation and committed Go formatting follow. The
selected file checks then run in order: workspace files, local replacements, selected file checks then run in order: workspace files, local replacements,
file size, and Markdown. Configured checks run afterward in profile order. It file size, and Markdown. Configured checks run afterward in profile order. It
then creates an annotated local tag then creates an annotated local tag
and pushes only its exact full tag object. It prints the confirmed semantic and pushes only its exact full tag object. It prints the confirmed identifier,
version, full tag, candidate commit, and tag object full tag, candidate commit, and tag object
on success. Validation on success. Validation
progress and failed publication state, including the captured publication progress and failed publication state, including the captured publication
endpoint for recovery, are written to standard error. HTTP(S) endpoint endpoint for recovery, are written to standard error. HTTP(S) endpoint
@@ -129,10 +131,11 @@ It reports outside-checkout links to standard error unless boundary enforcement
is selected; submodule contents remain out of scope. Markdown failures stop is selected; submodule contents remain out of scope. Markdown failures stop
publication before product checks or tag creation. publication before product checks or tag creation.
`--expected-module DIR` optionally checks a launcher's selected physical module `--expected-module DIR` and `--expected-source DIR` optionally check a
against the profile's `module_dir` before candidate work. Both paths are launcher's selected physical directory against the profile's source selection
normalized relative to the repository; the profile remains the source of module before candidate work. Paths are normalized relative to the repository; the
selection. The root selection is `.`. profile remains the source of selection. If both flags are supplied, both must
match. The root selection is `.`.
The optional profile field `expected_push_url` applies only to `publish`. A The optional profile field `expected_push_url` applies only to `publish`. A
nonempty value must exactly match the effective push URL resolved by Git; nonempty value must exactly match the effective push URL resolved by Git;
@@ -230,12 +233,26 @@ output directory are invalidated; no new receipt is written. An
empty target list returns the source commit without building or writing a empty target list returns the source commit without building or writing a
receipt. receipt.
The current receipt format carries the selected source and release identity;
receipts from older formats must be regenerated with `build`.
The command returns status 0 on completion, 1 for build or output failure, and The command returns status 0 on completion, 1 for build or output failure, and
2 for usage, profile, or invalid-version errors. It builds the current source 2 for usage, profile, or invalid-version errors. It builds the current source
tree and does not perform candidate validation or remote publication. `check` tree and does not perform candidate validation or remote publication. `check`
and `publish` run the same configured build after their one candidate and `publish` run the same configured build after their one candidate
validation, using temporary output outside the worktree. validation, using temporary output outside the worktree.
Inspect working release configuration without creating a release:
```sh
releasekit validate [--repo DIR] [--config FILE] [--context local|ci] [--operation NAME ...] [--offline] [--assets DIR] [--json]
```
Validation defaults to local credentials and read-only remote access. Operation
flags narrow the selected capabilities; `--offline` omits remote observations.
See the [readiness guide](consumers/readiness.md) for scope, evidence, and exit
statuses.
Deliver a tagged source release: Deliver a tagged source release:
```sh ```sh
@@ -243,8 +260,8 @@ go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERS
``` ```
`deliver` requires a `delivery` profile object with an explicit `deliver` requires a `delivery` profile object with an explicit
`"forge": "gitea"` selection and a token loaded from its configured environment `"forge": "gitea"` selection and a token loaded from its configured local
variable or token file. The destination URL does not select a forge. Selection credential file. The destination URL does not select a forge. Selection
errors are reported before token access or delivery work. Credential selection errors are reported before token access or delivery work. Credential selection
and errors are defined in the [configuration reference](config.md). It verifies and errors are defined in the [configuration reference](config.md). It verifies
the local tag, clean tagged checkout, hosted tag, and committed release note, the local tag, clean tagged checkout, hosted tag, and committed release note,
@@ -301,23 +318,23 @@ known missing assets are added. See the
Prepare a tagged CI checkout and deliver it: Prepare a tagged CI checkout and deliver it:
```sh ```sh
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] [--expected-source DIR] --commit OID TAG
``` ```
`TAG` is the complete Git tag name, including any module path prefix. Its last `TAG` is the complete Git tag name, including any source path prefix. Its last
path component must be a stable semantic version; other commands continue to component is validated against the profile's selected version format after
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from checkout. By default, `ci-deliver` fetches the exact `TAG` from
the selected Git remote (default `origin`), requires its peeled commit to match the selected Git remote (default `origin`), requires its peeled commit to match
the required full `--commit` object ID, checks out that commit detached, then the required full `--commit` object ID, checks out that commit detached, then
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
checks read-only against the existing checkout and does not fetch or check out. checks read-only against the existing checkout and does not fetch or check out.
Preparation diagnostics mask userinfo in HTTP(S) remote URLs. Preparation diagnostics mask userinfo in HTTP(S) remote URLs.
In either mode, it loads the profile from the verified source. `--expected-module` In either mode, it loads the profile from the verified source. The optional
optionally checks that the profile selects the module chosen by a launcher; `--expected-module` and `--expected-source` checks verify the launcher's
module selection itself remains profile-owned. The command compares the selected selected directory against the profile. The command compares the selected
module's derived release tag with the full event tag before forge access or source's derived release tag with the full event tag before forge access or
dependency preparation, then validates explicit forge selection and resolves dependency preparation, then validates explicit forge selection and resolves
the configured token. For binary profiles, it performs a read-only repository the configured CI environment token. For binary profiles, it performs a read-only repository
preflight before downloading application preflight before downloading application
dependencies; delivery performs a fresh check after dependency preparation. dependencies; delivery performs a fresh check after dependency preparation.
Source-only profiles rely on delivery's automatic preflight and skip dependency Source-only profiles rely on delivery's automatic preflight and skip dependency
@@ -351,3 +368,40 @@ consumers without a declared
ReleaseKit module dependency can use the separately installed-tool command. ReleaseKit module dependency can use the separately installed-tool command.
See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for
compatible Go environments, retries, and preparation details. compatible Go environments, retries, and preparation details.
## Rehearsal and recovery
```sh
releasekit test [--repo DIR] [--config FILE] [--ref REF] [--record-dir DIR] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]
releasekit test-resume --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--timeout DURATION] [--cleanup-timeout DURATION] [--json]
releasekit test-cleanup --record FILE [--token-file FILE] [--woodpecker-token-file FILE] [--cleanup-timeout DURATION] [--json]
```
`test` captures `HEAD` or `--ref`, reads the profile from that commit, and
pushes a temporary annotated diagnostic tag. It observes the selected
Woodpecker delivery step, verifies its recorded page and artifact evidence,
and attempts cleanup only after matching CI runs are quiescent. It does not
require a clean checkout, choose a production version, or cancel CI. The
observation timeout defaults to 30 minutes; `--timeout 0` waits until the
context is canceled. Cleanup defaults to two minutes and its timeout must be
positive.
The command reports the exact private record path. Recovery always requires
that explicit path; it never selects a newest attempt. Local credentials come
from the recorded commit's profile unless file overrides are supplied. With
both overrides, recovery can load credentials without the recorded profile;
the checkout remains necessary for Git operations. `test-resume` observes and
then cleans; `test-cleanup` reports cleanup independently of prior verification.
Human output uses the current durable executable in its recovery commands when
available. If it was a temporary Go-run executable, use a supported ReleaseKit
tool with the same record after that executable disappears.
The [rehearsal guide](consumers/rehearsal.md) covers permissions and the limits
of the result.
With `--json`, each command emits one `schema_version: 1` object with safe
identity, workflow, build, verification and cleanup outcomes, resource links,
remaining resources and diagnostics. Status 0 means verification and cleanup
succeeded for `test` or `test-resume`, or cleanup succeeded for `test-cleanup`.
Status 2 denotes usage, configuration or required input failure before effects;
1 denotes a known failure or reporting error; 3 denotes unresolved CI or
remote state or pending cleanup. An error can accompany useful partial results.

View File

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

View File

@@ -1,8 +1,22 @@
# Adopt ReleaseKit # Adopt ReleaseKit
Use a versioned Go tool dependency when ReleaseKit provides the repository's Use a versioned Go tool dependency when a Go module provides the repository's
release commands. This records the CLI in `go.mod` and keeps it available to release commands. Source-only repositories can instead use the installed-tool
maintainers without adding imports to application or library code. launcher described below.
## Source-only repositories
The [source-only example](../../examples/source-only/README.md) provides a
profile, local launcher, and tag-verified Woodpecker workflow without requiring
an application `go.mod`. Commit a root `.releasekit-version` containing one
stable ReleaseKit module version. The example selects v0.11.0, which supplies
the source-only profile and workflow interfaces.
The maintained installer uses the same committed pin locally and in CI,
installs the host executable in the ignored `.releasekit/tools` directory,
and preserves Go proxy and checksum settings. A failed install does not leave a
usable partial executable. The durable executable also supports the exact
publication-recovery command printed after an uncertain push.
## CLI tool dependency ## CLI tool dependency
@@ -15,6 +29,8 @@ go mod tidy
``` ```
Select a release that implements the API, profile, and workflow you are adopting. Select a release that implements the API, profile, and workflow you are adopting.
The [v0.11.0 release note](../releases/v0.11.0.md) covers
the new source selections, credential contexts, and rehearsal workflow.
The vanity module path starts with v0.5.0. Versions through v0.4.2 declare the 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. original module path and use their corresponding historical instructions.
The module-release interface requires a release containing that feature; The module-release interface requires a release containing that feature;
@@ -26,8 +42,8 @@ declaration retains the dependency through `go mod tidy`. Commit the resulting
version and review the module changes. version and review the module changes.
The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit
module declares a Go 1.26.0 minimum, so use Go 1.26.0 or later for the current module declares a Go 1.27.0 minimum, so use Go 1.27.0 or later for the current
release. Tool dependencies share the consumer's module graph: their requirements source. Tool dependencies share the consumer's module graph: their requirements
participate in dependency version selection and can raise the consumer module's participate in dependency version selection and can raise the consumer module's
Go minimum. See the Go minimum. See the
[Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool). [Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool).
@@ -110,7 +126,7 @@ Existing consumer tags retain their recorded module files, tool selection, and
matching workflows for retries. Apply these migration steps to new consumer matching workflows for retries. Apply these migration steps to new consumer
revisions. Source repository and hosted release URLs use revisions. Source repository and hosted release URLs use
`https://forge.maximumdirect.net/base-layer/releasekit`; the vanity path is the `https://forge.maximumdirect.net/base-layer/releasekit`; the vanity path is the
Go module identity. The Go consumer minimum remains 1.26.0. Go module identity.
## CI adoption ## CI adoption

View File

@@ -36,9 +36,9 @@ func build(ctx context.Context) error {
} }
``` ```
`Build` resolves `ModuleDir` and the selected module's working-tree declaration `Build` resolves the selected source and module's working-tree declaration
once, records the repository's current `HEAD`, injects the selected stable once, records the repository's current `HEAD`, injects the selected identifier
version into `buildinfo.Version`, and returns repository/module identity, the into `buildinfo.Version`, and returns repository/source and module identity, the
derived tag, compiler identity, normalized targets, artifact paths, filenames, derived tag, compiler identity, normalized targets, artifact paths, filenames,
and SHA-256 digests. It does not require a release note, unused tag, clean and SHA-256 digests. It does not require a release note, unused tag, clean
`main`, or publication. Names follow `main`, or publication. Names follow
@@ -47,6 +47,10 @@ target pair is built once, at its first position. Local builds may use modified
source. `SourceVerified` is true only after a complete build observes clean source. `SourceVerified` is true only after a complete build observes clean
source and the same HEAD before and after compilation; binary delivery requires source and the same HEAD before and after compilation; binary delivery requires
that fact. This observation is not a source snapshot or attestation guarantee. that fact. This observation is not a source snapshot or attestation guarantee.
An explicit `Source` with `GoEnabled` can select general source publication and
a calendar format or a product major independent of the module import path.
The optional [rehearsal](rehearsal.md) uses its own diagnostic version and
verifies temporary artifacts through the actual CI delivery job.
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
module. The default output directory is `<module>/dist`; a relative `OutputDir` module. The default output directory is `<module>/dist`; a relative `OutputDir`

View File

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

View File

@@ -9,12 +9,16 @@ The operation accepts historical lightweight and annotated tags, including a
detached checkout, when the checked-out `HEAD` identifies the selected tag detached checkout, when the checked-out `HEAD` identifies the selected tag
commit. It does not require the old remote `main` to match. commit. It does not require the old remote `main` to match.
Delivery resolves the selected module's declaration and release note from the Delivery resolves the selected source and release note from the captured commit;
captured commit. `Version` remains the semantic version; the full tag includes it reads a module declaration only when Go is enabled. `Version` follows the
the selected module's repository-relative physical path when it is nested. The selected identifier format, and the full tag follows the selected publication
profile or API request selects the physical module directory. The optional API mode. The profile or API request selects the physical source directory. The optional API
`ExpectedTag` checks that a CI event's literal tag agrees with the derived tag `ExpectedTag` checks that a CI event's literal tag agrees with the derived tag
before any build or hosted request. before any build or hosted request. Page-only source delivery does not require a
Go module or compiler.
The optional [rehearsal](rehearsal.md) runs this delivery machinery in the
tag-triggered CI job with a diagnostic identity and read-back verification.
## CI preparation ## CI preparation
@@ -74,7 +78,10 @@ Add a Gitea destination to the profile:
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",
"token_env": "RELEASEKIT_GITEA_TOKEN" "credentials": {
"local": {"token_file": ".releasekit/gitea-token"},
"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}
}
} }
} }
``` ```
@@ -83,11 +90,11 @@ Fetch and check out the immutable tag, then deliver it:
```sh ```sh
git checkout --detach v1.2.3 git checkout --detach v1.2.3
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3 releasekit deliver v1.2.3
``` ```
The CLI resolves the token for delivery using the configured environment The CLI resolves the local token file for `deliver` and the CI environment
variable or token file. It verifies the local checkout and hosted tag before variable for `ci-deliver`. It verifies the local checkout and hosted tag before
creating or accepting a hosted release page. The full checked-in note is the creating or accepting a hosted release page. The full checked-in note is the
hosted body. A retry accepts an identical page and matching attachments, adds hosted body. A retry accepts an identical page and matching attachments, adds
only missing assets, and reports conflicts without replacing content. only missing assets, and reports conflicts without replacing content.
@@ -106,15 +113,15 @@ as `.releasekit/gitea-token` and configure:
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",
"token_file": ".releasekit/gitea-token" "credentials": {"local": {"token_file": ".releasekit/gitea-token"}}
} }
} }
``` ```
Add `.releasekit/` to the consumer's ignore rules and use owner-only file 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 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 tagged checkout. CI supplies the variable selected in its own credential declaration. See the
[configuration reference](../config.md) for precedence, path resolution, and the [configuration reference](../config.md) for context selection, path resolution, and the
optional candidate check. The validator checks the selected committed paths; optional candidate check. The validator checks the selected committed paths;
it does not scan for secrets in other files or past commits. it does not scan for secrets in other files or past commits.
For nested modules, the note comes from that module's committed For nested modules, the note comes from that module's committed
@@ -131,17 +138,18 @@ separate credentials between build and delivery, use two invocations:
```sh ```sh
releasekit build --output dist v1.2.3 releasekit build --output dist v1.2.3
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3 releasekit deliver --assets dist v1.2.3
``` ```
The build command does not need delivery credentials. The `--assets DIR` The build command does not need delivery credentials. The `--assets DIR`
directory must contain the private `.releasekit-build.json` receipt created by directory must contain the private `.releasekit-build.json` receipt created by
`build`. ReleaseKit checks its schema, repository, commit, version, resolved `build`. ReleaseKit checks its schema, repository, commit, source selection,
module directory and path, full tag, normalized build settings, and artifact identity kind, version, module directory and path, full tag, normalized build
declarations. Old receipts must be regenerated with the updated `build` settings, and artifact declarations. Old receipts must be regenerated with the
command. Delivery verifies the artifact bytes and sizes after read-only 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 preflight and before any hosted write; caller-owned files remain available for
retries. retries. See the [receipt format](../integrations/build-receipts.md) for its
identity and compatibility rules.
Ordinary `deliver` does not download application dependencies or change the Ordinary `deliver` does not download application dependencies or change the
checkout. checkout.

View File

@@ -31,6 +31,13 @@ physical location. `Version` remains the stable semantic version. The note is
the note path but is removed from the tag prefix only when the module path ends the note path but is removed from the tag prefix only when the module path ends
in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared
`ModulePath`, complete `Tag`, and existing commit and tag-object evidence. `ModulePath`, complete `Tag`, and existing commit and tag-object evidence.
For general source publication, set `Source` as described in the
[candidate check guide](check.md#local-candidate-check). `PublicationResult`
also reports the selected source directory and capabilities.
Publication does not require a hosted delivery rehearsal. The optional
[rehearsal](rehearsal.md) uses separately recorded temporary resources and does
not change the production tag's completion or immutability rules.
The optional `ValidationSpec.SharedFiles` selects additional committed files The optional `ValidationSpec.SharedFiles` selects additional committed files
for enabled file checks. Its nil and empty-slice behavior is described in the for enabled file checks. Its nil and empty-slice behavior is described in the
@@ -44,7 +51,7 @@ when fetch and push URLs differ. A mismatch fails preflight before Go validation
callbacks, or tag creation; detect it with callbacks, or tag creation; detect it with
`errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this `errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this
publication-only field. publication-only field.
It runs one `go test -mod=readonly -count=1 ./...` suite with the available When Go is selected, it runs one `go test -mod=readonly -count=1 ./...` suite with the available
compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with
`-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after `-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after
successful tests, with test-time vet disabled for that suite. The zero values successful tests, with test-time vet disabled for that suite. The zero values

View File

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

View File

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

View File

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

View File

@@ -40,6 +40,10 @@ declared module stored at `integrations/core` derives the same tag. ReleaseKit
removes a final physical `/v2` directory from the tag prefix only when the removes a final physical `/v2` directory from the tag prefix only when the
module declaration has that `/v2` suffix. A module-local note stays at module declaration has that `/v2` suffix. A module-local note stays at
`<module>/docs/releases/<version>.md`, including a physical `/v2` directory. `<module>/docs/releases/<version>.md`, including a physical `/v2` directory.
General source releases instead derive the tag from their selected source
directory or explicit product prefix and the selected identifier; the source
note remains under `<source>/docs/releases/`. See the
[configuration reference](../config.md) for selection and version formats.
The default shared validation convention uses repository-root `COPYRIGHT`, The default shared validation convention uses repository-root `COPYRIGHT`,
`LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license `LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license
layout and release-note links. Use the complete derived tag as the immutable layout and release-note links. Use the complete derived tag as the immutable

View File

@@ -13,9 +13,17 @@ Each saved attempt is one complete JSON document with this versioned envelope:
```json ```json
{ {
"format_version": 1, "format_version": 3,
"evidence": { "evidence": {
"repository_dir": "/work/project", "repository_dir": "/work/project",
"source_dir": "/work/project",
"source_subdir": ".",
"go_enabled": true,
"publication_mode": "go-module",
"version_format": "semver",
"version_prefix": "v",
"identity_kind": "production",
"note_path": "docs/releases/v1.2.3.md",
"module_dir": "/work/project", "module_dir": "/work/project",
"module_path": "example.com/project", "module_path": "example.com/project",
"version": "v1.2.3", "version": "v1.2.3",
@@ -34,20 +42,20 @@ stopped before they were captured; loading preserves that partial evidence and
does not fill fields from the current checkout. Additional fields in a does not fill fields from the current checkout. Additional fields in a
supported version are ignored. A missing or unsupported version, malformed or supported version are ignored. A missing or unsupported version, malformed or
multiple JSON documents, or fields with invalid structural types are reported multiple JSON documents, or fields with invalid structural types are reported
as record-format errors. The codec supports versions 1 and 2; no migration from as record-format errors. The codec reads versions 1, 2, and 3; no migration from
an unsupported version is performed. an unsupported version is performed.
Ordinary UTF-8 evidence uses version 1. Evidence containing other pathname or New records use version 3, including source and selection evidence. Legacy
endpoint bytes uses version 2 with the same `evidence` object and an additional versions 1 and 2 retain only the evidence they captured. Version 2 and version 3
`evidence_bytes` object. Each entry in `evidence_bytes` uses an evidence field may include an `evidence_bytes` object for non-UTF-8 string values. Each entry
in `evidence_bytes` uses an evidence field
name and a standard base64 string containing its exact bytes. That entry name and a standard base64 string containing its exact bytes. That entry
supplies the field's value when loading; the writer omits its lossy string form supplies the field's value when loading; the writer omits its lossy string form
from `evidence`. Invalid known-field types or base64 encodings produce a from `evidence`. Invalid known-field types or base64 encodings produce a
record-format error with the available decoding cause. Unknown field names are record-format error with the available decoding cause. Unknown field names are
ignored. This representation applies ignored. This representation applies
to every evidence field and preserves the same identity as typed Go evidence. to string evidence fields and preserves the same identity as typed Go evidence.
Older CLIs that support only version 1 report an unsupported version for these Older CLIs report an unsupported version for records they cannot read.
byte-containing records; use a CLI supporting version 2 to load them.
The `endpoint` value is stored exactly as captured and may contain credentials. The `endpoint` value is stored exactly as captured and may contain credentials.
Private records are sensitive. Do not copy them into public logs or source Private records are sensitive. Do not copy them into public logs or source
@@ -65,7 +73,8 @@ not private attempt records or a Go serialization of public structs.
was read. Available `observed_tag_object` and `observed_commit` fields are was read. Available `observed_tag_object` and `observed_commit` fields are
included when present. A `diagnostic` is included for unresolved observation included when present. A `diagnostic` is included for unresolved observation
or record loading failure. Loading failure omits evidence, state, and observed or record loading failure. Loading failure omits evidence, state, and observed
IDs. IDs. Safe evidence may include source, capability, publication, and version
selection fields when those were captured.
`publication-attempts` includes `record_dir`, an `attempts` array with each `publication-attempts` includes `record_dir`, an `attempts` array with each
`record_path` and safe `evidence`, and a `diagnostics` array. A top-level `record_path` and safe `evidence`, and a `diagnostics` array. A top-level

View File

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

View File

@@ -3,45 +3,50 @@
Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports
two Go facades and a command-line interface: two Go facades and a command-line interface:
- The root `releasekit` package is the orchestration facade. `Check` validates - The root `releasekit` package is the orchestration facade. `Validate` inspects
working setup and read-only access, `Check` validates
one local candidate, `Publish` validates and publishes its exact annotated one local candidate, `Publish` validates and publishes its exact annotated
source tag, `Build` compiles selected application targets, and `Deliver` source tag, `Build` compiles selected application targets, and `Deliver`
delivers a tagged note page and any declared assets. `PrepareTaggedCheckout` delivers a tagged note page and any declared assets. `Rehearse`,
`ResumeRehearsal`, and `CleanupRehearsal` coordinate explicitly recorded
temporary diagnostics. `PrepareTaggedCheckout`
and `PrepareBuildDependencies` provide explicit local CI preparation. and `PrepareBuildDependencies` provide explicit local CI preparation.
- `buildinfo` is the small runtime facade. `Version` reports the injected - `buildinfo` is the small runtime facade. `Version` reports the injected
application version, the main-module version when available, or `dev`. application version, the main-module version when available, or `dev`.
- `cmd/releasekit` is the executable interface. Its `version`, `check`, - `cmd/releasekit` is the executable interface. Its `version`, `validate`, `check`,
`publish`, `reconcile`, `publication-attempts`, `build`, `deliver`, and `publish`, `reconcile`, `publication-attempts`, `build`, `deliver`,
`ci-deliver` commands adapt profiles and command output to the supported `ci-deliver`, `test`, `test-resume`, and `test-cleanup` commands adapt
library operations. profiles and command output to the supported library operations.
See the [CLI contract](../cli.md), [configuration reference](../config.md), See the [CLI contract](../cli.md), [configuration reference](../config.md),
[candidate check guide](../consumers/check.md), [candidate check guide](../consumers/check.md),
[source publication guide](../consumers/publish.md), [source publication guide](../consumers/publish.md),
[publication record format](../integrations/publication-records.md), [publication record format](../integrations/publication-records.md),
[build guide](../consumers/build.md), [build guide](../consumers/build.md),
[delivery guide](../consumers/delivery.md), and [delivery guide](../consumers/delivery.md),
[readiness guide](../consumers/readiness.md),
[rehearsal guide](../consumers/rehearsal.md), and
[runtime version guide](../consumers/runtime-version.md) for task-oriented use. [runtime version guide](../consumers/runtime-version.md) for task-oriented use.
Go declarations and GoDoc remain the owners of exact exported contracts. Go declarations and GoDoc remain the owners of exact exported contracts.
## Module and dependencies ## Module and dependencies
The module is `go.maximumdirect.net/releasekit`, with Go language The module is `go.maximumdirect.net/releasekit`, with Go language
version `1.26.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal version `1.27.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
validation; public facades do not expose either dependency. `go list ./...` validation; public facades do not expose either dependency. `go list ./...`
reports these implemented packages: reports these implemented packages:
| Package | Responsibility | | Package | Responsibility |
| --- | --- | | --- | --- |
| `releasekit` | Public orchestration facade and consumer-owned request/result types. | | `releasekit` | Public orchestration facade and facade-owned request/result types. |
| `buildinfo` | Public runtime version accessor. | | `buildinfo` | Public runtime version accessor. |
| `cmd/releasekit` | Executable entry point, command routing, output, and exit status. | | `cmd/releasekit` | Executable entry point, command routing, output, and exit status. |
| `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. | | `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. |
| `internal/apicheck` | Compiled-export and import-boundary checks run during development. | | `internal/apicheck` | Compiled-export and import-boundary checks run during development. |
| `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. | | `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. |
| `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. | | `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. |
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. | | `internal/candidate` | Release identifier and note validation, repository-state checks, candidate capture, and post-validation checks. |
| `internal/delivery` | 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/delivery` | Read-only backend preflight, captured-commit source and optional module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, artifact declaration, manifest assembly, shared page and asset policy, streamed comparisons, write recovery, and delivery outcomes. |
| `internal/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. | | `internal/forge` | Backend contract, neutral observations and failures, opaque handles, preflight classifications, and write evidence shared by delivery policy and adapters. |
| `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. | | `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
| `internal/gitea` | Gitea destination rules, authenticated repository preflight, HTTP operations and codecs, opaque handle interpretation, response validation, redirects, multipart streaming, and protocol-to-neutral failure conversion. | | `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. |
@@ -49,11 +54,15 @@ reports these implemented packages:
| `internal/tempdir` | Disposable system temporary storage outside source worktrees. | | `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
| `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. | | `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. |
| `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. | | `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. |
| `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. | | `internal/readiness` | Working/committed input inspection and read-only setup observations for explicitly selected capabilities. |
| `internal/recordstore` | Shared private-record location and worktree safety checks. |
| `internal/rehearsal` | Diagnostic tag manifests, private attempt evidence, dispatch, and exact CI job observation for rehearsal recovery. |
| `internal/releaseidentity` | Committed and working source and optional Go module selection, declaration reading, and production/diagnostic tag and note identity. |
| `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. | | `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. | | `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. |
| `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. | | `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. |
| `internal/versioncontract` | Shared stable-version rules and linker-symbol identity. | | `internal/versioncontract` | Shared SemVer and calendar identifier rules and linker-symbol identity. |
| `internal/woodpecker` | Authenticated read-only CI repository, pipeline, workflow, step, and streamed log observation. |
The `buildinfo` facade depends only on its small runtime implementation. The The `buildinfo` facade depends only on its small runtime implementation. The
root facade forwards to internal implementation packages. The CLI adapter is root facade forwards to internal implementation packages. The CLI adapter is

View File

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

View File

@@ -13,18 +13,24 @@ when the intended annotated tag is successfully
pushed, or when one exact-object recovery query confirms that the push pushed, or when one exact-object recovery query confirms that the push
succeeded. CI and consumer installation are not completion checks. succeeded. CI and consumer installation are not completion checks.
An optional [delivery rehearsal](consumers/rehearsal.md) exercises the same
tagged CI workflow with temporary diagnostic resources before a release. It is
not a publication gate. Configure the committed profile's Woodpecker settings
and separate local token before invoking it, and retain any reported record
until cleanup is resolved.
## Prepare a candidate ## Prepare a candidate
For local hosted-page delivery, save a Gitea personal access token in For local hosted-page delivery, save a Gitea personal access token in
`.releasekit/gitea-token` with owner-only file permissions. The file contains `.releasekit/gitea-token` with owner-only file permissions. The file contains
only the token. ReleaseKit's profile selects this file as a fallback to only the token. ReleaseKit's profile selects this file for local delivery and
`RELEASEKIT_GITEA_TOKEN`; `.releasekit/` is already ignored. Its optional `RELEASEKIT_GITEA_TOKEN` for CI; `.releasekit/` is already ignored. Its optional
`validation.forbidden_files` selection checks that this path is absent from the `validation.forbidden_files` selection checks that this path is absent from the
committed candidate. Source publication requires no delivery token. The committed candidate. Source publication requires no delivery token. The
[configuration reference](config.md) owns credential selection and validator [configuration reference](config.md) owns credential selection and validator
semantics. semantics.
Use a clean clone on `main`. The chosen build toolchain is Go 1.26.10. Make that Use a clean clone on `main`. The chosen build toolchain is Go 1.27.4. Make that
local installation the active `go` command for preparation, building the release local installation the active `go` command for preparation, building the release
executable, and candidate validation: executable, and candidate validation:
@@ -40,7 +46,7 @@ The maintained [source-delivery image](../examples/woodpecker/releasekit-source-
and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the
chosen build toolchain; update them together when that selection changes. chosen build toolchain; update them together when that selection changes.
The current consumer minimum is Go 1.26.0, declared in [go.mod](../go.mod). The current consumer minimum is Go 1.27.0, declared in [go.mod](../go.mod).
Keep it for a release unless release preparation deliberately selects a newer Keep it for a release unless release preparation deliberately selects a newer
series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain). series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain).
When increasing it, update `go.mod` to the first stable version of the selected When increasing it, update `go.mod` to the first stable version of the selected

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

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

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

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

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

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

View File

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

View File

@@ -1,7 +1,7 @@
# Multi-module release example # Multi-module release example
This example maps selectors and complete event tags to a physical Go module This example maps selectors and complete event tags to a physical Go module
directory and a repository-root profile. The library derives the release tag directory or installed tool and a repository-root profile. The library derives the release tag
from the selected module declaration and physical location; the table only from the selected module declaration and physical location; the table only
selects the corresponding profile and checkout directory. selects the corresponding profile and checkout directory.
@@ -9,17 +9,18 @@ Copy the contents of this directory into a consumer repository root, keeping
the listed module directories and profile paths at those locations, then run the listed module directories and profile paths at those locations, then run
the launcher from that checkout. the launcher from that checkout.
The sample modules declare Go 1.26.0, matching the current ReleaseKit consumer The sample modules declare Go 1.27.0, matching the current ReleaseKit consumer
minimum. minimum.
## Select the release tool ## Select the release tool
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
ReleaseKit version at or after the v0.5.0 vanity-path migration, then register ReleaseKit version that supports the selected source and rehearsal features,
that tool in each consumer module before running the launcher or workflow: then register that tool in each consumer module before running the launcher or
workflow. Version v0.11.0 supplies these interfaces:
```sh ```sh
: "${RELEASEKIT_TOOL_VERSION:?Select a ReleaseKit release with module-release support}" RELEASEKIT_TOOL_VERSION=v0.11.0
for module_dir in . integrations/ckconfig integrations/core/v2; do for module_dir in . integrations/ckconfig integrations/core/v2; do
go -C "$module_dir" get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}" go -C "$module_dir" get -tool "go.maximumdirect.net/releasekit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
go -C "$module_dir" mod tidy go -C "$module_dir" mod tidy
@@ -38,11 +39,12 @@ support and migration from earlier versions.
1. Local selector. 1. Local selector.
2. Shell pattern matched against a complete event tag. 2. Shell pattern matched against a complete event tag.
3. Repository-relative physical module directory (`.` means the root module). 3. Repository-relative tool module directory (`.` means the root module); `-` selects the installed tool from `.releasekit-version`.
4. Repository-relative profile path. 4. Repository-relative profile path.
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`, and The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`,
`integrations/core/v2.*`. The helper passes pattern text to the shell's `case` `integrations/core/v2.*`, and `configuration/20*`. Diagnostic tags select
the same row by their embedded selector. The helper passes pattern text to the shell's `case`
matcher without `eval`. A tag must match exactly one row; missing and ambiguous matcher without `eval`. A tag must match exactly one row; missing and ambiguous
matches are configuration errors. Module and profile paths may contain spaces. matches are configuration errors. Module and profile paths may contain spaces.
The `core-v2` row places the Go module physically under `integrations/core/v2` The `core-v2` row places the Go module physically under `integrations/core/v2`
@@ -68,9 +70,14 @@ Then select a module and semantic version with the shared launcher:
./release.sh root v1.2.3 ./release.sh root v1.2.3
./release.sh ckconfig v1.2.3 ./release.sh ckconfig v1.2.3
./release.sh core-v2 v2.1.0 ./release.sh core-v2 v2.1.0
./release.sh config 2026-12-05
``` ```
The launcher copies the selected module's `go.mod` and `go.sum` to temporary For a source-only row, the launcher installs the pinned tool with
`scripts/releasekit-tool` and passes the selected profile without interpreting
`-` as a source directory. The checked-in pin selects v0.11.0.
For Go rows, the launcher copies the selected module's `go.mod` and `go.sum` to temporary
alternate module files outside the checkout, resolves ReleaseKit from that alternate module files outside the checkout, resolves ReleaseKit from that
module's local dependency selection, adds the CLI tool declaration to that module's local dependency selection, adds the CLI tool declaration to that
temporary copy, and prepares its dependencies. It invokes the tool by its full temporary copy, and prepares its dependencies. It invokes the tool by its full
@@ -93,9 +100,9 @@ outside the checkout, and runs the selected ReleaseKit tool by its full package
path. It passes `ci-deliver --prepared`, the mapped profile, and the expected path. It passes `ci-deliver --prepared`, the mapped profile, and the expected
physical module to the tool. physical module to the tool.
The `core-v2` profile demonstrates binary delivery; the other profiles are The `core-v2` profile demonstrates binary delivery; the other profiles are
page-only. Before enabling the workflow, configure each selected profile's page-only. Before enabling the workflow, replace the example forge and Woodpecker
`delivery` object with `"forge": "gitea"`, its `base_url`, owner, and repository, destinations and repository ID in each profile. Configure separate local forge
then add the Woodpecker repository secret and Woodpecker token files, then add the Woodpecker repository secret
`releasekit_gitea_token`; the workflow exposes it as `releasekit_gitea_token`; the workflow exposes it as
`RELEASEKIT_GITEA_TOKEN` only in the delivery step. `RELEASEKIT_GITEA_TOKEN` only in the delivery step.
@@ -153,3 +160,13 @@ These commands use the repository-root profile paths even when invoked from a
child module. The core profile also verifies the native binary and injected child module. The core profile also verifies the native binary and injected
version. Prepared dependencies allow this verification with `GOPROXY=off` and version. Prepared dependencies allow this verification with `GOPROXY=off` and
`GOSUMDB=off`. `GOSUMDB=off`.
For an optional live rehearsal, select the corresponding tool and profile:
```sh
"$(./scripts/releasekit-tool)" test --config releasekit-config.json
go -C integrations/ckconfig tool go.maximumdirect.net/releasekit/cmd/releasekit test --config releasekit-ckconfig.json
```
A diagnostic ref contains the row selector and is verified against the
committed profile after bootstrap.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,6 +19,11 @@ trap 'rm -rf "$bootstrap_dir"' EXIT
tab=$(printf '\t') tab=$(printf '\t')
IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file" IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file"
if [ "$module_dir" = - ]; then
tool=$("$script_dir/scripts/releasekit-tool")
"$tool" publish --repo "$repository_dir" --config "$profile_path" "$version"
exit $?
fi
module_path=$repository_dir module_path=$repository_dir
if [ "$module_dir" != . ]; then if [ "$module_dir" != . ]; then
module_path=$repository_dir/$module_dir module_path=$repository_dir/$module_dir

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,11 +5,14 @@ when:
- refs/tags/v[01].* - refs/tags/v[01].*
- refs/tags/integrations/ckconfig/v* - refs/tags/integrations/ckconfig/v*
- refs/tags/integrations/core/v2.* - refs/tags/integrations/core/v2.*
- refs/tags/configuration/20*
- refs/tags/releasekit-test/*/*
steps: steps:
- name: deliver - name: deliver
image: golang:1.26.10-bookworm image: golang:1.27.4-bookworm
environment: environment:
# Woodpecker stores releasekit_gitea_token and injects it under this job variable.
RELEASEKIT_GITEA_TOKEN: RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token from_secret: releasekit_gitea_token
commands: commands:
@@ -36,6 +39,11 @@ steps:
"$${CI_WORKSPACE}/select-module.sh" tag "$${CI_COMMIT_TAG}" > "$${selection_file}" "$${CI_WORKSPACE}/select-module.sh" tag "$${CI_COMMIT_TAG}" > "$${selection_file}"
tab=$(printf '\t') tab=$(printf '\t')
IFS="$${tab}" read -r selector tag_pattern module_dir profile_path < "$${selection_file}" IFS="$${tab}" read -r selector tag_pattern module_dir profile_path < "$${selection_file}"
if [ "$${module_dir}" = - ]; then
tool=$("$${CI_WORKSPACE}/scripts/releasekit-tool")
"$${tool}" ci-deliver --repo "$${CI_WORKSPACE}" --config "$${profile_path}" --prepared --commit "$${expected_commit}" "$${CI_COMMIT_TAG}"
exit $?
fi
module_path="$${CI_WORKSPACE}" module_path="$${CI_WORKSPACE}"
if [ "$${module_dir}" != . ]; then if [ "$${module_dir}" != . ]; then
module_path="$${CI_WORKSPACE}/$${module_dir}" module_path="$${CI_WORKSPACE}/$${module_dir}"

View File

@@ -4,13 +4,33 @@
"build": { "build": {
"main_package": "./cmd/example", "main_package": "./cmd/example",
"binary_name": "example", "binary_name": "example",
"targets": ["linux/amd64", "linux/arm64", "darwin/arm64"] "targets": [
"linux/amd64",
"linux/arm64",
"darwin/arm64"
]
}, },
"delivery": { "delivery": {
"forge": "gitea", "forge": "gitea",
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",
"token_env": "RELEASEKIT_GITEA_TOKEN" "credentials": {
"local": {
"token_file": ".releasekit/gitea-token"
},
"ci": {
"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"
}
}
},
"rehearsal": {
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
} }
} }

View File

@@ -6,6 +6,22 @@
"base_url": "https://gitea.example", "base_url": "https://gitea.example",
"owner": "example", "owner": "example",
"repository": "example", "repository": "example",
"token_env": "RELEASEKIT_GITEA_TOKEN" "credentials": {
"local": {
"token_file": ".releasekit/gitea-token"
},
"ci": {
"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"
}
}
},
"rehearsal": {
"woodpecker": {
"base_url": "https://ci.example",
"repository_id": 42,
"workflow": "delivery",
"step": "deliver",
"token_file": ".releasekit/woodpecker-token"
}
} }
} }

1
examples/source-only/.gitignore vendored Normal file
View File

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

View File

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

View File

@@ -0,0 +1,47 @@
when:
- event: tag
ref:
include:
- refs/tags/20*
- refs/tags/releasekit-test/root/*
steps:
- name: deliver
image: golang:1.27.4-bookworm
environment:
# Woodpecker stores releasekit_gitea_token and injects this job variable.
RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token
commands:
- |
set -eu
test -n "$${CI_COMMIT_TAG}"
test -n "$${CI_COMMIT_SHA}"
case "$${CI_COMMIT_TAG}" in
releasekit-test/*)
releasekit_diagnostic=$${CI_COMMIT_TAG#releasekit-test/}
releasekit_selector=$${releasekit_diagnostic%%/*}
releasekit_attempt=$${releasekit_diagnostic#*/}
case "$${releasekit_attempt}" in
*[!0-9a-f]*|'') ;;
*)
if [ "$${#releasekit_attempt}" -eq 32 ] && [ -n "$${releasekit_selector}" ] && [ "$${releasekit_diagnostic}" != "$${releasekit_attempt}" ]; then
[ "$${releasekit_selector}" = root ] || { echo 'Unknown diagnostic selector' >&2; exit 2; }
fi ;;
esac ;;
esac
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)" = "$${expected_commit}"
test -z "$(git status --porcelain --untracked-files=all)"
export GOWORK=off GOTOOLCHAIN=local
tool=$("$${CI_WORKSPACE}/scripts/releasekit-tool")
"$${tool}" ci-deliver --repo "$${CI_WORKSPACE}" --prepared --commit "$${expected_commit}" "$${CI_COMMIT_TAG}"

View File

@@ -0,0 +1,41 @@
# Source-only configuration example
This example releases JSON configuration without a Go module. Copy its files
into a repository, set the product and forge destination in `releasekit.json`,
and select ReleaseKit v0.11.0 or a compatible later version in
`.releasekit-version`. The committed pin selects v0.11.0, which introduces
source-only calendar releases.
Install a local Go toolchain and Git. `scripts/releasekit-tool` reads the single
stable module version in the repository-root pin, installs the host executable
under the ignored `.releasekit/tools` directory, and prints its absolute path.
The private installation is reusable; installation can use the network, while
candidate validation remains offline. The launcher honors configured Go proxy,
checksum, and cache settings and disables automatic toolchain downloads and
workspace discovery. Update only the pin to select another tool version.
Save the local forge token in `.releasekit/gitea-token` and the separate
Woodpecker API token in `.releasekit/woodpecker-token` with owner-only
permissions. Set the Woodpecker URL and numeric repository ID in the profile. The ignore rule keeps it out of ordinary commits; the optional
`validation.forbidden_files` check rejects a candidate that includes that
path. Configure the Woodpecker stored secret `releasekit_gitea_token`, which the
workflow injects as the CI job variable `RELEASEKIT_GITEA_TOKEN`.
After preparing a committed release note and authoritative `main`, run:
```sh
./scripts/releasekit validate
./scripts/release 2026-12-05
```
The second command publishes the source tag. The [delivery workflow](.woodpecker/delivery.yml)
checks out and verifies the event tag before reading its committed pin. It
installs the same version for the host and invokes `ci-deliver`; page delivery
is separate from successful source publication. `scripts/releasekit` forwards
other CLI commands, including recovery commands, to the installed executable.
The publication failure output identifies the durable executable and exact
attempt record to use after the original launcher exits.
After configuring both tokens, `./scripts/releasekit test` runs the optional
live diagnostic through the same tagged delivery workflow and records cleanup
evidence for explicit recovery.

View File

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

View File

@@ -0,0 +1,3 @@
# Example Configuration 2026-12-05
Publish the initial configuration.

View File

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

View File

@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repository=$(git -C "$script_dir" rev-parse --show-toplevel)
exec "$script_dir/releasekit" publish --repo "$repository" "$@"

View File

@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export GOWORK=off GOTOOLCHAIN=local
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
tool=$("$script_dir/releasekit-tool")
exec "$tool" "$@"

View File

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

View File

@@ -1,11 +1,15 @@
when: when:
- event: tag - event: tag
ref: refs/tags/v* ref:
include:
- refs/tags/v*
- refs/tags/releasekit-test/root/*
steps: steps:
- name: deliver - name: deliver
image: golang:1.26.10-bookworm image: golang:1.27.4-bookworm
environment: environment:
# Woodpecker stores releasekit_gitea_token and injects it under this job variable.
RELEASEKIT_GITEA_TOKEN: RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token from_secret: releasekit_gitea_token
commands: commands:
@@ -13,6 +17,19 @@ steps:
set -eu set -eu
test -n "$${CI_COMMIT_TAG}" test -n "$${CI_COMMIT_TAG}"
test -n "$${CI_COMMIT_SHA}" test -n "$${CI_COMMIT_SHA}"
case "$${CI_COMMIT_TAG}" in
releasekit-test/*)
releasekit_diagnostic=$${CI_COMMIT_TAG#releasekit-test/}
releasekit_selector=$${releasekit_diagnostic%%/*}
releasekit_attempt=$${releasekit_diagnostic#*/}
case "$${releasekit_attempt}" in
*[!0-9a-f]*|'') ;;
*)
if [ "$${#releasekit_attempt}" -eq 32 ] && [ -n "$${releasekit_selector}" ] && [ "$${releasekit_diagnostic}" != "$${releasekit_attempt}" ]; then
[ "$${releasekit_selector}" = root ] || { echo 'Unknown diagnostic selector' >&2; exit 2; }
fi ;;
esac ;;
esac
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}" git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}" git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}") tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")

View File

@@ -1,15 +1,19 @@
matrix: matrix:
include: include:
- GO_IMAGE: golang:1.26.10-bookworm - GO_IMAGE: golang:1.27.4-bookworm
when: when:
- event: tag - event: tag
ref: refs/tags/v* ref:
include:
- refs/tags/v*
- refs/tags/releasekit-test/root/*
steps: steps:
- name: deliver - name: deliver
image: ${GO_IMAGE} image: ${GO_IMAGE}
environment: environment:
# Woodpecker stores releasekit_gitea_token and injects it under this job variable.
RELEASEKIT_GITEA_TOKEN: RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token from_secret: releasekit_gitea_token
commands: commands:
@@ -17,6 +21,19 @@ steps:
set -eu set -eu
test -n "$${CI_COMMIT_TAG}" test -n "$${CI_COMMIT_TAG}"
test -n "$${CI_COMMIT_SHA}" test -n "$${CI_COMMIT_SHA}"
case "$${CI_COMMIT_TAG}" in
releasekit-test/*)
releasekit_diagnostic=$${CI_COMMIT_TAG#releasekit-test/}
releasekit_selector=$${releasekit_diagnostic%%/*}
releasekit_attempt=$${releasekit_diagnostic#*/}
case "$${releasekit_attempt}" in
*[!0-9a-f]*|'') ;;
*)
if [ "$${#releasekit_attempt}" -eq 32 ] && [ -n "$${releasekit_selector}" ] && [ "$${releasekit_diagnostic}" != "$${releasekit_attempt}" ]; then
[ "$${releasekit_selector}" = root ] || { echo 'Unknown diagnostic selector' >&2; exit 2; }
fi ;;
esac ;;
esac
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}" git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}" git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}") tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")

8
go.mod
View File

@@ -1,8 +1,10 @@
module go.maximumdirect.net/releasekit module go.maximumdirect.net/releasekit
go 1.26.0 go 1.27.0
toolchain go1.27.4
require ( require (
github.com/yuin/goldmark/v2 v2.1.6 github.com/yuin/goldmark/v2 v2.1.16
golang.org/x/mod v0.40.0 golang.org/x/mod v0.43.0
) )

8
go.sum
View File

@@ -1,4 +1,4 @@
github.com/yuin/goldmark/v2 v2.1.6 h1:igy0q9JcqovoFXFx/XjtU8sHVhcUHavPj2sA3EoKJUE= github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
github.com/yuin/goldmark/v2 v2.1.6/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ= github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=

View File

@@ -74,11 +74,41 @@ func checkRepository(ctx context.Context, dir string) error {
if violations := checkValidationTypes(pkg); len(violations) != 0 { if violations := checkValidationTypes(pkg); len(violations) != 0 {
return fmt.Errorf("facade %s has invalid validation diagnostics:\n %s", path, strings.Join(violations, "\n ")) return fmt.Errorf("facade %s has invalid validation diagnostics:\n %s", path, strings.Join(violations, "\n "))
} }
if violations := checkRehearsalAPI(pkg); len(violations) != 0 {
return fmt.Errorf("facade %s has invalid rehearsal contracts:\n %s", path, strings.Join(violations, "\n "))
}
} }
} }
return nil return nil
} }
func checkRehearsalAPI(pkg *types.Package) []string {
var violations []string
for _, name := range []string{"RehearsalRequest", "RehearsalRecoveryRequest", "RehearsalResult", "RehearsalDeliveryRequest", "RehearsalDeliveryResult", "RehearsalError", "RehearsalTimeout", "RehearsalJob", "RehearsalWorkflow", "RehearsalArtifact"} {
object, ok := pkg.Scope().Lookup(name).(*types.TypeName)
if !ok || !namedTypeIs(object.Type(), pkg.Path(), name) {
violations = append(violations, fmt.Sprintf("missing facade-owned type %s", name))
}
}
for _, item := range []struct{ name, request, result string }{{"Rehearse", "RehearsalRequest", "RehearsalResult"}, {"ResumeRehearsal", "RehearsalRecoveryRequest", "RehearsalResult"}, {"CleanupRehearsal", "RehearsalRecoveryRequest", "RehearsalResult"}, {"DeliverRehearsal", "RehearsalDeliveryRequest", "RehearsalDeliveryResult"}} {
function, ok := pkg.Scope().Lookup(item.name).(*types.Func)
if !ok {
violations = append(violations, "missing facade operation "+item.name)
continue
}
signature, ok := function.Type().(*types.Signature)
if !ok || signature.Params().Len() != 2 || signature.Results().Len() != 2 || !namedTypeIs(signature.Params().At(0).Type(), "context", "Context") || !namedTypeIs(signature.Params().At(1).Type(), pkg.Path(), item.request) || !namedTypeIs(signature.Results().At(0).Type(), pkg.Path(), item.result) || !types.Identical(signature.Results().At(1).Type(), types.Universe.Lookup("error").Type()) {
violations = append(violations, "invalid facade operation "+item.name)
}
}
return violations
}
func namedTypeIs(typ types.Type, packagePath, name string) bool {
named, ok := types.Unalias(typ).(*types.Named)
return ok && named.Obj().Pkg() != nil && named.Obj().Pkg().Path() == packagePath && named.Obj().Name() == name
}
func checkValidationTypes(pkg *types.Package) []string { func checkValidationTypes(pkg *types.Package) []string {
var violations []string var violations []string
for _, name := range []string{"ValidationCheck", "ValidationFinding", "FileSizeMeasurement", "ValidationError"} { for _, name := range []string{"ValidationCheck", "ValidationFinding", "FileSizeMeasurement", "ValidationError"} {
@@ -189,6 +219,14 @@ func checkImportDirections(packages []listedPackage) error {
var violations []string var violations []string
for _, pkg := range packages { for _, pkg := range packages {
if strings.HasPrefix(pkg.ImportPath, modulePath+"/cmd/") {
for _, imported := range pkg.Imports {
switch imported {
case modulePath + "/internal/gitea", modulePath + "/internal/build", modulePath + "/internal/delivery", modulePath + "/internal/preparation":
violations = append(violations, fmt.Sprintf("command package %s bypasses orchestration facade through %s", pkg.ImportPath, imported))
}
}
}
if !isInternalPackage(pkg.ImportPath) { if !isInternalPackage(pkg.ImportPath) {
continue continue
} }

View File

@@ -30,6 +30,15 @@ func TestRuntimeFacadeCannotDependOnForge(t *testing.T) {
} }
} }
func TestCommandUsesOrchestrationFacade(t *testing.T) {
for _, name := range []string{"gitea", "delivery", "build", "preparation"} {
err := checkImportDirections([]listedPackage{{ImportPath: modulePath + "/cmd/releasekit", Imports: []string{modulePath + "/internal/" + name}}})
if err == nil || !strings.Contains(err.Error(), "bypasses orchestration facade") {
t.Fatalf("dependency=%s error=%v", name, err)
}
}
}
func TestExportedContractBoundaries(t *testing.T) { func TestExportedContractBoundaries(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -279,3 +288,32 @@ func TestCommandInternalCompositionPreservesLibraryBoundaries(t *testing.T) {
}) })
} }
} }
func TestRehearsalOperationsRequireFacadeOwnedRequestsAndResults(t *testing.T) {
valid := `package facade
import "context"
type RehearsalDeliveryRequest struct{}
type RehearsalDeliveryResult struct{}
func DeliverRehearsal(context.Context, RehearsalDeliveryRequest) (RehearsalDeliveryResult, error) { return RehearsalDeliveryResult{}, nil }
type RehearsalRequest struct{}
type RehearsalRecoveryRequest struct{}
type RehearsalResult struct{}
type RehearsalError struct{}
type RehearsalTimeout int64
type RehearsalJob struct{}
type RehearsalWorkflow struct{}
type RehearsalArtifact struct{}
func Rehearse(context.Context, RehearsalRequest) (RehearsalResult,error) {return RehearsalResult{},nil}
func ResumeRehearsal(context.Context, RehearsalRecoveryRequest) (RehearsalResult,error) {return RehearsalResult{},nil}
func CleanupRehearsal(context.Context, RehearsalRecoveryRequest) (RehearsalResult,error) {return RehearsalResult{},nil}
`
pkg := typecheck(t, token.NewFileSet(), modulePath, valid)
if violations := checkRehearsalAPI(pkg); len(violations) != 0 {
t.Fatalf("valid facade: %v", violations)
}
changed := strings.Replace(valid, "func CleanupRehearsal(context.Context, RehearsalRecoveryRequest)", "func CleanupRehearsal(context.Context, RehearsalRequest)", 1)
pkg = typecheck(t, token.NewFileSet(), modulePath, changed)
if violations := checkRehearsalAPI(pkg); !strings.Contains(strings.Join(violations, "\n"), "invalid facade operation CleanupRehearsal") {
t.Fatalf("violations=%v", violations)
}
}

View File

@@ -42,6 +42,7 @@ type Artifact struct {
} }
type Result struct { type Result struct {
Identity releaseidentity.Identity
RepositoryDir string RepositoryDir string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
@@ -63,6 +64,7 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
identity := request.Identity identity := request.Identity
settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets) settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets)
result = Result{ result = Result{
Identity: identity,
RepositoryDir: identity.RepositoryDir, RepositoryDir: identity.RepositoryDir,
ModuleDir: identity.ModuleDir, ModuleDir: identity.ModuleDir,
ModulePath: identity.ModulePath, ModulePath: identity.ModulePath,
@@ -70,10 +72,40 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
Settings: settings, Settings: settings,
Version: identity.Version, Version: identity.Version,
} }
if !versioncontract.ValidStableVersion(identity.Version) { format, prefix := identity.VersionFormat, identity.VersionPrefix
if format == "" {
format, prefix = "semver", "v"
}
validVersion := versioncontract.ValidIdentifier(identity.Version, format, prefix)
if identity.Kind == "diagnostic" {
attempt := strings.TrimPrefix(identity.Version, "releasekit-test-")
parts := strings.Split(identity.Tag, "/")
_, err := hex.DecodeString(attempt)
validVersion = strings.HasPrefix(identity.Version, "releasekit-test-") && len(attempt) == 32 && strings.ToLower(attempt) == attempt && err == nil && len(parts) == 3 && parts[0] == "releasekit-test" && parts[1] != "" && parts[2] == attempt
}
if !validVersion {
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version) return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version)
} }
if identity.RepositoryDir == "" || identity.ModuleDir == "" || identity.ModulePath == "" { if identity.RepositoryDir == "" {
return result, errors.New("build requires a resolved source identity")
}
if identity.Kind == "production" && !identity.GoEnabled {
if len(settings.Targets) != 0 {
return result, errors.New("build targets require Go capability")
}
commit, err := git.CaptureHead(ctx, identity.RepositoryDir)
if err != nil {
return result, fmt.Errorf("read source commit: %w", err)
}
if identity.Commit != "" && identity.Commit != commit {
return result, errors.New("source commit changed before build")
}
result.Identity.Commit = commit
result.CandidateCommit = commit
result.OutputDir = artifact.OutputDirectory(identity.SourceDir, request.OutputDir)
return result, nil
}
if identity.ModuleDir == "" || identity.ModulePath == "" {
return result, errors.New("build requires a resolved module identity") return result, errors.New("build requires a resolved module identity")
} }
if len(settings.Targets) != 0 { if len(settings.Targets) != 0 {
@@ -106,6 +138,10 @@ func buildResolved(ctx context.Context, request Request, remove func(string) err
if err != nil { if err != nil {
return result, fmt.Errorf("read source commit: %w", err) return result, fmt.Errorf("read source commit: %w", err)
} }
if identity.Commit != "" && identity.Commit != commit {
return result, errors.New("source commit changed before build")
}
result.Identity.Commit = commit
result.CandidateCommit = commit result.CandidateCommit = commit
statusBefore, err := git.WorktreeStatus(ctx, repositoryDir) statusBefore, err := git.WorktreeStatus(ctx, repositoryDir)
if err != nil { if err != nil {

View File

@@ -6,11 +6,9 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"go.maximumdirect.net/releasekit/internal/candidate" "go.maximumdirect.net/releasekit/internal/candidate"
"go.maximumdirect.net/releasekit/internal/gotool" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/tempdir" "go.maximumdirect.net/releasekit/internal/tempdir"
) )
@@ -25,21 +23,6 @@ func candidateCallback(spec *Spec, output io.Writer, remove func(string) error)
selected := *spec selected := *spec
selected.Targets = append([]Target(nil), spec.Targets...) selected.Targets = append([]Target(nil), spec.Targets...)
return func(ctx context.Context, captured candidate.Candidate, owner *gotool.Owner) (resultErr error) { return func(ctx context.Context, captured candidate.Candidate, owner *gotool.Owner) (resultErr error) {
moduleSubdir, err := filepath.Rel(captured.RepositoryDir, captured.ModuleDir)
if err != nil {
return fmt.Errorf("resolve captured module path: %w", err)
}
identity := releaseidentity.Identity{
Selection: releaseidentity.Selection{
RepositoryDir: captured.RepositoryDir,
ModuleDir: captured.ModuleDir,
ModuleSubdir: filepath.ToSlash(moduleSubdir),
},
ModulePath: captured.ModulePath,
Version: captured.Version,
Tag: captured.Tag,
NotePath: filepath.ToSlash(filepath.Join(moduleSubdir, "docs", "releases", captured.Version+".md")),
}
temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-") temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-")
if err != nil { if err != nil {
return fmt.Errorf("create temporary candidate build output: %w", err) return fmt.Errorf("create temporary candidate build output: %w", err)
@@ -50,7 +33,7 @@ func candidateCallback(spec *Spec, output io.Writer, remove func(string) error)
} }
}() }()
_, err = BuildResolved(ctx, Request{ _, err = BuildResolved(ctx, Request{
Identity: identity, Identity: captured.Identity,
Spec: selected, Spec: selected,
OutputDir: temporaryDir, OutputDir: temporaryDir,
Output: output, Output: output,

View File

@@ -109,7 +109,7 @@ func TestCandidateBuildCleanupPreservesOutcome(t *testing.T) {
_ = os.RemoveAll(path) _ = os.RemoveAll(path)
return cleanupErr return cleanupErr
}) })
err := callback(ctx, candidate.Candidate{RepositoryDir: identity.RepositoryDir, ModuleDir: identity.ModuleDir, ModulePath: identity.ModulePath, Version: identity.Version, Tag: identity.Tag}, nil) err := callback(ctx, candidate.Candidate{Identity: identity, RepositoryDir: identity.RepositoryDir, ModuleDir: identity.ModuleDir, ModulePath: identity.ModulePath, Version: identity.Version, Tag: identity.Tag}, nil)
if !errors.Is(err, cleanupErr) || removed == "" || !strings.Contains(err.Error(), removed) { if !errors.Is(err, cleanupErr) || removed == "" || !strings.Contains(err.Error(), removed) {
t.Fatalf("candidate cleanup = %q, error = %v", removed, err) t.Fatalf("candidate cleanup = %q, error = %v", removed, err)
} }

View File

@@ -21,6 +21,7 @@ import (
var ErrInvalidVersion = errors.New("invalid stable version") var ErrInvalidVersion = errors.New("invalid stable version")
type Candidate struct { type Candidate struct {
Identity releaseidentity.Identity
RepositoryDir string RepositoryDir string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
@@ -33,6 +34,8 @@ type Candidate struct {
type Request struct { type Request struct {
RepositoryDir string RepositoryDir string
ModuleDir string ModuleDir string
Source *releaseidentity.SourceSpec
BuildTargets bool
Product string Product string
Version string Version string
Validation validation.Settings Validation validation.Settings
@@ -67,7 +70,7 @@ func Check(ctx context.Context, request Request) (Candidate, error) {
// including the note bytes from the captured commit. It does not run checks. // including the note bytes from the captured commit. It does not run checks.
func Capture(ctx context.Context, request Request) (Candidate, error) { func Capture(ctx context.Context, request Request) (Candidate, error) {
captured := Candidate{Version: request.Version} captured := Candidate{Version: request.Version}
if !validStableVersion(request.Version) { if request.Source == nil && !validStableVersion(request.Version) {
return captured, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version) return captured, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)
} }
if strings.TrimSpace(request.Product) == "" { if strings.TrimSpace(request.Product) == "" {
@@ -91,13 +94,20 @@ func Capture(ctx context.Context, request Request) (Candidate, error) {
return captured, 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)
} }
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit) identity, err := releaseidentity.FromCommittedSource(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit, request.Source)
captured.Identity = identity
captured.ModuleDir = identity.ModuleDir captured.ModuleDir = identity.ModuleDir
captured.ModulePath = identity.ModulePath captured.ModulePath = identity.ModulePath
captured.Tag = identity.Tag captured.Tag = identity.Tag
if err != nil { if err != nil {
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return captured, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)
}
return captured, fmt.Errorf("resolve selected module release identity: %w", err) return captured, fmt.Errorf("resolve selected module release identity: %w", err)
} }
if !identity.GoEnabled && request.BuildTargets {
return captured, errors.New("build targets require Go capability")
}
note, err := git.ReadCommitFile(ctx, identity.RepositoryDir, state.commit, identity.NotePath) note, err := git.ReadCommitFile(ctx, identity.RepositoryDir, state.commit, identity.NotePath)
if err != nil { if err != nil {
return captured, fmt.Errorf("read committed release note %q: %w", identity.NotePath, err) return captured, fmt.Errorf("read committed release note %q: %w", identity.NotePath, err)
@@ -115,6 +125,7 @@ func Capture(ctx context.Context, request Request) (Candidate, error) {
} }
captured.Note = string(note) captured.Note = string(note)
captured.Identity.Note = captured.Note
return captured, nil return captured, nil
} }
@@ -128,6 +139,8 @@ func Validate(ctx context.Context, request Request, captured Candidate) error {
if err := validation.Run(ctx, validation.Request{ if err := validation.Run(ctx, validation.Request{
RepositoryDir: captured.RepositoryDir, RepositoryDir: captured.RepositoryDir,
ModuleDir: captured.ModuleDir, ModuleDir: captured.ModuleDir,
SourceDir: captured.Identity.SourceDir,
SourceOnly: !captured.Identity.GoEnabled,
Commit: captured.Commit, Commit: captured.Commit,
Output: request.Output, Output: request.Output,
Settings: request.Validation, Settings: request.Validation,

View File

@@ -14,6 +14,7 @@ import (
"testing" "testing"
"go.maximumdirect.net/releasekit/internal/gotool" "go.maximumdirect.net/releasekit/internal/gotool"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
"go.maximumdirect.net/releasekit/internal/validation" "go.maximumdirect.net/releasekit/internal/validation"
) )
@@ -47,6 +48,27 @@ func TestValidStableVersion(t *testing.T) {
} }
} }
func TestCaptureUsesExplicitModuleSelection(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRoot release.\n")
moduleDir := "components/tool"
writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/tool\n")
writeTestFile(t, repository, moduleDir+"/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nNested release.\n")
gitRun(t, repository, "add", moduleDir)
gitRun(t, repository, "commit", "-m", "add nested module")
captured, err := Capture(context.Background(), Request{
RepositoryDir: repository,
Source: &releaseidentity.SourceSpec{Dir: moduleDir, GoEnabled: true, Publication: "go-module"},
Product: "Example Product", Version: testVersion,
})
if err != nil {
t.Fatal(err)
}
if captured.ModuleDir != filepath.Join(repository, moduleDir) || captured.ModulePath != "example.com/tool" || captured.Tag != moduleDir+"/"+testVersion {
t.Fatalf("captured candidate = %+v", captured)
}
}
func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) { func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n") repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
writeTestFile(t, repository, "guide.md", "# Guide\n[section](#guide)\n") writeTestFile(t, repository, "guide.md", "# Guide\n[section](#guide)\n")

View File

@@ -33,6 +33,7 @@ const (
type Request struct { type Request struct {
RepositoryDir string RepositoryDir string
ModuleDir string ModuleDir string
Source *releaseidentity.SourceSpec
Product string Product string
Version string Version string
ExpectedTag string ExpectedTag string
@@ -40,9 +41,23 @@ type Request struct {
Build *internalbuild.Spec Build *internalbuild.Spec
Prebuilt *internalbuild.Result Prebuilt *internalbuild.Result
Output io.Writer Output io.Writer
Diagnostic *Diagnostic
}
// Diagnostic supplies a verified identity and deterministic temporary note.
type Diagnostic struct {
Identity releaseidentity.Identity
Note string
}
type VerifiedAsset struct {
Name string
Size int64
SHA256 string
} }
type Result struct { type Result struct {
Identity releaseidentity.Identity
RepositoryDir string RepositoryDir string
ModuleDir string ModuleDir string
ModulePath string ModulePath string
@@ -55,6 +70,11 @@ type Result struct {
Pending []AssetIdentity Pending []AssetIdentity
Conflicting []AssetIdentity Conflicting []AssetIdentity
Uncertain []AssetIdentity Uncertain []AssetIdentity
Verified bool
PageID int64
VerifiedAssets []VerifiedAsset
BuildStarted bool
BuildComplete bool
} }
func Deliver(ctx context.Context, request Request) (Result, error) { func Deliver(ctx context.Context, request Request) (Result, error) {
@@ -63,7 +83,7 @@ func Deliver(ctx context.Context, request Request) (Result, error) {
func deliver(ctx context.Context, request Request, remove func(string) error) (result Result, resultErr error) { func deliver(ctx context.Context, request Request, remove func(string) error) (result Result, resultErr error) {
result = Result{State: NotAttempted} result = Result{State: NotAttempted}
if !versioncontract.ValidStableVersion(request.Version) { if request.Diagnostic == nil && request.Source == nil && !versioncontract.ValidStableVersion(request.Version) {
return result, candidate.ErrInvalidVersion return result, candidate.ErrInvalidVersion
} }
if strings.TrimSpace(request.Product) == "" { if strings.TrimSpace(request.Product) == "" {
@@ -85,19 +105,34 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
return result, err return result, err
} }
result.CandidateCommit = commit result.CandidateCommit = commit
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, commit) var identity releaseidentity.Identity
if request.Diagnostic == nil {
identity, err = releaseidentity.FromCommittedSource(ctx, repositoryDir, request.ModuleDir, request.Version, commit, request.Source)
} else {
identity = request.Diagnostic.Identity
if identity.Kind != "diagnostic" || identity.RepositoryDir != repositoryDir || !git.EqualObjectID(identity.Commit, commit) || identity.Tag != request.ExpectedTag {
return result, errors.New("diagnostic identity does not match tagged checkout")
}
}
result.Identity = identity
result.ModuleDir = identity.ModuleDir result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath result.ModulePath = identity.ModulePath
result.Tag = identity.Tag result.Tag = identity.Tag
if err != nil { if err != nil {
if errors.Is(err, versioncontract.ErrInvalidIdentifier) {
return result, candidate.ErrInvalidVersion
}
return result, fmt.Errorf("resolve committed delivery identity: %w", err) return result, fmt.Errorf("resolve committed delivery identity: %w", err)
} }
if !identity.GoEnabled && request.Build != nil && len(request.Build.Targets) != 0 {
return result, errors.New("build targets require Go capability")
}
result.RepositoryDir = identity.RepositoryDir result.RepositoryDir = identity.RepositoryDir
result.ModuleDir = identity.ModuleDir result.ModuleDir = identity.ModuleDir
result.ModulePath = identity.ModulePath result.ModulePath = identity.ModulePath
result.Tag = identity.Tag result.Tag = identity.Tag
if request.ExpectedTag != "" && request.ExpectedTag != 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) return result, fmt.Errorf("expected delivery tag %q does not match selected source tag %q", request.ExpectedTag, identity.Tag)
} }
source, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag) source, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
if err != nil { if err != nil {
@@ -112,12 +147,20 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
if source.TagCommit != commit { if source.TagCommit != commit {
return result, fmt.Errorf("checkout HEAD %s does not match tag %s commit %s", source.Head, identity.Tag, source.TagCommit) 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) var note []byte
if err != nil { if request.Diagnostic == nil {
return result, fmt.Errorf("read release note %q: %w", identity.NotePath, err) note, err = git.ReadCommitFile(ctx, repositoryDir, commit, identity.NotePath)
} if err != nil {
if err := candidate.ValidateReleaseNote(note, request.Product, request.Version); err != nil { return result, fmt.Errorf("read release note %q: %w", identity.NotePath, err)
return result, fmt.Errorf("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", identity.NotePath, err)
}
} else {
note = []byte(request.Diagnostic.Note)
if releaseNoteTitle(string(note)) == "" {
return result, errors.New("diagnostic note requires a title")
}
} }
if request.Prebuilt != nil { if request.Prebuilt != nil {
if err := validateBuildIdentity(identity, commit, request.Prebuilt); err != nil { if err := validateBuildIdentity(identity, commit, request.Prebuilt); err != nil {
@@ -130,6 +173,7 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
build := request.Prebuilt build := request.Prebuilt
if request.Build != nil && len(request.Build.Targets) != 0 { if request.Build != nil && len(request.Build.Targets) != 0 {
result.BuildStarted = true
temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-delivery-build-*") temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-delivery-build-*")
if err != nil { if err != nil {
return result, fmt.Errorf("create temporary delivery build directory: %w", err) return result, fmt.Errorf("create temporary delivery build directory: %w", err)
@@ -150,6 +194,7 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
return result, fmt.Errorf("build delivery assets: %w", err) return result, fmt.Errorf("build delivery assets: %w", err)
} }
build = &built build = &built
result.BuildComplete = true
} }
var assets []artifact.ExpectedAsset var assets []artifact.ExpectedAsset
if build != nil { if build != nil {
@@ -191,6 +236,14 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
result.ReleaseURL = release.URL result.ReleaseURL = release.URL
if len(assets) == 0 { if len(assets) == 0 {
result.State = Complete result.State = Complete
if request.Diagnostic != nil {
result.PageID, result.VerifiedAssets, err = verifyDiagnostic(ctx, request.Backend, identity, string(note), assets)
result.Verified = err == nil
if err != nil {
result.State = Partial
return result, err
}
}
return result, nil return result, nil
} }
inspection, err := inspectRemoteAssets(ctx, request.Backend, release.Handle, assets) inspection, err := inspectRemoteAssets(ctx, request.Backend, release.Handle, assets)
@@ -212,6 +265,14 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r
if result.State == NotAttempted && pageEvidence.Attempted { if result.State == NotAttempted && pageEvidence.Attempted {
result.State = Partial result.State = Partial
} }
if uploadErr == nil && result.State == Complete && request.Diagnostic != nil {
result.PageID, result.VerifiedAssets, err = verifyDiagnostic(ctx, request.Backend, identity, string(note), assets)
result.Verified = err == nil
if err != nil {
result.State = Partial
return result, err
}
}
return result, uploadErr return result, uploadErr
} }
@@ -242,13 +303,19 @@ func validateBuildIdentity(identity releaseidentity.Identity, commit string, bui
if err != nil { if err != nil {
return fmt.Errorf("resolve build repository: %w", err) return fmt.Errorf("resolve build repository: %w", err)
} }
buildModule, err := filepath.Abs(build.ModuleDir) buildModule := ""
if err != nil { if build.ModuleDir != "" {
return fmt.Errorf("resolve build module: %w", err) buildModule, err = filepath.Abs(build.ModuleDir)
if err != nil {
return fmt.Errorf("resolve build module: %w", err)
}
} }
if buildRepository != identity.RepositoryDir || buildModule != identity.ModuleDir || build.ModulePath != identity.ModulePath || build.Tag != identity.Tag || build.CandidateCommit != commit || build.Version != identity.Version { 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") return errors.New("build result does not identify the selected tagged module")
} }
if build.Identity.Kind != identity.Kind || build.Identity.SourceDir != identity.SourceDir || build.Identity.SourceSubdir != identity.SourceSubdir || build.Identity.GoEnabled != identity.GoEnabled || build.Identity.Publication != identity.Publication || build.Identity.VersionFormat != identity.VersionFormat || build.Identity.VersionPrefix != identity.VersionPrefix {
return errors.New("build result does not match the selected source identity")
}
if len(build.Settings.Targets) == 0 { if len(build.Settings.Targets) == 0 {
return nil return nil
} }

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